一、生命周期 init()、service()、destory()

  1. 在第一次创建Servlet的时候通过init()初始化,之后不再执行此方法
  2. 通过service()处理HTTP请求,常用doGet()、doPost()
  3. destory()在Servlet结束时执行
    最后由JVM进行垃圾回收.

二、实现方式 implements Servlet、extends GenericServlet、extends HttpServlet

HttpServlet本身就是通过implements Servlet实现的.


三、代码示例: 通过继承HttpServlet实现Servlet

1、继承HttpServlet

package cn.config;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {
    
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("execute HelloServlet#doGet ...");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("execute HelloServlet#doPost ...");
    }

}

2、web.xml注册Servlet

<servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>cn.config.HelloServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

3、 通过get/post请求http://ip:port/context/hello控制台会打印相对应的代码.

推荐使用postman模拟请求

标签: Java, servlet

添加新评论