Java Servlet

In this article, we will first discuss important concepts related to Java servlets and then we will create a step by step Servlet example.
Check out complete Servlet tutorial at Servlet Tutorial.

What is a Servlet?

A servlet is a Java technology-based Web component, managed by a container, that generates dynamic content. Like other Java technology-based components, servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server. Containers, sometimes called servlet engines, are Web server extensions that provide servlet functionality. Servlets interact with Web clients via a request/response paradigm implemented by the servlet container.

What is a Servlet Container?

The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.
All servlet containers must support HTTP as a protocol for requests and responses, but additional request/response-based protocols such as HTTPS (HTTP over SSL) may be supported.
For example, Apache Tomcat is a good example. As we create Servlet application and deploy on tomcat server.

How Servlet Container Works

  1. A client (e.g., a Web browser) accesses a Web server and makes an HTTP request.
  2. The request is received by the Web server and handed off to the servlet container. The servlet container can be running in the same process as the host Web server, in a different process on the same host, or on a different host from the Web server for which it processes requests.
  3. The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.
  4. The servlet uses the request object to find out who the remote user is, what HTTP POST parameters may have been sent as part of this request, and other relevant data. The servlet performs whatever logic it was programmed with, and generates data to send back to the client. It sends this data back to the client via the response object.
  5. Once the servlet has finished processing the request, the servlet container ensures that the response is properly flushed, and returns control back to the host Web server.

Servlet Life Cycle

There is a Servlet interface in Servlet API which is the central abstraction of the Java Servlet API. All servlets implement this interface either directly, or more commonly, by extending a class that implements the interface. The Servlet interface provides a life cycle methods to initialize a servlet, to service requests, and to remove a servlet from the server.
These Servlet interface methods are central to the life cycle of a servlet.
  1. init( )
  2. service()
  3. destroy( )
Let us consider a typical user scenario to understand when these methods are called.
  1. First, assume that a user enters a Uniform Resource Locator (URL) to a web browser. The browser then generates an HTTP request for this URL. This request is then sent to the appropriate server.
  2. Second, this HTTP request is received by the web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server.
  3. Third, the server invokes the init( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself.
  4. Fourth, the server invokes the service( ) method of the servlet. This method is called to process the HTTP request. You will see that it is possible for the servlet to read data that has been provided in the HTTP request. It may also formulate an HTTP response for the client.
  5. The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients. The service( ) method is called for each HTTP request.
  6. Finally, The servlet is taken out of service, then destroyed with the destroy() method, then garbage collected and finalized.
Below diagram shows a life cycle methods of Servlet interface:

Servlet Example

Let's use  @WebServlet annotation to create a Servlet component in a web application. This annotation is specified on a class and contains metadata about the Servlet being declared.
When we use @WebServlet annotation then deployment descriptor (web.xml file) is not required. While @WebServlet allows the mapping of servlets to occur in the Java code, the deployment descriptor file can still be used to map servlets.  In fact, there are still many valid reasons to have a web.xml file in your Web application.  Providing a list of welcome pages, defining error pages, and giving filters order are things that can only be done in the deployment descriptor.

Create Servlet using @WebServlet Annotation

Following example demonstrates the usage of @WebServlet annotation:
package net.javaguides.servlet.tutorial.httpservlet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/helloworld")
public class HelloWorldExample extends HttpServlet {

    private static final long serialVersionUID = 1 L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter printWriter = resp.getWriter();
        printWriter.print("<html>");
        printWriter.print("<body>");
        printWriter.print("<h1>Hello World HttpServlet Class Example</h1>");
        printWriter.print("<a href=\"http://www.javaguides.net\">Java Guides</a>");
        printWriter.print("</body>");
        printWriter.print("</html>");
        printWriter.close();
    }
}
Here the servlet HelloWorldExample is mapped to the URL pattern /helloworld. When accessing this servlet, it will display below page on the web browser: 
Check out @WebServlet Annotation Example article to know everything about @WebServlet annotation.

Comments

Post a Comment