006.JavaWebServlet实现的三种方式

1 实现Servlet接口,然后实现接口中的五个方法,代码为:

public class Hello implements Servlet{

     //该函数用于初始化servlet,类似于类的构造函数,该函数只会被调用一次
    public void init(ServletConfig parm1) throws ServletException {
        System.out.println("init it!");
    }

    public ServletConfig getServletConfig() {
        // TODO: Add your code here
        return null;
    }

     //这个函数用于处理业务逻辑
     //当用户每访问servlet时,都会调用
     //req:用于获得客户端(浏览器)信息
     //res:用于向客户端(浏览器)返回信息
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        //从res中得到PrintWriter
        System.out.println("Service it");
        PrintWriter pw = res.getWriter();
        pw.println("Hello world!");
    }

    public String getServletInfo() {
        return "";
    }

     //销毁,释放内存,三种方式会触发destroy
     //1. reload该servlet(webApps) 2. 关闭tomcat 3.关机
    public void destroy() {
        System.out.println("destroy it!");
    }
} 

2 继承GenericServlet,只需要实现一个方法:service

public class HelloGen extends GenericServlet{
    //重写一个方法service即可
    public void service(ServletRequest req, ServletResponse res){
        //返回Hello world, generic
        try{
            PrintWriter pw = res.getWriter();
            pw.println("Hello generic");
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

3 继承HttpServlet,复写doGetdoPost方法

public class HelloHttp extends HttpServlet{
    //处理get请求
    public void doGet(HttpServletRequest req, HttpServletResponse res){
        //业务逻辑
        try{
            PrintWriter pw = res.getWriter();
            pw.println("hello, Http");
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res){
        this.doGet(req,res);    
    }
}

 

posted @ 2021-08-26 16:02  李林林  阅读(61)  评论(0编辑  收藏  举报