Overview of Servlets

Servlets represent an extension to the HTTP server. It takes http request as an input and sends the http response to the client as an output. Servlet API provides two packages they are javax.servlet and javax.http.servelt. These packages contain interfaces and classes to deal with generic and http functionality that means you can write a Servlet in java to get http request and send a http response to the client. Client is typically a browser. These interfaces are implemented by Servlet Engines. There are numerous vendors who provide Servlet Engines to work with Servlets, for example Tomcat, weblogic, webshpere etc.

Servlet is loaded into the memory by Servlet Engine and it calls init() method on first request and then onwards only service() method is called for every other request by creating a separate thread for each request and finally destroy() method is called when the Servlet is removed by the Servlet Engine. Service() method can be replaced by doGet() or doPost() method.

Note that this architecture is a multi threaded model which is generally followed in most of the applications. You can even work with single threaded model by implementing SingleThreadModel interface where the Servlet Engine creates a separate Servlet instance for each request.

Key Points

1. Use init() method to cache static data
2. Use StringBuffer rather than using + operator when you concatenate multiple strings
3. Use print() method rather than println() method
4. Use ServletOutputStream rather than PrintWriter to send binary data
5. Initialize the PrintWriter with proper size
6. Flush the data partly
7. Minimize code in the synchronized block
8. Set the content length
9. Release resources in destroy() method.
10. Implement getLastModified() method to use browser cache and server cache
11. Use application server caching facility
12. Use Mixed session mechanisms such as HttpSession with hidden fields
13. Remove HttpSession objects explicitly in your program whenever you finish the task
14. Reduce session time out value as much as possible
15. Use ‘transient’ variables to reduce serialization overhead if your HttpSession tracking mechanism uses serialization process.
16. Disable servlet auto reloading feature.
17. Use thread pool for your servlet engine and define the size as per application requirement.