26 Java Servlets – Introduction

Dr M. Vijayalakshmi

    Server-side Programming

 

The programs that are written and executed in the server side are called Server-side programs. The Server-side program receives the data from the Web Server, processes the data and returns the output back to the web Server which will be given to the Web Browser. The Web Browser receives the data and presents the data on the document. The Server- side programs can be written in any language and the current technologies include ASP, JSP and soon.

 

What is Servlet?

 

A Servlet is like an Applet, but executes on the server side. Servlets are platform independent server-side software components. It is written in Java, which dynamically extends the functionality of a server. A servlet executes on a Java-enabled server.

 

How does it work?

 

The steps involved in the working of a Servlet are:

 

Step 1: Client sends a request to server.

Step 2: Server starts a Servlet.

Step 3: Servlet computes a result for server and does not quit.

Step 4: Server returns response to client.

Step 5: Another client sends a request.

Step 6: Server calls the Servlet again.

    Servlets vs. CGI scripts

 

Advantages:

 

CGI means every time there’s client request, HTTP server creates new instance of process to serve this request. Running a Servlet does not require creating a separate process each time. A servlet stays in memory, so it doesn’t have to be reloaded each time. There is only one instance handling multiple requests, not a separate instance for every request. If untrusted servlets, they can run in a “sandbox”.

 

Disadvantage:

 

There is less choice of languages, when compared to CGI scripts. CGI scripts can be in any language.

 

Tomcat

 

Tomcat is the Servlet Engine than handles Servlet requests for Apache. Tomcat is a “helper application” for Apache. It acts as a “servlet container”. Apache can handle many types of web services. Apache can be installed without Tomcat. Tomcat can be installed without Apache. It is easier to install Tomcat standalone than as part of Apache. By itself, Tomcat can handle web pages, servlets, and JSP. Apache and Tomcat are open source (and therefore free) software .

 

The Servlet API

 

To build Servlets, we need two packages in Java that contain the classes and interfaces.

javax.servlet

javax.servlet.http

These packages are not part of Java core packages, so they are not included in the Java Software Development Kit.

 

The Servlet API consists of packages such as javax.servlet and javax.servlet.http.

1.  javax.servlet package contains interfaces like:

  • Servlet Interface – Declares life cycle methods for a servlet.
  • ServletRequest Interface – Used to read data from a client request.
  • ServletResponse Interface – Used to write data to a client response.
  • ServletContext Interface – Enables servlets to log events and access information about their environment.
  • ServletConfig Interface – Allows servlets to get initialization parameters.
  1. javax.servlet.http package contains interfaces like:
  • HttpServletRequest Interface – Enables servlets to read data from an HTTP request
  • HttpServletResponse Interface – Enables servlets to write data to an HTTP response.
  • HttpSession Interface – Allows session data to be read and written

     The Servlet Interface

 

A servlet is any class that implements the javax.servlet.Servlet interface. The API provides two abstract classes that implement the Servlet interface called GenericServlet and HttpServlet.

 

In practice, most servlets extend the javax.servlet.http.HttpServlet class. Some servlets extend javax.servlet.GenericServlet instead.

 

The Servlet Interface consists of the following methods such as:

  • public void init(ServletConfig)
  • public void service(request, response)
  • public void destroy()
  • public ServletConfig getServletConfig()
  • public String getServletInfo()

    Note: Servlets, like Applets, usually lack a main method, but must implement or override certain other methods.

 

The ServletRequest Interface

 

The various methods defined in the ServletRequest Interface are shown in Table 28.1.

 

 

The ServletResponse Interface

 

The various methods defined in the ServletResponse interface are shown in Table 28.2.

 

 

The ServletContext Interface

 

The various methods defined in the ServletContext interface are shown in Table 28.3.

 

 

The HttpServletRequest Interface

 

The various methods defined in the HttpServletRequest interface are shown in Table 28.4.

 

 

The HttpServletResponse Interface

 

The various methods defined in the HttpServletResponseinterface are shown in Table 28.5.

 

 

The HttpSession Interface

 

The various methods defined in the HttpSession interface are shown in Table 28.6.

 

 

    GenericServlet

 

A GenericServlet defines a generic, protocol-independent Servlet. It gives a blueprint and makes writing Servlet easier. GenericServlet provides simple versions of the lifecycle methods called init() and destroy() and of the methods in the ServletConfig interface. To write a generic servlet, it is sufficient to override the abstract service method.public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException.Here ServletRequest and ServletResponse provides access to generic server requests and response.

 

HttpServlet

 

A HttpServlet class is extended to add HTTP-specific functionality to Servlets. It is an abstract class that extends GenericServlet class. Web-based servlets typically extend the class HttpServlet.HttpServlet overrides the service()method and defines other methods like doGet() and doPost(). It provides additional methods that are called by the service() method automatically. Both methods throw ServletException and IOException.Methods of most concern in this class are:

  • protected void doGet(HttpServletRequest, HttpServletResponse)
  • protected void doPost(HttpServletRequest, HttpServletResponse)

    Life Cycle of Servlet

 

The Servlet lifecycle starts with the initiation of the Servlet where an instance of a Servlet is created. Then the Servlet is initialized with the control parameters in the init() method. When the servlet has a request the service() method is called where the client request is processed. When the Web container is closed, the servlets are destroyed by calling the destroy() method and the Servlet is marked for garbage collection.

 

•  Instantiation – Web container creates an instance.

•  Initialization – container calls the instance’s init(). It initializes a Servlet.

• Service – If container has request, then it calls the service() method. This method processes a client’s request.

• Destroy – before reclaiming the memory (destroying the servlet), the container calls the destroy() method. This method terminates a Servlet.

• Unavailable – instance is destroyed and marked for GC.

Description of the Methods

init() Method

When a servlet is first started up, its init(ServletConfig config) method is called.

public void init(ServletConfig config) throws ServletException

This method is called once when the Servlet is loaded into the Servlet engine, before the Servlet is asked to process its first request and it should perform any necessary initializations.

service() Method

Every servlet request results in a call to service(ServletRequest request, ServletResponse response).

   public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException

This method is called to process a request. It can be called zero, one or many times until the servlet is unloaded. Multiple threads (one per request) can execute this method in parallel so it must be thread safe.

destroy() Method

When the servlet is shut down, destroy() is called.

public void destroy()

This method is called once just before the Servlet is unloaded and taken out of service.

 

Architecture Diagram

 

First the HTTP requests coming to the server are delegated to the Servlet container. The Servlet container loads the Servlet before invoking the service() method. Then the Servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the Servlet. This is shown in Figure 28.1.

 

HTTP Requests

 

When a request is submitted from a Web page, it is almost always a GET or a POST request.

The HTTP <form> tag has an attribute action, whose value can be “get” or “post”. The “get” action results in the form information being put after a ‘?’ in the URL.

 

HTTP Requests

 

When a request is submitted from a Web page, it is almost always a GET or a POST request.

The HTTP <form> tag has an attribute action, whose value can be “get” or “post”. The “get” action results in the form information being put after a ‘?’ in the URL.

 

Example

 

http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q=servlets

 

The & separates the various parameters. Only a limited amount of information can be sent this way whereas “put” can send large amounts of information.

 

The service method dispatches the following kinds of requests such as DELETE, GET, HEAD, OPTIONS, POST, PUT, and TRACE.

 

A GET request is dispatched to the doGet(HttpServletRequest request, HttpServletResponse response) method.

 

A POST request is dispatched to the doPost(HttpServletRequest request, HttpServletResponse response) method.

 

These are the two methods we will usually override. Methods doGet and doPost typically do the same thing, so usually you do the real work in one, and have the other just call it.

 

public void doGet(HttpServletRequest request, HttpServletResponse response) {

doPost(request, response);

}

 

Summary

In this module, we have discussed about the purpose of Servlets used to create web applications. This section also explains about the architecture and lifecycle of Servlets. Further, it gives an insight about the Servlet API, that provides many interfaces and classes, which is deployed on the server to create dynamic web pages.

http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q=servlets

The & separates the various parameters. Only a limited amount of information can be sent this way whereas “put” can send large amounts of information.

The service method dispatches the following kinds of requests such as DELETE, GET, HEAD, OPTIONS, POST, PUT, and TRACE.

A GET request is dispatched to the doGet(HttpServletRequest request, HttpServletResponse response) method.

A POST request is dispatched to the doPost(HttpServletRequest request, HttpServletResponse response) method.

These are the two methods we will usually override. Methods doGet and doPost typically do the same thing, so usually you do the real work in one, and have the other just call it.

public void doGet(HttpServletRequest request, HttpServletResponse response) {

doPost(request, response);

}

 

Summary

 

In this module, we have discussed about the purpose of Servlets used to create web applications. This section also explains about the architecture and lifecycle of Servlets. Further, it gives an insight about the Servlet API, that provides many interfaces and classes, which is deployed on the server to create dynamic web pages.

 

Web Links