大多数Web应用都是通过HTTP和客户端进行交互
因此,在Servlet接口中,提供了一个抽象类javax.servlet.http.HttpServlet,它是GenericServlet的子类,专门用于创建应用于HTTP的Servlet
查看HttpServlet类的源代码
首先,从Tomcat的lib文件中,找到Servlet的jar包——servlet-api.jar
查看jar包,使用压缩软件打开jar包,找到HttpServlet.class类文件
查看class文件,直接使用idea打开
代码如下
public abstract class HttpServlet extends GenericServlet {
public HttpServlet() {
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
……
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
……
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
long lastModified;
if (method.equals("GET")) {
lastModified = this.getLastModified(req);
if (lastModified == -1L) {
this.doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader("If-Modified-Since");
} catch (IllegalArgumentException var9) {
ifModifiedSince = -1L;
}
if (ifModifiedSince < lastModified / 1000L * 1000L) {
this.maybeSetLastModified(resp, lastModified);
this.doGet(req, resp);
} else {
resp.setStatus(304);
}
}
} else if (method.equals("HEAD")) {
lastModified = this.getLastModified(req);
this.maybeSetLastModified(resp, lastModified);
this.doHead(req, resp);
} else if (method.equals("POST")) {
this.doPost(req, resp);
} else if (method.equals("PUT")) {
this.doPut(req, resp);
} else if (method.equals("DELETE")) {
this.doDelete(req, resp);
} else if (method.equals("OPTIONS")) {
this.doOptions(req, resp);
} else if (method.equals("TRACE")) {
this.doTrace(req, resp);
} else {
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[]{method};
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(501, errMsg);
}
}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest)req;
response = (HttpServletResponse)res;
} catch (ClassCastException var6) {
throw new ServletException("non-HTTP request or response");
}
this.service(request, response);
}
代码说明
可以发现,HttpServlet主要有两大功能
一、根据用语请求方式的不同,定义相应的doXXX()方法,处理用户请求,比如
与GET请求方式对应的doGet()方法
与POST请求方式对应的doPost()方法
二、通过service()方法,将HTTP请求和响应分别转为HttpServletRequest和HttpServletResponse类型的对象
注意
由于,HttpServlet类在重写的service()方法中,为每一个HTTP请求方式,都定义了对应的doXXX()方法,因此,当定义的类继承HttpServlet之后,只需要根据请求方式,重写对应的doXXX()方法,即可,而不需要重写service()方法