Definition

  • Servlets are Java programs that run 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 a 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 that 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 the 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 for handling HTTP-specific services, such as do get and do Post.
  • 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 web servers. we all do Net Surfing and well know the data on which the web is submitted and we get the response accordingly. On web pages, the data is retrieved from 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 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 perform better because they use 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 its consisting of Java code.
    • Since servlets use the Java concept hence JVM manages Servlet’s activities, hence servlets represent Robustness and scalability and need not worry about the memory leak, garbage collection, etc.
    • Servlets are secure entity because it consists of Java language.
    • A servlet can communicate with different servlets and servers.
    • Since all web applications are stateless protocols, the servlet uses its own API to maintain the session.
    • Provides all the powerful features of JAVA.

    Disadvantages

    • Designing the 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.
    • The 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, we should the HTML, so the role-based development is missing in pure servlet. The developer who is writing the servlet should know Java and HTML both.
    • It is very difficult to enhance and a bug fix in servlets.
    •  It requires more steps to develop, thus servlet takes too long time to develop.

      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 a 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 method 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 the 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 object.
        • 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 servlet program generates 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 PrintWriter. This can be solved using the 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 the Servelet program, type in the 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 online 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, the servlets program is placed in the servlets directory within the main JWS installation directory.
          • To proper functioning 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 the address bar=
      Url Syntax = http://host or localhost/servlet/ServletsavedprogramName.
      Url Example=http://localhost:8080/servlet/HelloWorld
      (NB: The directory name is actually servlets, [plural] while the URL above to run the program refers to the 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, HTTP is a stateless protocol hence it does not maintain a 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 the state between client requests in HTTP. Hence, this is done by servlets.
      • It is necessary to maintain the state of each client on the web, especially for the e-commerce type of applications. The state, or shopping items in the 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 the same client for a limited amount of time depending on the application used which finally creates a web session. If a session is supposed to be configured to 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 handle it in two different ways  –
        • It is possible to save information about the 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 the state information of a client –
        • Hidden Form Fields
        • URL Rewriting
        • Session Handling
        • Cookies.

      (a) State Maintenance using Hidden Form Fields by Servlets

      • 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, as it does for any 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=”session_id” value=”Hidden Form”>

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

      In this approach, the search servlet gets the session_id from the hidden form field and uses 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 coupled dependency between client requests and server responses requires sessions involving hidden form fields to be an unbreakable chain of dynamically generated web pages. If at any point during the session the client accesses a static page that is not the point of the chain, the hidden form field is lost, and with it, the session is also lost.

      (b) State Maintenance using URL Rewriting by Servlets

      • URL rewriting is a technique used by web applications to maintain the state between different requests. This is accomplished by adding information to the URL that is sent with each request. The information added to the URL is typically in the form of name-value pairs that represent session data.
      • Servlets are Java classes that run on a web server and are used to handle requests and responses. Servlets can use URL rewriting to maintain the state between requests by adding session data to the URL. The session data can then be retrieved on subsequent requests by parsing the URL.
      • To use URL rewriting with servlets, we need to add the session data to the URL as name-value pairs. The session data can be added to the URL using the HttpServletResponse.encodeURL() method. This method takes a URL as a parameter and returns a new URL with the session data added.
      • Here’s an example of how to use URL rewriting to maintain the state using servlets:

      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      HttpSession session = request.getSession(true); // get the session
      String name = request.getParameter(“name”); // get the name parameter from the request
      if(name != null && !name.isEmpty()) {
      session.setAttribute(“name”, name); // set the name attribute in the session
      }
      String url = response.encodeURL(“hello.jsp”); // encode the URL with session data
      response.sendRedirect(url); // redirect to the new URL
      }

      In the above example, we first get the session using the request.getSession() method. We then check if the name the parameter was included in the request, and if it was, we set the name the attribute in the session using the session.setAttribute() method.

      We then encode the URL using the response.encodeURL() method, which adds the session ID to the URL. Finally, we redirect to the new URL using the response.sendRedirect() method.

      On subsequent requests, we can retrieve the session data by parsing the URL and retrieving the attributes from the session.

      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      HttpSession session = request.getSession(false); // get the session if it exists
      if(session != null) {
      String name = (String) session.getAttribute(“name”); // get the name attribute from the session
      if(name != null && !name.isEmpty()) {
      // do something with the name attribute
      }
      }
      // render the response
      }

      In this example, we first get the session using the request.getSession(false) method, which returns null if the session doesn’t exist. We then check if the name attribute exists in the session using the session.getAttribute() method.

      If the name attribute exists, we can do something with it, such as rendering it in the response. If it doesn’t exist, we can either redirect the user to a page where they can enter their name, or we can use a default value.

      (c) 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.
      • Servlets can also use sessions to maintain state information across multiple requests from the same client. A session is a server-side mechanism that allows you to store information about a client’s interaction with a web application. The session information is associated with a unique identifier, which is typically stored in a cookie or in the URL.
      • Sessions provide a powerful way for servlets to maintain state information across multiple requests from the same client. Unlike cookies, sessions are stored on the server side, which makes them more secure and less prone to manipulation. However, sessions require additional server-side resources and can become a scalability bottleneck if not used judiciously. Therefore, we should use sessions in combination with other state management techniques, such as cookies or URL rewriting, depending on the specific requirements of your web application.

      Here’s how we can use sessions to maintain state information in a servlet:

        1. Create a session object: To create a session object in the servlet program, we can use the following code:

      HttpSession session = request.getSession();

      This creates a new session object and associates it with the current request. If a session object already exists for the current request, it is returned instead of creating a new one.

        1. Set session attributes: We can store state information in the session object by setting session attributes using the following code:

      session.setAttribute(“name”, “value”);

      This sets a session attribute with the name “name” and the value “value”. We can set multiple session attributes as needed.

        1. Retrieve session attributes: To retrieve session attributes in subsequent requests, we can use the following code:

      String value = (String) session.getAttribute(“name”);

      This retrieves the value of the session attribute with the name “name”. We can retrieve multiple session attributes as needed.

        1. Invalidate the session: When the client’s interaction with the web application is complete, we should invalidate the session to release any resources associated with it and prevent unauthorized access. We can invalidate the session using the following code:

      session.invalidate();

      (d) State Maintenance using Cookies by Servlets

      • Cookies provide a simple and effective way for servlets to maintain state information across multiple requests from the same client. However, cookies have some limitations, such as maximum size and the fact that they are stored on the client’s machine, which means that they can be deleted or modified by the client. Therefore, cookies should be used judiciously and in combination with other state management techniques, such as session tracking.
      • Servlets can use cookies to maintain state information across multiple requests from the same client. A cookie is a small piece of data that is sent from a web server to a web browser and is stored on the client’s machine. The client’s browser sends the cookie back to the server with each subsequent request, allowing the server to retrieve any state information associated with that cookie.
      • Steps to use cookies to maintain state information in a servlet are:

        1. Create a cookie object: In the servlet program, we can create a new cookie object using the following code:

      Cookie cookie = new Cookie(“name”, “value”);

      This creates a new cookie object with a name of “name” and a value of “value”.

        1. Set the cookie properties: We can set various properties of the cookie object, such as its expiration date and path, using the following methods:

      cookie.setMaxAge(3600); // sets the cookie to expire in one-hour
      cookie.setPath(“/”); // sets the cookie to be accessible to all pages in the application

        1. Add the cookie to the response: To send the cookie to the client, we need to add it to the HTTP response headers using the following code:

      response.addCookie(cookie);

        1. Retrieve the cookie in subsequent requests: When the client sends a subsequent request to the server, the cookie will be included in the request headers. To retrieve the cookie in our servlet program, we can use the following code:

      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
      for (Cookie cookie : cookies) {
      if (cookie.getName().equals(“name”)) {
      String value = cookie.getValue();
      //Do something with the value…
      }
      }
      }

      The above code will retrieve all the cookies sent by the client in the current request and check if there is a cookie with the name “name”. If such a cookie is found, its value is retrieved and can be used to maintain state information.

      Use of Servlets

      • The servlet technology is used to create a web application.
      • A servlet is an API that provides many interfaces and classes including documentation.
      • A servlet is a web component that is deployed on the server to create a dynamic web page.
      • Servlets can be used to validate user credentials and restrict access to certain parts of a web application based on the user’s role or permissions.
      • Servlets can receive form submissions and other input from clients and process that data to generate dynamic content or store it in a database.
      • Servlets can generate dynamic HTML pages, XML documents, or other types of content based on user input or other factors.
      • Servlets can be used to implement RESTful web services that expose application functionality to other applications or clients.
      • Servlets can interact with databases using JDBC or other persistence technologies to retrieve or store data.

      Loading

      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.