What is Servlet in Java?

Servlets are preferred by developers who are working on developing Server side programs and applications as it has platform-independent methods and do not have the limitations of CGI programs. This makes the programs and application fast and efficient. Developers use Servlet to add dynamic content to a web server.

What is Servlet in Java?


Servlets are preferred by developers who are working on developing Server side programs and applications as it has platform-independent methods and do not have the limitations of CGI programs. This makes the programs and application fast and efficient.

Servlets are mostly used to develop interactive Web-based applications that can run on any servlet enabled web server. Servlets use of Java language and a standard framework makes it the first choice for developers to create sophisticated server side extensions.

Developers use Servlet to add dynamic content to a web server. Servlets generally embed HTML inside Java code. Servlet receives a request from user and generates a response and displays it back to the user.

Servlets run entirely inside the Java Virtual Machines (JVM). The applications developed on Servlets are portable, reusable and crash protected.

Servlets can access Java APIs and JDBC API and a HTTP-specific library. All servlets must implement the Servlet interface. doGet() method and doPost() methods are used to handle HTTP-specific services.

Servlets are also used to store and process data.

Lifecycle of Servlets:

  • Servlet container calls the init() method to access and initialize the name and value parameters from the web application. init() method can only be called once.

Every client request is received on a different thread.

  • Servlet container then calls service() method to analyze the request made by client and send them accordingly to the concerned method.
  • At last, Servlet container calls the destroy() method that takes the servlet out of service. destroy() method can only be called once.

Example:

  • A user types a URL in the browser.
  • Browser creates a HTTP request and sends it to server
  • Servlet container on receiving the request from server analyzes it and sends it to a particular servlet
  • Servlet container then calls init() method when the servlet is first loaded into memory
  • Servlet container then calls service() method to process the HTTP request
  • Servlet container calls the service() method every time a HTTP request is made
  • Servlet container calls the destroy() method to release any resources allocated for the servlet
  • Memory allocated can then be garbage collected

Servlets container generates a default page reading "A Servlet Exception Has Occurred" when an error occurs while servlet executes.