doGet or doPost method invocation

3.3k views Asked by At

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

There are 4 answers

0
Semih Eker On BEST ANSWER

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;

0
Miron Balcerzak On

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

0
Chetan On

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

0
Serge Ballesta On

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.