Definition

  • Servlets are the Java programs that runs on the Java-enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response, then send response back to the web server. 
  • A servlet is a class of Java programming language, used to extend the capabilities of
    servers, that host applications accessed via a request-response programming model.
  • servlet is simply a class which responds to a particular type of network request, most commonly an HTTP request.

Features

  • Servlets can respond to any type of request coming from clients, they are commonly used to extend the applications hosted by web servers.
  • Java Servlet technology also defines HTTP-specific servlet classes.
  • The javax.servlet and java.servlet.http packages provide interfaces and classes for writing servlets program.
  • All servlets must implement the Servlet interface, which defines/contains life-cycle methods.
  • When implementing a generic service, we can use or extend the GenericServlet class
    provided with the Java Servlet API.
  • The HttpServlet class provides methods, such as do get and do Post, for handling HTTP-specific services.
  • Servlets work on the server-side i.e. Servlets is the utility of Java used for server side-programming.
  • Servlets are programs that run on servers, such as a web server. we all do Net Surfing and well known the data on which the web is submitted and we get the respond accordingly. On web pages, the data is retrieved from the corporate databases, which should be secure. For these kinds of operations we can use servlets.
  • Servlets run in a servlet container which handles the networking side. One of the best-known open source servlet containers is Tomcat.

Types

  • Two types – 
    • Generic servlets :-
      • Extend javax.servlet.GenericServlet.
      • Protocol independent.
      • It is a base class servlet from which all other Servlets are derived.
      • Supports for HTTP, FTP and SMTP protocols.
      • It implements the Servlet and ServletConfig interface.
    • HTTP servlets :-
      • Extend javax.servlet.HttpServlet.
      • Have built-in HTTP protocol support and are more useful in a Sun Java System Web Server environment.

Advantages

  • The advantages of Servlet are as follows : –
    • Servlets show better performance because it uses a separate thread for each request, not process.
    • Servlets provide a way to generate dynamic documents that is both easier to write and faster to run.
    • Servlet enables easy portability across Web Servers due to it consists of Java code.
    • Since, servlets uses java concept hence JVM manages Servlets activities, hence servlets represents Robustness and scalability and need not to worry about the memory leak, garbage collection, etc.
    • Servlets are secure entity because it consists of java language.
    • Servlet can communicate with different servlet and servers.
    • Since all web applications are stateless protocol, servlet uses its own API to maintain  session.
    • Provides all the powerful features of JAVA.

    Disadvantages

    • Designing of servlet is difficult and slows down the application.
    • Writing complex business logic makes the application difficult to understand.
    • It needs Java Runtime Environment on the server to run servlets.
    • Servlet is a mixture of java skills and web related HTML skills, because we have to write the business logic in java and for presentation you should the HTML, so the role based development is missing in pure servlet. The developer who is writing servlet should know java and HTML both.
    • It is very difficult for enhancement and bug fixing in servlets.
    •  It requires more steps to develop, thus servlet takes too long time for development.

      Servlets Life Cycle

      • When a request is mapped to a servlet, the container(in which the servlet has been deployed controls the life cycle of a servlet) performs the following steps –
        • Loads the servlet class.
        • Creates an instance of the servlet class.
        • Initializes the servlet instance by calling the init() method.
        • When servlet is executed it invokes the service method, passing a request and response object.
        • If the container needs to remove the servlet, it finalizes the servlet by calling the servlet’s destroy method.

      • GET and POST Methods :
        • The GET methods is a request made by browsers when the user types in a URL on the address line, follows a link from a Web page, or makes an HTML form that does not specify a METHOD.
        • Servlets can also very easily handle POST requests, which are generated when someone creates an HTML form that specifies METHOD=”POST”.
      • To Write a Sample Servlet Programs :

      Syntax : 

      import java.io.*;
      import javax.servlet.*;
      import javax.servlet.http.*;
      public class SomeServlet extends HttpServlet
      {
            public void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException
                {
                     // Use “request” to read incoming HTTP headers (e.g. cookies)
                     // and HTML form data (e.g. data the user entered and submitted)
                     // Use “response” to specify the HTTP response line and headers
                     // (e.g. specifying the content type, setting cookies).
                     PrintWriter out = response.getWriter();
                         // Use “out” to send content to browser
                }
      }

      Explanation : 

        • To prepare a servlet program, a class should extend HttpServlet and override doGet or doPost (or both as needed), depending on whether the data is being sent by GET or by POST. These methods take two arguments: an HttpServletRequest and an HttpServletResponse objects.
        • The HttpServletRequest has methods for information about incoming information such as FORM data, HTTP request headers etc.
        • The httpServletResponse has methods that specify the HTTP response line (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and most importantly, a PrintWriter used to send output back to the client.

      Example :

      //Java Servelet Program to display message : HelloWorld.java
      import java.io.*;
      import javax.servlet.*;
      import javax.servlet.http.*;
      public class HelloWorld extends HttpServlet
      {
           public void doGet (HttpServletRequest request, HttpServletResponse response)
               throws ServletException, IOException
            {
                 PrintWriter out = response.getWriter();
                 out.println(“Hello World”);
            }
      }

      Normally, most of the servlet program generate HTML output, not plain text output as in the above example. Therefore, to handle html output, we need two additional steps: tell the browser that we’re sending back HTML, and modify the println statements to build a legal Web page. For this, first the Content-Type response header is set. In general, headers can be set via the setHeader method of HttpServletResponse, but setting the content type is such a common task that there is also a special setContentType method just for this purpose. Now, we need to set response headers before actually returning any of the content via the PrintWriter. This can be solved using following example : –

      import javax.servlet.*;
      import java.io.*;
      import javax.servlet.http.*;

      public class HelloWWW extends HttpServlet
         {
             public void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException
                {
                      response.setContentType(“text/html”);
                      PrintWriter out = response.getWriter();
                      out.println(“<!DOCTYPE HTML PUBLIC \”-//W3C//DTD HTML 4.0 ” +
                               “Transitional//EN\”>\n” +
                          “<HTML>\n” +
                                “<HEAD>
                                      <TITLE>Hello WWW</TITLE>
                                 </HEAD>\n”+
                                  “<BODY>\n” +
                                             “<H1>Hello WWW</H1>\n” +
                                  “</BODY>
                              </HTML>”);
                 }
            }
           To run type in URL: http://localhost:8080/servlet/HelloWWW

      Compilation and Installation of the Servlets Programs : 

          • The specific details for installing servlets vary from Web server to Web server. Hence it is referred to the Web server documentation for definitive directions.
          • The on-line examples are running on Java Web Server (JWS) 2.0, where servlets are expected to be in a directory called servlets in the JWS installation hierarchy.
          • To save the servlets program, with the Java Web Server, servlets program are placed in the servlets directory within the main JWS installation directory.
          • To proper functioning of servlets, We have to set the CLASSPATH to point to the directory that contains the servlets folder then we can compile normally from within the directory.
          • To set CLASSPATH, we have  – 
      DOS> set CLASSPATH=C:\JavaWebServer\servlets;%CLASSPATH%
          • To compile the Servlets, we have  – 
      DOS> cd C:\JavaWebServer\servlets\
      DOS> javac HelloWorld.java
          • To run the Servlets, we have  – 
      Type the following in address bar=
      Url Syntax = http://host or localhost/servlet/ServletsavedprogramName.
      Url Example=http://localhost:8080/servlet/HelloWorld
      (NB : The directory name is actually is servlets, [plural] while the URL above to run the program is refers to servlet, [singular].)
      Most servers also define aliases for servlets, so that a servlet can be invoked via http://host/any-path/any-file.html.

      State Maintenance by Servlets

      • As we know that, HTTP is a stateless protocol hence it does not maintain state between client requests i.e. If a client makes a series of requests on a server, HTTP provides no help whatsoever to determine if those requests originated from the same client. There is no way in HTTP to link two separate requests to the same client. Hence, there is no way to maintain state between client requests in HTTP. This is done by servlets.
      • It is necessary to maintain the state of each client on the web specially for e-commerce type of applications. The state, or shopping items in shopping cart, needs to be maintained over a series of client requests. HTTP alone cannot do this; it needs help. This state is maintained for same client is for limited amount of time depend on application used which finally creates a web session.If a session is supposed to be configured for last for 30 minutes, once it has expired the client will need to start a new session. Each session requires a unique identifier that can be used by the client.
      • It is essential to track each client’s requests/state during communication (between a client and server environment).
      • To perform this tracking, java servlets handles it through two different ways  –
        • It is possible to save information about client state on the server using a Session object [Session Handling/Tracking].
        • It is possible to save information on the client system using cookies.
      • This tracking is also done by other two methods – 
        • Hidden Form Fields
        • URL Rewriting
      • Thus, There are four ways to track state information of a client –
        • Hidden Form Fields
        • URL Rewriting
        • Session Handling
        • Cookies.

      Hidden Form Fields

      • Hidden form fields are HTTP tags that are used to store information that is invisible to the user.In terms of session tracking, the hidden form field would be used to hold a client’s unique session id that is passed from the client to the server on each HTTP request. This way the server can extract the session id from the submitted form, like it does for any of form field, and use it to identify which client has made the request and act accordingly.
      • For example, using servlets we could submit the following search form : –
               <form method=”post” action=”/servlet/search”>
      <input type=”text” name=”searchtext”>
      <input type=”hidden” name=”sessionid” value=”512abc”>

      </form>
      When it is submitted to the servlet registered with the name search, it pulls out the sessionid from the form as follows:
      public void doPost(HttpServletRequest request, HttpServletResponse response)
      {
      String theSessionId = request.getParameterValue(“sessionid”);
      if(isAllowToPerformSearch(theSessionId) )
      {
      }
      }

      In this approach, the search servlet gets the session id from the hidden form field and use it to determine whether it allows performing any more searches.
      Hidden form fields implement the required anonymous session tracking features the client needs but not without cost. For hidden fields to work the client must send a hidden form field to the server and the server must always return that same hidden form field. This tightly coupled dependency between client requests and server responses requires sessions involving hidden form fields to be an unbreakable chain dynamically generated web pages. If at any point during the session the client accesses a static page that is not point of the chain, the hidden form field is lost, and with it the session is also lost.

      URL Rewriting

      URL rewriting stores session details as part of the URL itself. You can see below how
      we look at request information for our search servlet : –

      [i] http://www.archana.com/servlet/search

      [ii] http://www.archana.com/servlet/search/23434abc

      [iii] http://www.archana.com/servlet/search?sessionid=23434abc

      For the original servlet [i] the URL is clean. In [ii] we have URL rewritten at the
      server to add extra path information as embedded links in the pages we send back to the client. When the client clicks on one of these links, the search servlet will do th
      following: –

      public void doGet(HttpServletRequest request, HttpServletResponse response)

      {

      String sessionid = request.getPathInfo(); // return 2343abc from [ii]


      }

      Extra path information work for both GET and POST methods involved from inside as 
      well as outside of forms with static links.

      Technique [iii] simply re-writes the URL with parameter information that can be
      accessed as follows:

      request.getParameterValue(“sessionid”);

      URL re-writing, like hidden forms provide a means to implement anonymous session

      tracking. However, with URL rewriting you are not limited to forms and you can wrerite
      URLs in static documents to contain the required session information. But URL re-writing suffers from the same major disadvantage that hidden form fields do, in that
      they must be dynamically generated and the chain of HTML page generation cannot be broken.

      State Maintenance using Session by Servlets

      • A session is a sequence of HTTP requests from the same client, over a period of time, in a client server network during communication.
      • There are various ways through which the state is maintained by the session – 
        • Hidden Form Fields

          • !
            ! URL Rewriting
            ! Session Handling
            ! Cookies.
            en Form
            the user. In terms of session tracking, the hidden form field would be used to hold a
            client’s unique session id that is passed from the client to the server on each HTTP
            request. This way the server can extract the session id from the submitted form, like
            does for any of form field, and use it to identify which client has made the request and
        • URL Rewriting
        • Session Handling
        • Cookies.

        State Maintenance using Cookies by Servlets

        • A cookie is a text file with a name, a value and a set of attributes.
        • Using JSDK (Java Servlet Development Kit) it is possible to save client’s state
          sending cookies. Cookies are sent from the server and saved on client’s system. On
          client’s system cookies are collected and managed by the web browser. When a cookie is sent, the server can retrieve it in a successive client’s connection. Using this
          strategy it is possible to track client’s connections history.

        Cookie class of Java is derives directly from the Object class. Each Cookie object
        instance has some attributes like max age, version, server identification, comment.

        Below are some cookie methods:

        public Cookie (String Name, String Value): Cookie class’ constructor. It has two parameters. The first one is the name that will identity the cookie in the future; the second one is value is a text representing the cookie value. Notice that Name parameter must be a “token” according to the standard defined in RFC2068 and RFC2109.

        Public String getName( ): Returns cookie’s name. A cookie name is set when the
        cookie is created and can’t be changed.

        public void setValue(String NewValue): This method can be used to set or change
        cookie’s value.

        public String getValue( ): Returns a string containing cookie’s value.

        public void setComment(Sting Comment): It is used to set cookie’s comment attribute.

        public String getComment( ): Returns cookie’s comment attribute as a string.

        public void setMaxAge (int MaxAge): Sets cookie’s max age in seconds. This means

        client’s browser will delete the cookie in MaxAge seconds. A negative value indicate the cookie has to be deleted when client’s web browser exits.

        public int getMaxAge( ): Returns cookie’s max age.

        Use of Servlets

        • Servlet is a technology that is used to create a web application.
        • Servlet is an API that provides many interfaces and classes including documentation.
        • Servlet is a web component that is deployed on the server to create a dynamic web page.

         1,773 total views,  2 views today

        Categories: Java

        0 Comments

        Leave a Reply

        Your email address will not be published. Required fields are marked *

        This site uses Akismet to reduce spam. Learn how your comment data is processed.