doGet or doPost method invocation [duplicate]

2019-08-02 19:58发布

This question already has an answer here:

How does the servlet container know whether to call doGet or doPost method.

When I make a get request doGet is called, When I make a post request doPost is called , but where is the logic to decide this .

4条回答
beautiful°
2楼-- · 2019-08-02 20:25

The logic is in the HTTP protocol and its management by the servlet container (Tomcat, Glassfish, Jetty, ...)

The first word of the request (at the TCP level) is the HTTP verb, generally GET or POST but it can be DELETE, PUT, OPTIONS, HEAD, TRACE,...

The servlet container call the service method of the servlet, but the default implementation of HttpServlet.service method contains the logic to dispatch to the proper method. Extract from the Javadoc :

public void service(ServletRequest req,
                ServletResponse res)
         throws ServletException,
                java.io.IOException

Dispatches client requests to the protected service method. There's no need to override this method.

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.

查看更多
Evening l夕情丶
3楼-- · 2019-08-02 20:28

Request Method is a standard HTTP/1.1 token, which is sent as part of request headers

Please refer to:- http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html

查看更多
Evening l夕情丶
4楼-- · 2019-08-02 20:44

You never really call doGet() or doPost() (the service() method will, and it is called by the Web container as you read in the lifecycle).

The service() method detects the HTTP method used and delegates to doGet(), doPost() and other methods which process HTTP requests in a HTTPServlet. It also encapsulates the ServletRequest and ServletResponse objects in HttpServletRequest and HttpServletResponse objects which contain additional context data from the HTTP headers.

Tahnks to @helderdarocha.

For more;

查看更多
你好瞎i
5楼-- · 2019-08-02 20:47

javax.servlet.http.HttpServlet.service(HttpServletRequest req, HttpServletResponse resp) contains the logic for that.

查看更多
登录 后发表回答