httpServlet是和Http协议相关的Servlet。
httpServlet是继承自GenericServlet,所以GenericServlet的所有方法HttpServlet都有。
HttpServlet的主要方法(内部已经实现,不用程序员自己写)
public abstract class HttpServlet extends GenericServlet {
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
……
}
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest) req; / / req 强制转换 为和Http协议相关的request
response = (HttpServletResponse) res; / /res 强制转换 为和Http协议相关的response
} catch (ClassCastException e) {
throw new ServletException("non-HTTP request or response");
}
service(request, response); / / HttpServlet的protected service()方法
}
……
}
理解: service(ServletRequest req,ServletResponse res) ---req/res类型强制转换为Httpreq/Httpres-->
service(HttpServletRequest req,HttpServletResponse resp) -----> doGet()或者doPost()方法。
// ---------------------------------------------------------------------
程序员写自己的Servlet继承自Servlet,重写doGet()或者doPost()方法即可。
在HttpServlet的service(HttpServletRequest,HttpServletResponse)方法会去判断当前请求是GET还是POST:
如果是GET请求,那么会去调用本类的doGet()方法
如果是POST请求会去调用doPost()方法,这说明我们在子类中去覆盖doGet()或doPost()方法即可。