Make delicious recipes!

Servlet

Programs that add functionality to a web server.

Each request to be handled by a servlet is handled by a separate Java thread within the Web server process. Hence, there are same amount of threads as requests and all these threads/requests share a single copy of the servlet class. This single copy persists between requests.


Before servlets, CGI was used. However, it was non-Java and used a different process for each server request. Hence, it was non-portable and very resource consuming. Also, it lacked other features provided by Java like JDBC and OOPS-based programming.

That’s why now we mostly use servlets instead of CGI


Servlet life-cycle

1) init() : Called once per servlet to initialise it.

2) destroy() : Again called only once per servlet at the end of its life-cycle.

3) service() : Method which handles requests. Each request comes in a separate thread.


Servlet is an interface mandating the implementation of above 3 methods.

GenericServlet is an abstract implementation of servlet. It only has service() method as abstract.

HttpServlet extends GenericServlet and its service() method delegates requests into the following 4 methods:

1) doGet()

2) doPost()

3) doDelete()

4) doPut()



Web Server

Web Server is a tool that runs servlets. It responds to requests from clients for accessing Internet content. Example, Tomcat, JBoss, Glassfish

Servlet container or Web Server does the following:

  1. Waits for HTTP request.

  2. When the servlet is called for the first time, load the servlet class and call its init method.

  3. For each request, construct objects of javax.servlet.ServletRequest and javax.servlet.ServletResponse

  4. If the request is for a static resource, invoke the process method of the StaticResourceProcessor instance, passing the ServletRequest and ServletResponse objects.

  5. If the request is for a servlet, load the servlet class and invoke its service method in a new thread, passing the ServletRequest and ServletResponse objects.

  6. Finally, call destroy method in the servlet when its done processing. Every server has its own algorithms to determine when destroy() should be called.

  7. All servlets are loaded at start-up if the attribute <load-on-startup> is set to true in web.xml file, else they are loaded on demand.




Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal