[java]
1. protected void service(HttpServletRequest req, HttpServletResponse resp)
2. throws ServletException, IOException {
3.
4. String method = req.getMethod();
5.
6. if (method.equals(METHOD_GET)) {
7. long lastModified = getLastModified(req);
8. if (lastModified == -1) {
9. // servlet doesn't support if-modified-since, no reason
10. // to go through further expensive logic
11. doGet(req, resp);
12. } else {
13. long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
14. if (ifModifiedSince < (lastModified / 1000 * 1000)) {
15. // If the servlet mod time is later, call doGet()
16. // Round down to the nearest second for a proper compare
17. // A ifModifiedSince of -1 will always be less
18. maybeSetLastModified(resp, lastModified);
19. doGet(req, resp);
20. } else {
21. resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
22. }
23. }
24.
25. } else if (method.equals(METHOD_HEAD)) {
26. long lastModified = getLastModified(req);
27. maybeSetLastModified(resp, lastModified);
28. doHead(req, resp);
29.
30. } else if (method.equals(METHOD_POST)) {
31. doPost(req, resp);
32.
33. } else if (method.equals(METHOD_PUT)) {
34. doPut(req, resp);
35.
36. } else if (method.equals(METHOD_DELETE)) {
37. doDelete(req, resp);
38.
39. } else if (method.equals(METHOD_OPTIONS)) {
41.
42. } else if (method.equals(METHOD_TRACE)) {
43. doTrace(req,resp);
44.
45. } else {
46. //
47. // Note that this means NO servlet supports whatever
48. // method was requested, anywhere on this server.
49. //
50.
51. String errMsg = lStrings.getString("http.method_not_implemented");
52. Object[] errArgs = new Object[1];
53. errArgs[0] = method;
54. errMsg = MessageFormat.format(errMsg, errArgs);
55.
56. resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
57. }
58. }
当然,这个service()方法也可以被子类置换掉。
下面给出一个简单的Servlet例子:

从上面的类图可以看出,TestServlet类是HttpServlet类的子类,并且置换掉了父类的两个方法:doGet()和doPost()。
[java]
1. public class TestServlet extends HttpServlet {
2.
3. public void doGet(HttpServletRequest request, HttpServletResponse response)
4. throws ServletException, IOException {
5.
6. System.out.println("using the GET method");
7.
8. }
9.
10. public void doPost(HttpServletRequest request, HttpServletResponse response)
11. throws ServletException, IOException {
12.
13. System.out.println("using the POST method");
14. }
15