HttpServlet
由于大多数Web应用都是通过HTTP协议和客户端进行交互,因此,在Servlet 接口中,提供了一个抽象类javax.servlet.http.HttpServlet,它是GenericServlet的子类,专门用于创建应用于HTTP协议的Servlet。为了大家可以更好地了解HttpServlet,接下来,我们看一下HttpServlet类的源代码片段,具体如下:
1 public abstract class HttpServlet extends GenericServlet {
2 protected void doGet(HttpServletRequest req,
HttpServletResponse resp)
3 throws ServletException, IOException
4 {
5 ......
6 }
7 protected void doPost(HttpServletRequest req,
HttpServletResponse resp)
8 throws ServletException, IOException {
9 ......
10 }
11 protected void service(HttpServletRequest req,
HttpServletResponse resp)
12 throws ServletException, IOException {
13 String method = req.getMethod();
14 if (method.equals(METHOD_GET)) {
15 long lastModified = getLastModified(req);
16 if (lastModified == -1) {
17 // servlet doesn't support if-modified-since, no reason
18 // to go through further expensive logic
19 doGet(req, resp);
20 } else {
21 long ifModifiedSince =req.getDateHeader(HEADER_IFMODSINCE);
22 if (ifModifiedSince < (lastModified / 1000 * 1000)) {
23 // If the servlet mod time is later, call doGet()
24 // Round down to the nearest second for a proper compare
25 // A ifModifiedSince of -1 will always be less
26 maybeSetLastModified(resp, lastModified);
27 doGet(req, resp);
28 } else {
29 resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
30 }
31 }
32 } else if (method.equals(METHOD_HEAD)) {
33 long lastModified = getLastModified(req);
34 maybeSetLastModified(resp, lastModified);
35 doHead(req, resp);
36 } else if (method.equals(METHOD_POST)) {
37 doPost(req, resp);
38 } else if (method.equals(METHOD_PUT)) {
39 doPut(req, resp);
40 } else if (method.equals(METHOD_DELETE)) {
41 doDelete(req, resp);
42 } else if (method.equals(METHOD_OPTIONS)) {
43 doOptions(req,resp);
44 } else if (method.equals(METHOD_TRACE)) {
45 doTrace(req,resp);
46 } else {
47 String errMsg =
lStrings.getString("http.method_not_implemented");
48 Object[] errArgs = new Object[1];
49 errArgs[0] = method;
50 errMsg = MessageFormat.format(errMsg, errArgs);
51 resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
52 }
53 }
54 public void service(ServletRequest req, ServletResponse res)
55 throws ServletException, IOException {
56 HttpServletRequest request;
57 HttpServletResponse response;
58 try {
59 request = (HttpServletRequest) req;
60 response = (HttpServletResponse) res;
61 } catch (ClassCastException e) {
62 throw new ServletException("non-HTTP request or response");
63 }
64 service(request, response);
65 }
66 }
通过分析HttpServlet的源代码片段,发现HttpServlet主要有两大功能,第一是根据用户请求方式的不同,定义相应的doXxx()方法处理用户请求。例如,与GET请求方式对应的doGet()方法,与POST方式对应的doPost()方法。第二是通过service()方法将HTTP请求和响应分别转为HttpServletRequest和HttpServletResponse类型的对象。
需要注意的是,由于HttpServlet类在重写的service()方法中,为每一种HTTP请求方式都定义了对应的doXxx()方法,因此,当定义的类继承HttpServlet后,只需根据请求方式,重写对应的doXxx()方法即可,而不需要重写service()方法。