doGet or doPost method invocation [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 12:52:58

问题


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 .


回答1:


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;




回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/27292471/doget-or-dopost-method-invocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!