[需要补充]javaEE中servlet方法service与doXXX的关系

刚开始很模糊他们的关系,不清楚

service

protected void service(HttpServletRequest req,
                       HttpServletResponse resp)
                throws ServletException,
                       java.io.IOException
Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. This method is an HTTP-specific version of the Servlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) method. There's no need to override this method.
Parameters:
req - the HttpServletRequest object that contains the request the client made of the servlet
resp - the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
java.io.IOException - if an input or output error occurs while the servlet is handling the TRACE request
ServletException - if the request for the TRACE cannot be handled
See Also:
Servlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
查看源代码:反编译工具打开j2ee13.jar,定位到javax.servlet.http.HttpServlet,可以看到service的代码
  protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    long lastModified;
    String method = req.getMethod();

    if (method.equals("GET")) {
      lastModified = getLastModified(req);
      if (lastModified == -1L)
      {
        doGet(req, resp);
      } else {
        long ifModifiedSince = req.getDateHeader("If-Modified-Since");
        if (ifModifiedSince < lastModified / 1000L * 1000L)
        {
          maybeSetLastModified(resp, lastModified);
          doGet(req, resp);
        } else {
          resp.setStatus(304);
        }
      }
    }
    else if (method.equals("HEAD")) {
      lastModified = getLastModified(req);
      maybeSetLastModified(resp, lastModified);
      doHead(req, resp);
    }
    else if (method.equals("POST")) {
      doPost(req, resp);
    }
    else if (method.equals("PUT")) {
      doPut(req, resp);
    }
    else if (method.equals("DELETE")) {
      doDelete(req, resp);
    }
    else if (method.equals("OPTIONS")) {
      doOptions(req, resp);
    }
    else if (method.equals("TRACE")) {
      doTrace(req, resp);
    }
    else
    {
      String errMsg = lStrings.getString("http.method_not_implemented");
      Object[] errArgs = new Object[1];
      errArgs[0] = method;
      errMsg = MessageFormat.format(errMsg, errArgs);

      resp.sendError(501, errMsg);
    }
  }
结论:当客户端请求服务器servlet,request对象封装了请求的数据,servlet通过service方法通过请求方式的不同(get,post...)来跳转(dispacher)到对应的doXXX方法。
原文地址:https://www.cnblogs.com/westward/p/5216900.html