Servlet程序创建的几种方式

方式1. 创建Servlet的实现类,并实现HttpServlet接口

1.1 创建实现类

1.2 实现HttpServlet接口,并手动创建POST与GET请求分发处理

public class ServletTest1 extends HttpServlet {
          
   
    
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
          
   
        //向下强制转换为HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) req;
        //调用getMethod()方法, 获取请求分发的类型
        String method = request.getMethod();
        if ("GET".equals(method)){
          
   
            doGet();
        }else if ("POST".equals(method)){
          
   
            doPost();
        }
    }
    public void doGet(){
          
   
        System.out.println("手动配置Get请求的分发");
    }
    public void doPost(){
          
   
        System.out.println("手动配置Post请求的分发");
    }
}

方式2. 自动创建Servlet程序的实现类

2.1 在Web工程的包下, 右键New > Servlet 2.2 新建Servlet的实现类

别名: 是在web.xml使用的 2.3 创建好后会自动请求的分发方法

@WebServlet(name = "ServletTest2", value = "/ServletTest2")
public class ServletTest2 extends HttpServlet {
          
   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
   
        System.out.println("Get请求");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
   
        System.out.println("Post请求");
    }
}

2.4 配置web.xml信息

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!-- servlet标签,给Tomcat配置一个servlet程序-->
    <servlet>
        <!--servlet-name给servlet起一个别名(一般是类名)-->
        <servlet-name>ServletTest2</servlet-name>
        <!--servlet-class是servlet程序的全类名-->
        <servlet-class>com.example.servlet.ServletTest2</servlet-class>
    </servlet>

    <!--servlet-mapping标签给servlet程序配置访问地址. 这里的名字需要跟上面的servlet-name名字一至-->
    <servlet-mapping>
        <!--servlet-name标签是告诉服务器,我当前配置的地址是给那个程序使用的-->
        <servlet-name>ServletTest2</servlet-name>
        <!--url-pattern标签配置访问地址
            / 斜杠在服务器解析的时候,表示为 http://ip:port/工程路径/
            hello 表示配置访问servlet的路径: http://ip:port/工程路径/hello, 可以将路径映射到servlet.ServletTest的实例化对象-->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>
经验分享 程序员 微信小程序 职场和发展