Servlet的三种创建方式

实现javax.servlet.Servlet接口

public class ServletDemo implements Servlet{
    //Servlet生命周期的方法
    //在servlet第一次被访问时调用
    //实例化
    public ServletDemo(){
        
    }
    //Servlet生命周期的方法
    //在servlet第一次被访问时调用
    //初始化
    public void init(ServletConfig arg0) throws ServletException {
        
        
    }
    //Servlet生命周期的方法
    //服务
    //每次访问时都会被调用
    public void service(ServletRequest arg0, ServletResponse arg1)
            throws ServletException, IOException {
        
    }
    
    //Servlet生命周期的方法
    //销毁
    public void destroy() {
        
    }

    public ServletConfig getServletConfig() {
        
        return null;
    }

    public String getServletInfo() {
        
        return null;
    }

继承javax.servet.GenericServlet类(适配器模式)

public class ServletDemo extends GenericServlet{

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1)
            throws ServletException, IOException {
        
    }

}

继承javax.servlet.http.HttpServlet类(模板方法设计模式)

public class ServletDemo3 extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
    }
    
}

注:解决线程安全问题的最佳办法,不要写全局变量,而写局部变量。

Last modification:February 5, 2018
If you think my article is useful to you, please feel free to appreciate