How Servlet Works?


It is critical to find out how the servlet works for information about the servlet well. Here, we're going to get the inner element approximately the primary servlet program.

The server assessments if the servlet is asked for the primary time.

If yes, web container does the subsequent tasks:

  • load of servlet classes.
  • instantiates the servlet class.
  • calls the init technique passing the ServletConfig item


  • calls the carrier technique passing request and reaction gadgets

The web container calls the distroy technique when it wishes to do away with the servlet along with at time of preventing server or undeploying the project.

How does the web Container hold the servlet request?

The web container is accountable to address the request. Let's see the way it handles the request.

  • maps the request with the servlet withinside the net.xml file.
  • makes request and reaction gadgets for this request
  • calls the carrier technique at the thread
  • The public carrier technique internally calls the covered carrier technique
  • The covered carrier technique calls the doGet technique relying on the form of request.
  • The doGet technique generates the reaction and it's miles exceed the client.
  • After sending the reaction, the net field deletes the request and reaction gadgets. The thread is contained withinside the thread pool or deleted relies upon at the server implementation.

What is written withinside the public carrier technique?

The public carrier technique transforms the ServletRequest item into the HttpServletRequest kind and ServletResponse item into the HttpServletResponse kind. Then, call the carrier technique passing those gadgets. Let's see the inner code:

public void service(ServletRequest req, ServletResponse res)  

        throws ServletException, IOException  
        HttpServletRequest request;  
        HttpServletResponse response;  
            request = (HttpServletRequest)req;  
            response = (HttpServletResponse)res;  
        catch(ClassCastException e)  
            throw new ServletException("non-HTTP request or response");  
        service(request, response);  

Inside the protected Service Method What is Written Let's See?

Checking the type of request is done by protected service Method. And if the request type is get, it calls doget way, if request type is post then, it calls do post method, and So on. The internal codes are given below:

protected void service(HttpServletRequest req, HttpServletResponse resp)  

        throws ServletException, IOException  
        String method = req.getMethod();  
            long lastModified = getLastModified(req);  
            if(lastModified == -1L)  
                doGet(req, resp);  
    //rest of the code