Servlet个人实操笔记(一)

2022/7/25 6:52:56

本文主要是介绍Servlet个人实操笔记(一),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

通过继承HttoServlet实现Servlet程序

一般在实际项目开发中,都是继承HttpServlet类的方式去实现Servlet程序

1、编写一个类继承HttpServlet类
2、根据业务需要重写doGet或doPost方法
3、到web.xml中配置Servlet程序的访问地址

test_1.java代码如下:

package com.servletlearning.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class test_1 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("test_1的doGet方法");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("test_1的doPost方法");
    }
}

test.html文件代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="http://localhost:8080/helloword_war_exploded/test_1" method="get">
        <input type="submit">
    </form>
</body>
</html>

运行结果:

点击提交后,控制台显示对doGet方法的调用:

ServletContext类

什么是ServletContext

  • ServletContext是一个接口,他表示Servlet上下文对象
  • 一个web工程只有一个ServletContext对象实例
  • ServletContext对象是一个域对象

域对象:是可以 像Map一样存取数据的对象,这里“域”指的是存取数据的操作范围。

ServletContext类的4个作用

  • 获取web.xml中配置的上下文参数context-param
  • 获取当前的工程路径,格式:/工程路径
  • 获取工程部署后在服务器硬盘上的工程路径
  • 像Map一样存取数据

java class代码如下:

public class ContextServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        * 获取web.xml中配置的上下文参数context-param
        ServletContext context = getServletConfig().getServletContext();

        System.out.println("context-param参数username的值是:"+context.getInitParameter("username"));
        System.out.println("context-param参数password的值是:"+context.getInitParameter("password"));
//        * 获取当前的工程路径,格式:/工程路径
        System.out.println("当前工程路径:"+context.getContextPath());
//        * 获取工程部署后在服务器硬盘上的绝对路径
        //    / 斜杠被服务器解析地址为:http://ip:端口号/工程名/    映射到代码的web目录
        System.out.println("工程部署的绝对路径为:"+context.getRealPath("/"));
    }
}

运行结果如下所示:

注意:init-param只能由ServletConfig对象获取, context-param只能由ServletContext对象获取



这篇关于Servlet个人实操笔记(一)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程