HttpServlet类型介绍

2022-09-14 20:50:36 浏览数 (1)

一、HttpServlet概述

HttpServlet类是GenericServlet的子类,它提供了对HTTP请求的特殊支持,所以通常我们都会通过继承HttpServlet来完成自定义的Servlet。

二、HttpServlet覆盖了service()方法

HttpServlet类中提供了service(HttpServletRequest,HttpServletResponse)方法,这个方法是HttpServlet自己的方法,不是从Servlet继承来的。

在HttpServlet的service(ServletRequest,ServletResponse)方法中会把ServletRequest和ServletResponse强转成HttpServletRequest和HttpServletResponse,然后调用service(HttpServletRequest,HttpServletResponse)方法,这说明子类可以去覆盖service(HttpServletRequest,HttpServletResponse)方法即可,这就不用自己去强转请求和响应对象了。

其实子类也不用去覆盖service(HttpServletRequest,HttpServletResponse)方法,因为HttpServlet还要做另一步简化操作,下面会介绍。

HttpServlet.java

代码语言:javascript复制
public abstract class HttpServlet extends GenericServlet {
    protected void service(HttpServletRequest req, 
                           HttpServletResponse resp)
        throws ServletException, IOException {
        //根据request对象是GET请求还是POST请求,然后去调用
        //doGet方法或者doPost方法
        /*
        	if(req.getMethod=="GET"){
        		doGet(req,resp);
        	}
        	else{
        		doPost(req,resp);
        	}
        */
	}
    @Override
    public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException {

        HttpServletRequest  request;
        HttpServletResponse response;

        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) res;
         } catch (ClassCastException e) {
            throw new ServletException("non-HTTP request or response");
        }
        service(request, response); 
	}
	……
}

三、doGet()和doPost()

在HttpServlet的service(HttpServletRequest,HttpServletResponse)方法会去判断当前请求是GET还是POST,如果是GET请求,那么会去调用本类的doGet()方法,如果是POST请求会去调用doPost()方法,这说明我们在子类中去覆盖doGet()或doPost()方法即可。

代码语言:javascript复制
public class AServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, 
                      	HttpServletResponse response)
						throws ServletException, IOException {
		System.out.println("hello doGet()...");
	}
}
代码语言:javascript复制
public class BServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, 
                       	HttpServletResponse response)
						throws ServletException, IOException {
		System.out.println("hello doPost()...");
	}
}

0 人点赞