• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Servlet

Servlet Chaining

Session and Cookies

Servlet Database

Servlet Example

Servlet Introduction

Servlet to create cookies and add them to the response header

By Dinesh Thakur

One of the ways to keep track of session between the client and the server is through the use of cookies. A cookie is a piece of information that a web server sends to the browser.

The web server assigns a unique ID as a cookie to each client. It sends the cookie to the client by embedding it in the response header. With each request, the client sends this cookie value to the server. Using this value, the server identifies the user. Cookie is usually used to maintain the information about the client (such as user ID, name, etc.) that is needed every time a client visits the website. A cookie is constructed using the following constructor of Cookie class. public Cookie(String name, String val)

A servlet to create cookies and add them to the response header

import java.io.* ;

import javax.servlet.*;

import javax.servlet.http.*;

public class CreateCookies extends HttpServlet

{

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

   {

       Cookie name = new Cookie(“name”, request.getParameter(“name”));

       // Create cookie for name

       Cookie age= new Cookie(“age”, request.getParameter(“age”));

       // Create cookie for age

       name.setMaxAge(60*60*12); //60*60*24

       age.setMaxAge(60*60*12); // 60*60*24

       // Set expiry date after 12 Hrs for both the cookies

       response.addCookie(name);

       response.addCookie(age);

       // Add both the cookies in the response header

       response.setContentType(“text/html”);

       // Set response content type

       PrintWriter out= response.getWriter();

       String title = “Example to Set Cookies”;

       out.println(“<html>\n” +”<head><title>” + title+

       “</title></head>\n” +”<body >\n” +

       “<h1 align=\”center\”>” + title + “</h1>\n” +

       “<ul>\n” + “<li><b>Name</b>: “

       + request.getParameter(“name”) + “\n” +

       ” <li><b>Age</b>: “

       + request.getParameter(“age”) + “\n” +

       “</ul>\n” + “</body></html>”);

    }

}

This example creates two cookies using the Cookie () constructor. First one is name having the name “name” and the value of the “name” parameter. Other one is age having the name “age” and value of the “age” parameter. The maximum age of both the cookies is set to 12 hrs; the browser will keep this cookie information for 12 hrs. These cookies are then added to the HTTP response header using addCookie () method.

HTML code to call the servlet named CreateCookies is as follows:

<HTML>

   <BODY>

      <FORM ACTION=”servlet/CreateCookies” METHOD=” GET”>

            Name: <INPUT TYPE=”text” NAME=”name”>

      <BR/>

            Age: &nbsp;&nbsp;&nbsp;<INPUT TYPE=”text” NAME=”age” />

             <BR><BR>

              <INPUT TYPE=”submit” VALUE=”Submit” />

      </FORM>

    </BODY>

</HTML>

Compile the servlet CreateCookies and create appropriate entry in web.xml file. Type the URL https://ecomputernotes.com:8080/CreateCookies in the browser. It will display the output shown in Figure

          Web Page Displaying the form

Enter the Name and Age, and then click the submit button on the web page. It will display the output and set two cookies named name and age, which will be passed to the server every time when the submit button is clicked.

        Output Generated by CreateCookies Servlet

A servlet to retrieve cookies from the HTTP request header

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ReadCookies extends HttpServlet

{

    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException

   {

        Cookie cookie = null;

        Cookie[] cookies= null;

        cookies= request.getCookies();

        // Get an array of Cookies

        response.setContentType(“text/html”);

        // Set response content type

        PrintWriter out= response.getWriter();

        String title = ” Example to Read Cookies”;

        out.println(“<html>\n” +”<head><title>” + title+

        “</title></head>\n” +”<body>\n” );

        if( cookies !=null )

          {

              out.println(“<h2> Cookies found: Name and Value</h2>”);

              for (int i = 0; i < cookies.length; i++)

                   {

                        cookie= cookies[i];

                        out.print(“Name : “+cookie.getName( )+”, “);

                        out.print(“Value: “+cookie.getValue( )+”<br/>”);

                   }

           }

                  else

                      {

                          out.println(“<h2>No cookies exist</h2>”);

                      }

                          out.println(“</body>”);

                          out.println(“</html>”);

     }

}

In this example, the cookies that are included in the HTTP request header are retrieved by calling getcookies () method of HttpServletRequest object.. This method returns an array of cookie objects for the current request. The name and value associated with each cookie is obtained using the getName () and get Value () methods respectively. The names and values of these cookies are then written to HTTP response.

Compile the servlet ReadCookies and create appropriate entry in web.xml file. Type the URL https://ecomputernotes.com:8080/ReadCookies in the browser. It will display the output shown in Figure

           Retrieving Cookies

HttpSession in Servlet Java Example

By Dinesh Thakur

HTTP is a stateless protocol; each time a client requests for a page, a separate connection is established between the client and the server. Thus, it provides no way for a server to maintain information for a particular user across multiple requests. There are many web applications where it is required to maintain this information. For example, in case of shopping cart, it is required to keep track of the list of items that are added in each user’s cart. For this, the server must provide a way to store data for each client and distinguish clients from one another.

Session provides such mechanism. A session consists of all the requests that are made during invocation of a single browser. The servlet manages the session using HttpSession interface. Using this interface, a session can be created between an HTTP client and an HTTP server. This session exists for a specified period of time across a sequence of requests from a user.

A servlet to keep track of the number of times a user has visited a site during the current session using interface HttpSession

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

public class SessionTrackingExample extends HttpServlet

{

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

   {

       HttpSession session= request.getSession(true);

       // Create a session object if does not exist

       Date createTime =new Date(session.getCreationTime());

       // Get session creation time

       Date lastAccessTime = new Date(session.getLastAccessedTime());

       // Get sessions last access time

       String title = “Welcome Back !”;

       Integer visitCounter =new Integer(0);

       String userID =new String(“xyz”);

       if (session.isNew())

          {

               title= “Welcome !”;

               session.setAttribute(“userID”, userID);

          }

          else

             {

                 visitCounter = (Integer) session.getAttribute(“visitCount”);

                 visitCounter = visitCounter + 1;

                 userID = (String)session.getAttribute(“userID”);

             }

             session.setAttribute(“visitCount”, visitCounter);

             // Check if this is new Visitor

             response.setContentType(“text/html”);

             PrintWriter out= response.getWriter();

             out.println(“<html>\n” +”<head><title>” + title+

             “</title></head>\n” + “<body\”>\n” +

             “<h1 align=\”center \”>”+title + “</h1>\n” +

             “<h2 align=\”center\”>Session Details</h2>\n” +

             “<table border=\”1\” align=\”center\”>\n” + 

             “<tr\”>\n” +

             “<th>Session info</th><th>value</th></tr>\n”+

             “<tr>\n” + ” <td>Id</td>\n” +

             “<td>” + session.getId() + “</td></tr>\n” +

             “<tr>\n” +” <td>Session Creation Time</td>\n” +

             “<td>” + createTime + ” </td></tr>\n” +

             “<tr>\n” + ” <td>Last Accessed at</td>\n” +

             “<td>” + lastAccessTime + ” </td></tr>\n” +

             “<tr>\n” + ” <td>Visitor ID</td>\n” +

             “<td>” + userID + ” </td></tr>\n” +

             “<tr>\n” + ” <td>Number of visits</td>\n” +

             “<td>” + visitCounter + “</td></tr>\n” + 

             “</table>\n” + “</body></html>”);

     }

}

In this example, a session is created using the getSession () method of HttpServletRequest interface. The single parameter to this method indicates that a new session must be created if it does not exist. This method returns an HttpSession object. To access the properties of session including the session identifier, different methods, namely, getCreationTime(), lastAccessTime(), SetAttribute(), getAttribute(), and get Id ()are invoked using the session object.

Compile the servlet SessionTrackingExample and create appropriate entry in web.xml file. Type the URL https://ecomputernotes.com:8080/SessionTrackingExample in the browser. On first run, it will display the output shown in Figure

               Output Generated by SessionTrackingExample Servlet

Servlet for handling HTTP POST request Example

By Dinesh Thakur

Like doGet () method, the do Post () method is invoked by server through service () method to handle HTTP POST request. The doPost () method is used when large amount of data is required to be passed to the server which is not possible with the help of doGet () method.

 

In doGet () method, parameters are appended to the URL whereas, in do Post () method parameters are sent in separate line in the HTTP request body. The do Get ( ) method is mostly used when some information is to be retrieved from the server and the doPost () method is used when data is to be updated on server or data is to be submitted to the server. To understand the working of do Post () method, let us consider a sample program to define a servlet for handling the HTTP POST request.

A program to define a servlet for handling HTTP POST request

import java.io.*;

import java.util.*;

import javax.servlet.*;

public class ServletPostExample extends HttpServlet

{

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

   {

      PrintWriter out = res.getWriter();

      String login= req.getParameter(“loginid”);

      String password= req.getParameter(“password”);

      out.println(“Your login ID is: “);

      out.println(login);

      out.println(“Your password is: “);

      out.println(password);

      out.close();

   }

}

The corresponding HTML code for this servlet is as follows

<HTML>

          <BODY>

                  <CENTER>

                         <FORM NAME=”Form1″ METHOD=”post” ACTION=”https://ecomputernotes.com:8080/ServletGetExample”>

                                 <B>Login ID</B> <INPUT TYPE=”text” NAME=”loginid” SIZE=”30″>

                                 <P>

                                 <B>Password</B> <INPUT TYPE=”password” NAME=”password” SIZE=”30″>

                                 </P>

                                 <P>

                                 <INPUT TYPE=submit VALUE=”Submit”.>

                                 </P>

           </BODY>

</HTML>

This HTML code create as web page containing a form

Enter the required data and press the submit button on the web page. The browser will display the response generated dynamically by the corresponding servlet.

Servlet for handling HTTP GET request Example

By Dinesh Thakur

The doGet () method is invoked by server through service () method to handle a HTTP GET request. This method also handles HTTP HEAD request automatically as HEAD request is nothing but a GET request having no body in the code for response and only includes request header fields. To understand the working of doGet () method, let us consider a sample program to define a servlet for handling the HTTP GET request. [Read more…] about Servlet for handling HTTP GET request Example

Servlet using GenericServlet class Example

By Dinesh Thakur

The GenericServlet class implements the Servlet and ServletConfig interfaces. Since service () method is declared as an abstract method in GenericServlet class, it is an abstract class. The class extending this class must implement the service () method. It is used to create servlets which are protocol independent.

To understand the creation of servlets using the GenericServlet class, lets us consider a simple program given here. For this, two files will be required; one .java file in which servlet is defined and another. html file containing code for web page.

A program to create servlet using GenericServlet class

import java.io.*;

import java.util.*;

import javax.servlet.*;

public class ServletExample extends GenericServlet

{

    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException

   {

      PrintWriter out = res.getWriter();

      String login= req.getParameter(“loginid”);

      String password= req.getParameter(“password”);

      out.print(“You have successfully login :”);

      out.println(“Your login ID is: “+login);

      out.println(“Your password is: ” +password);

      out.close();

   }

}

The explanation of this program is as follow.

1. Firstly, the javax.servlet package is imported which contains interfaces and classes to create servlet.

2. Next, the class named ServletExample is defined which extends the GenericServlet class. This class provides methods for initializing ,invoking and destroying an instance of servlet. The init () and destroy () methods are inherited from the GenericServlet class. The ServletExample class must override the service () method as it is declared as abstract in GenericServlet class.

3. The two parameters passed to the service () method are req and res, the objects of ServletRequest and ServletResponse interfaces respectively. The req object allows to read data provided in the client request and the res object is used to develop response for the client request.

4. The getWriter () method returns PrintWriter stream. This stream is used to send data as part of the response. The println () method can be used to write HTML code forming part of the response.

5. The getParameter () method of ServletRequest interface is used to retrieve data sent To the server by the client .For example, the expression req. getParameter (“loginid”) is used the retrieve value stored in parameter loginid provided as a part of the request.

This code for servlet will be executed as a response to some action performed on the webpage. The HTML code(.html) for the webpage is as follows.

<HTML>

   <BODY>

      <CENTER>

         <FORM NAME=”Form1″ METHOD=”post” ACTION=”https://ecomputernotes.com:8080/ServletExample”>

              <B>Login ID</B> <INPUT TYPE=”text” NAME=”loginid” SIZE=”30″>

              <P>

              <B>Password</B> <INPUT TYPE=”password” NAME=”password” SIZE=”30″>

             </P>

             <P>

                  <INPUT TYPE=submit VALUE=”Submit”>

            </P>

   </BODY>

</HTML>

This HTML code creates a web page containing a form. This form includes two text fields, one submit button and one reset button. The action attribute of< FORM>tag is used to specify the URL for identifying the servlet to be processed for the POST request. Save this file as ServletExample.html in root directory.

To make servlet working, compile ServletExample.java file and store its .class file in the appropriate directory. Add its name in web.xml file using the following statements in the section which defines the servlets.

<servlet>

<servlet-name>ServletExample</servlet-name>

<servlet-class>ServletExample</servlet-class>

</servlet>

Also, add the following statements in the section which defines the section mappings in web.xml.

<servlet-mapping>

<servlet-name>ServletExample</servlet-name>

<url-pattem>ServletExample</url-pattern>

</servlet-mapping>

Start the Tomcat so that it is in the running mode in the background when web page is being processed. Open the Internet Explorer and enter the following URL in the address bar.

https://ecomputernotes.com:8080/ServletExample.html

      Web Page Displaying the Form

Enter the required data and press the submit button. The browser will display the response generated dynamically by the corresponding servlet.

               Output Generated by Servlet

Creating and Executing Servlets

By Dinesh Thakur

Servlets are platform independent and can work with almost all the web servers. They can be executed on any web server that supports the servlet API. Some of the web servers having built-in support for Java servlets are Tomcat server (Apache), Java web server (Sun Microsystems), Enterprise server (Netscape), Zeus web server (Zeus Technology), Tengah application server (Weblogic) and Sun web server (Sun Microsystems).

In this unit, we will be using the Tomcat server to explain the steps required to execute the servlet in Windows environment. Assume that the default location of Tomcat 6.0 is as follows.

C:\Program Files\Apache Software Foundation\Tomcat 6.0\

Following are the steps to create and execute the servlet.

1. Create a . java source file containing the code for creating servlet and save it with the name, say Sample. java.

2. Compile this source file, as a result Sample . class file will be created.

3. Copy the Sample. class file in the directory under the webapps directory of Tomcat. The

path for the directory is as follows.

C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\MyApp\WEB-INF\classes

Add the name and mapping of this servlet in the web . xml file. The path of this file is as follows.

C:\Program Files\Apache Software Foundation\Tomcat6.0\webapps\MyApp\WEB-INF

4. Add the following statements in the section which defines the servlets.

<servlet>

     <servlet-name>Sample</servlet-name>

    <servlet-class>Sample</servlet-class>

</servlet>

Also, add the following statements in the section which defines the servlets mappings.

<servlet-mapping>

     <servlet-name>Sample</servlet-name>

     <url-pattem>/servlet/Sample</url-pattem>

</servlet-mapping>

5. Start the Tomcat. To start the Tomcat, click the Start menu, point to All Programs, point to Apache Tomcat 6.0 and then click Configure Tomcat. This displays the Apache Tomcat Properties. Click the Start button.

6. Start a web browser and request for the servlet. Note that the HTML code can be included in the servlet code or a separate HTML file can be used. If the HTML code is included in the servlet code, enter the following URL in the address bar.

https://ecomputernotes.com:8080/MyApp/servlet/Sample

or

http:/1127.0.0.1:8080/MyApp/servlet/Sample

If separate HTML file is used for the HTML code, enter the following URL in the address bar.

https://ecomputernotes.com:8080/MyApp/Sample.html

or

http:/1127.0.0.1:8080/MyApp/Sample.html

Here, 127 . 0 . 0 . 1 : 8O80 is an IP address of the local system. Note that the . html file must be saved in the MyAppdirectory.

The output of the servlet will be displayed in the display area of browser.

Advantages of Servlets

By Dinesh Thakur

Internet and WWW are often used interchangeably but both are different. Internet is the global network of computer networks whereas Web is one of the services provided over Internet. That is, Web is an application running over Internet. While creating web applications, the main goal is to perform most of the processing on the browser side, there by, reducing processing load on the server side.

 

However, sometimes it is not possible to eliminate all processing at the server side. For example, in situations like online registration, retrieving data from underlying data, etc., some processing might be required at the server side. One of the server side technologies, servlets is used to handle server side processing. Servlets are small programs written in Java, which are loaded and executed by web server as applets are loaded and executed by web browser. Since, servlets are written in Java, they are platform independent and also posses all other advantages of Java.

Advantages of servlets

A servlet can be imagined to be as an applet running on the server side. Some of the other server side technologies available are Common Gateway Interface (CGI), server side JavaScript and Active Server Pages (ASP). Advantages of servlets over these server side technologies are as follows:

• Persistent: Servlets remain in memory until explicitly destroyed. This helps in serving several incoming requests. Servlets establishes connection only once with the database and can handle several requests on the same database. This reduces the time and resources required to establish connection again and again with the same database. Whereas, CGI programs are removed from the memory once the request is processed and each time a new process is initiated whenever new request arrives.

• Portable: Since servlets are written in Java, they are portable. That is, servlets are compatible with almost all operating systems. The programs written on one operating system can be executed on other operating system.

• Server-independent: Servlets are compatible with any web server available today. Most of the software vendors today support servlets within their web server products. On the other hand, some of the server side technologies like server side JavaSricpt and ASP can run on only selected web servers. The CGI is compatible with the web server that has features to supports it.

• Protocol-independent: Servlets can be created to support any of the protocols like FTP commands, Telnet sessions, NNTP newsgroups, etc. It also provides extended support for the functionality of HTTP protocol.

• Extensible: Servlets being written in Java, can be extended and polymorphed into the objects that suits the user requirement.

• Secure: Since servlets are server side programs and can be invoked by web server only, they inherit all the security measures taken by the web server. They are also safe from the problems related to memory management as Java does not support the concept of pointers and perform garbage collection automatically.

• Fast: Since servlets are compiled into bytecodes, they can execute more quickly as compared to other scripting languages. The bytecode compilation feature helps servlets to give much better performance. In addition, it also provides advantage of strong error and type checking.

What Is File Uploading? Important Classes Of Javazoom.Api

By Dinesh Thakur

The process of selecting file from the client machine file system and sending that file to the server machine system is known as file uploading. File uploading and downloading using servlet-api is a complex process, that is why industry uses JavaZoom 3rd party API. [Read more…] about What Is File Uploading? Important Classes Of Javazoom.Api

Difference Between Rd.Forward () Res. sendRedirect ()

By Dinesh Thakur

[Read more…] about Difference Between Rd.Forward () Res. sendRedirect ()

How to use sendRedirect method

By Dinesh Thakur

This method sends a temporary redirect response to the client using the mentioned redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading ‘/’ the container interprets it as relative to the current request URL. If the location is relative with a leading ‘/’ the container interprets it as relative to the servlet container root. [Read more…] about How to use sendRedirect method

How to use RequestDispatcher Forward method

By Dinesh Thakur

This method forwards a request from a servlet to another resource (servlet, JSP file or HTML file) on the server. It enables one servlet to do prelude processing of a request and another resource to create the response. [Read more…] about How to use RequestDispatcher Forward method

How to use RequestDispatcher include method

By Dinesh Thakur

This method of RequestDispatcher interface includes the content of web resource (servlets, JSP and HTML file) in the response. In other words, this method allows server-side to include the response of destination program to source program. Here ServletResponse object are passed as the argument of include () method. [Read more…] about How to use RequestDispatcher include method

Servlet Chaining Between Two Servlet Programs

By Dinesh Thakur

In the diagram Below, Srvl program forwards the request to Srv2 only when the generated square value is less than 100,otherwise, the Srvl directly sends response to browser window displaying that square value.

Deploy both these web applications in web logic server (Adv.java Batch Domain) copy WeqAppl, WebApp2 web applications to <oracleweblogic_home>\user-if possible \domains \Adv.javaBatchDomain \autodeploy folder.

              Servlet Chaining between Two Servlet Programs of two different web applications which resides in the same server

In the Srvl servlet program of the above WebAppl web application, we must create RequestDispatcher object based on ServletContext object.

             

            

Source Code (WebApp1)

input.html url patttren of Srvl servlet program

<form action=”slurl” method=”get”>

             A value : <input type = “text” name= “t1”><br>

            <input type= “submit” value= “getResult”>

</form>

Srv1.java

import javax.servlet.*;

import javax.http.*;

import javax.io.*;

public class Srv1 extends HttpServlet

{

     public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException

   {

            PrintWriter pw = response.getWriter();

            response.setContentType(“text/html”);

            int no=Integer.parselnt(req.getParameter(“t1”));

            int res1=no*no;

            if (res>=100)

               {

                  pw.println(“Srv1 : Square val is :”+res);

               }

            else

               {

                  ServletContext sc1 = getServletContext();

                  ServletContext sc2 = sc1.getContext(“WebApp2”);

                  RequestDispatcherrd = sc2.getRequestDispatcher(“/s2url”);

                  rd.forward(req,res);

              }

   }

}

web.xml

Configure Srvl program with /srvlurl as url pattern’

 

Source Code(WebApp2)

Srv2. java

import javax.servlet.*;

import javax.http.*;

import javax.io.*;

public class Srvl extends HttpServlet

{

     public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException

   {

            PrintWriter pw = response.getWriter();

            response.setContentType(“text/html”);

       int no=Integer.parselnt(req.getParameter(“t1”));

       int res2=no*no*no;

       pw.println{“Srv2: cube val is :”+res2) ;

  }

}

Difference between the REQUESTDISPATCHER Object and SERVLETCONTEXT Object

By Dinesh Thakur

The request object based RequestDispatcher object expects that the source servlet Program, destination web resource program and the destination web resource program be in the same web application.

The ServletContext object based RequestDispatcher object allows to keep the source servlet program and destination web resource program either in the same web application or in two different web application of the same server, but they cannot be two different web applications of two different servers.

         different web applications of two different servers

Here, we can use request object or ServletContext object basedRequestDispatcher Object.

         

Here Srv1 should use ServletContext object based RequestDispatcher object.

           servlet-servlet Communication

This kind of ServletChaining is not possible with RequestDispatcher object use send redirection concept. Servlet chaining is all about performing servlet-servlet communication.

Difference between GETREQUESTDISPATCHER () AND GETNAMEDDISPATCHER ()

By Dinesh Thakur

GETREQUESTDISPATCHER ()

lnvokable on both request, servletContext object. Expects URL pattern of destination JSP or HTML programs as argument value. Generated RequestDispatcher object can point the destination servlet JSP program and HTML program.

GETNAMEDDISPATCHER ()

lnvokable only on ServletContext object. Expects logical name of the destination servlet/JSP program as argument value. Generated RequestDispatcher object can point only to the destination servlet, JSP programs.

RequestDispatcher in Servlet

By Dinesh Thakur

While building a complex web application there might be a need to distribute the request to multiple servlets. This is where request dispatching comes into use. Due to this requirement Servlet container supports request dispatching within the same context.

The javax.servlet.RequestDispatcher is an interface that enables the Servlet Container to dispatch the request from a web application to another within the same context.

 

In order to dispatch the request we need to perform these tasks:

• Get a RequestDispatcher object

• Use the forward() method or include method of RequestDispatcher

 

There are three approaches to create the RequestDispatcher object:

 

i. By using ServletRequest object

ii. By using getRequestDispatcher() method of ServletContext

iii. By using getNamedDispatcher() method of ServletContext

 

Approach 1: (by using reqobj)

 

Example 1

 

In srv1 source code,

 

RequestDispatcherrd=req.getRequestDispatcher(“s2url“);

rd.forward(req,res);

           (or)

Rd.include(req,res);

 

Example 2

 

In source srv2 program

 

RequestDispatcherrd=req.getRequestDispatcher(“/abc.html“);

      (or)

RequestDispatcherrd=req.getRequestDispatcher(“/abc.jsp“);

rd.forward(req,res);

           (or)

rd.include(req,res);

 

Approach 2: (by using ServletContextobj)

 

Example 1

 

In srv1 source code,

 

ServletContext sc=getServletcontext();

RequestDispatcherrd=req.getRequestDispatcher(“s2url“);

rd.forward(req,res);

           (or)

Rd.include(req,res);

 

Example 2

 

In source srv1 program

 

ServletContext sc=getServletcontext();

RequestDispatcherrd=req.getRequestDispatcher(“/abc.html“);

      (or)

RequestDispatcherrd=req.getRequestDispatcher(“/abc.jsp“);

rd.forward(req,res);

           (or)

rd.include(req,res);

 

Approach 3: (by using ServletContextobj)

 

Example 1

 

In srvl source code,

ServletContext sc=getServletcontext();

RequestDispatcherrd=sc.getNameDispatcher(“s2”);

rd.forward(req,res);

           (or)

rd.include(req,res);

 

Example 2

 

In srv1 source code,

 

ServletContext sc=getServletcontext();

RequestDispatcherrd=sc.getNameDispatcher(“j2”);

rd.forward(req,res);

           (or)

rd.include(req,res);

 

• If the source servlet program calls rd.forward(req,res) method, then it performs forwarding request mode of servlet chaining with destination web resource program.

• Servlet configuration in web.xml is mandatory so it contains logical name and URL pattern.

• The JSP program configuration in web.xml file is optional so it mayor may not contain logical name and URL pattern. We cannot configure HTML in web.xml.

Type of Servlet Chaining

By Dinesh Thakur

• In any mode of servlet chaining, all servlet programs/web resource programs use the same request and response objects. If srvI, srv2, srv3 and srv4 servlet programs are in forwarding request mode of servlet chaining, the html output of srv1, srv and srv3 is discarded and only the output of srv4 servlet program goes to the browser window.

• If srv1, srv2, srv3 and srv4 servlet programs are in including response mode of servlet chaining, the HTML output of all servlet programs together goes to the browser window.

• The source servlet program uses RequestDispatcher object to perform servlet chaining with destination web resource program.

             Type of Servlet Chaining

What is Servlet Chaining?

By Dinesh Thakur

Taking a request from a browser window and processing it by using multiple servlets as a chain is called Servlet Chaining. In servlet chaining, communication occurs between servlet chains and servlet programs to process the request given by a client.

This is a process to make available the user’s request to multiple servlets. A user provides request to the first servlet present in the chain. The first servlet uses the form fields present in the request. It can transfer the request to another servlet with the execution control. The second servlet can use the request, as it is available to it. This process can be repeated for any number of servlets. The last servlet present in the chain provides response to the user. All servlets present before the last servlet remain invisible to the user.

A question may come to your mind, as to why one would want to use a servlet chain when one could instead write a script that edits the files in place, especially when there is an additional amount of overhead for each servlet involved in handling a request? The answer is that servlet chains have a threefold advantage:

• They can be easily undone.

• They handle dynamically created content, so you can trust that your restrictions are maintained, your special tags are replaced, and your dynamically converted PostScript images are properly displayed, even in the output of a servlet (or a CGI script).

• They handle the content of the future, so you do not have to run your script every time new content is added.

               Servlet Chaining

• All servlet programs that participate in the servlet chaining will use some request and response objects because they process the same request that is given by the client.

• To perform servlet chaining we need RequestDispatcher object. RequestDispatcher object means it is the object of a container supplied Java class implementing javax. servlet.RequestDispatcher interface.

Jsp To Servlet Communication

By Dinesh Thakur

JSP is a tag-based language, i.e., code is written within specified tags. It is developed by Sun Microsystems. Unlike servlet program, we can write HTML tags within the JSP program, making it easier to build.

When a servlet JSP communication is taking place, it is not just about forwarding the request to a JSP from a servlet. There might be a need to transfer a string value or an object itself.

In the JSP program we use simple HTML tags to take input from the client but we will save the file as a .jsp extension and then we will retrieve the data in the servlet program.

                 

Login.html

<center>

<form action=”login” method=”get” >

USERNAME <input type=’text’ name=’t1′><br>

PASSWORD <input type=’text’ name=’t2′><br>

<input type=”submit” value=”login” >

<input type=”reset” value=”reset” >

</form>

</center>

Login·java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Login extends HttpServlet

{

           public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException

       {

               res.setContentType(“text/html”);          

               String usname=req.getParameter(“t1”);

               String pass=req.getParameter(“t2”);

               PrintWriter pw=res.getWriter();

               pw.println(“USERNAME IS : “+usname);

               pw. println (” PASSWORD IS : “+pass) ;

               pw.close();

        }

}

To test the application

https://ecomputernotes.com:portno/login.jsp

Servlet to Database Communication

By Dinesh Thakur

Accessing data in a database or in any other data sources is a significant operation in web programming. Data access from JSPs and servlets is done through Java Database Connectivity (JDBC). [Read more…] about Servlet to Database Communication

Applet to Servlet Communication

By Dinesh Thakur

HTML exhibits high performance by taking less time to load in the browser. However, when we use HTML page for important user details, by default, all the parameters that are passed appended in the URL. This compromises with the security. On the other hand, applet takes more time to load but there is no problem with Java security. This is an advantage of this technique. [Read more…] about Applet to Servlet Communication

What is the difference between doGet and doPost?

By Dinesh Thakur

In doGet Method the parameters are appended to the URL and sent along with the information. Maximum size of data that can be sent using do Get it 240 bytes. Parameters are not encrypted. doGet method generally is used to query or to get some informationfromthe server.

doGet is faster if we set the response content length since the same connection is used. Thus increasing the performance. doGet should be important. doGet should be able to be repeated safely many times. doGet should be safe without any side effects for which user is held responsible.

doPost

In doPost, parameters are sent in separate line in the body. There is no maximum size for data. Parameters are encrypted. doPost is generally used to update or posts some information to the server. do Post is slower compared to doGet since do Post does not write the content length.

This method does not need to be important Operations requested through POST can have side effects for which the user can be held accountable, for example, updating stored data  or buying items online.

What is HttpServletResponse and It’s Methods?

By Dinesh Thakur

HttpServletResponse is a predefined interface present in javax.servlet.http package. It can be said that it is a mirror image of request object. The response object is where the servlet can write information about the data it will send back. Whereas the majority of the methods in the request object start with GET, indicating that they get a value, many of the important methods in the response object start with SET, indicating that they change some property. Note that these interfaces adhere to the usual naming conventions for beans.

Methods in HttpServletResponse

i. public void addCookie(Cookie cookie)

Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.

ii. public void addDateHeader (String name, long date)

Adds a response header with the given name and date-value.

iii. public void addHeader(String name,String value)

Adds a response header with the given name and value.

iv public void addlntHeader(String name,int value)

Adds a response header with the given name and integer value.

v public boolean containsHeader(String name)

Returns a boolean indicating whether the named response header has already been set.

vi. public String encodeRedirectURL(String url)

Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.

vii. public String encodeURL(String url)

Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.

viii. public void sendError(int sc) throws IOException

Sends an error response to the client using the specified status code and clearing the buffer.

ix. public void sendError(int Be, String mag) throws IOException

Sends an error response to the client using the specified status clearing the buffer.

x. public void sendRedirect(string location) throws IOException

Sends a temporary redirect response to the client using the specified redirect location URL.

xi. public void setDateHeader(String name,long date)

Sets a response header with the given name and date-value.

xii. public void setHeader(String name, String value)

Sets a response header with the given name and value.

xiii. public void setlntHeader (String name,int value)

Sets a response header with the given name and integer value.

xiv public void setStatus(int sc)

Sets the status code for this response.

What is HttpServletRequest and It’s Methods?

By Dinesh Thakur

HttpServletRequest is an interface and extends the ServletRequest interface. By extending the ServletRequest this interface is able to allow request information for HTTP Servlets. Object of the HttpServletRequest is created by the Servlet container and, then, it is passed to the service method (doGet(), doPost(), etc.) of the Servlet.

Extends the ServletRequest interface to provide request information for HTTP servlets.

The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet’s service methods (doGet, doPost, etc.).

i. public String getAuthType()

Returns the name of the authentication scheme used to protect the servlet.

ii. public String getContextPath ()

Returns the portion of the request URI that indicates the context of the request.

iii. public Cookie [] getCookies ( )

Returns an array containing all of the cookie objects the client sent with this request.

iv public long getDateHeader(String name)

Returns the value of the specified request header as a long value that represents a date object.

v public String getHeader(String name)

Returns the value of the specified request header as a string.

vi. public Enumeration getHeaderNames()

Returns an enumeration of all the header names this request contains.

vii. public Enumeration getHeaders (String name)

Returns all the values of the specified request header as an enumeration of String objects.

viii. public int getIntHeader (String name)

Returns the value of the specified request header as an int.

ix. public String getMethod()

Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT, same as the value of the CGI variable REQUEST_METHOD.

x. public String getPathlnfo()

Returns any extra path information associated with the URL the client sent when it made this request.

xi. public String getpathTranslated ()

Returns any extra path information after the servlet name but before the query string, and translates it to a real path.

xii. public String getQueryString ()

Returns the query string that is contained in the request URL after the path.

xiii. public String getRemoteUser ()

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

xiv public String getRequestedSessionld()

Returns the session ID specified by the client.

xv public String getRequestURI()

Returns the part of this request’s URL from the protocol name up to the query string in the first line of the HTTP request.

xvi. public StringBuffer getRequestURL()

Reconstructs the URL the client used to make the request.

xvii.public String getServletpath ()

Returns the part of this request’s URL that calls the serv let.

xviii.public HttpSession getSession ()

Returns the current session associated with this request, or if the request does not have a session, creates one.

xix. public HttpSession getSession(boolean create)

Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.

xx. public Principal getUserPrincipal()

Returns a java.security. Principal object containing the name of the current authenticated user.

xxi. public boolean isRequestedSessionldFromCookie()

Checks whether the requested session ID came in as a cookie.

xxii. public boolean isRequestedSessionldValid()

Checks whether the requested session ID is still valid.

xxiii. public boolean isUserlnRole (String role)

Returns a boolean indicating whether the authenticated user is included in the specified logical role.

What is HttpServlet and it’s Methods?

By Dinesh Thakur

HttpServlet is an abstract class given under the servlet-api present. It is present in javax.servlet.http package and has no abstract methods. It extends GenericServlet class.

When the servlet container uses HTTP protocol to send request, then it creates HttpServletRequest and HttpServletResponse objects. HttpServletRequest binds the request information like header and request methods and HttpServletResponse binds all information of HTTP protocol.

HttpServlet does not override in it or destroy method. However, it uses service (-,-) method. ServletRequest and ServletResponse references are cast into HttpServletRequest and HttpServletResponse, respectively.

Methods in HttpServlet

The methods in httpservlet are given as follows:

i. protected void doDelete (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a DELETE request. The DELETE operation allows a client to remove a document or web page from the server.

ii. protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method)”to allow a servlet to handle a GET request. Overriding this method to support a GETrequest also automatically supports an HTTP HEAD request.

iii. protected void doHead(HttpServletRequest req,HttpServletResponse resp)

throws ServletException, IOException

Receives an HTTP HEAD request from the protected service method and handles the request.

iv. protected void doOptions(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle OPTIONS request. The OPTIONS request determines which HTTP methods the server supports and returns an appropriate header.

v. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a POST request. The HTTP POST method allows the client to send data of unlimited length to the Web server a single time and is useful when posting information such as credit card numbers.

vi. protected void doPut(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a PUT request. The PUT operation allows a client to place a file on the server and is similar to sending a file by FTP.

vii.· protected void doTrace(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a TRACE request. ATRACE returns the headers sent with the TRACE request to the client, so that they can be used in debugging. There’s no need to override this method.

viii. protected long getLastModified(HttpServletRequest req)

Returns the time the HttpServletRequest object was last modified, in milliseconds since midnight 1January 1970GMT.If the time is unknown, this method returns a negative number (the default).

ix. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. This method is an HTTP· specific version of the service method. There’s no need to override this method.

x. public void service (ServletRequest req/ ServletRespon,se res) throws ServletException, IOException

Dispatches client request to the protected service method. There’s no need to override this method.

Next Page »

Primary Sidebar

Servlet Tutorials

Servlet Tutorials

  • Servlet - Home
  • Servlet - Types
  • Servlet - Advantages
  • Servlet - Container
  • Servlet - API
  • Servlet - Chaining
  • Servlet - Life Cycle
  • Servlet - Developement Way
  • Servlet - Servlet Vs CGI
  • Servlet - Server Side
  • Servlet - HttpServletRequest
  • Servlet - Cookies Advantages
  • Servlet - JDBC Architecture
  • Servlet - HttpServlet
  • Servlet - HttpServletResponse
  • Servlet - Web Technology
  • Servlet - Applet Communication
  • Servlet - Html Communication
  • Servlet - HTTP POST Request
  • Servlet - HTTP GET Request

Other Links

  • Servlet - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW