by Dinesh Thakur Category: Session And Cookies

In a web server, a session is a collection of all the requests made by a client (browser). HTTP is a stateless protocol. Between requests, it does not maintain any state of the client (browser). Suppose the client makes request for a web page, it should be checked whether the request is from an authorized user. It is impossible to check the authorization for each web page. It is necessary to maintain some information of the user while a user navigates between web pages. Thus, it is useful to maintain the state of client. The following processes arc used to maintain the state of a client:

• URL rewriting

• Hidden fields

• Cookies

• Sessions

Hidden fields Hidden fields are the easiest way of maintaining the state of a client. These are the same as the HTML input tags. These are specified as follows:

<inputtype="HIDDEN" name="item" value="Book" >

These tags will not display anything on the web page but are very useful to present some information to the next page as name-value pairs.

Rewriting URLs Rewriting the URL plays an important role in the session management of the HTTP. This method passes the state information between the client and server by embedding the information as name-value pairs in the URL.

  <A href ="SampleServletlitem = Book&quantity =5">ltems</A> or                

   <form method ="Get" action="SampleServlet?item = Book&quantity=5">

Name-value pairs are placed within the anchor tag separated by the ampersand (&). The Servlet API is capable of accessing the QueryString (name-value pairs after the URL that are found after the question mark (?)) by using the getParameterValue() and getParameterNames() methods of the ServletRequest object.

Cookies Another way to maintain the state of a client is by using cookies. A cookie is an object sent by the server to a client. A cookie is created by the server and sent to the client along with the requested response. Each cookie has a definite lifetime. In general, cookies are insecure and, thus, they are considered to make privacy issues difficult.

Cookies contain small bits of information created by the server and stored at the client machine. These are created when the client makes the first request to the servlet. They are sent to the client along with the response and stored in the client. With each subsequent request, the client sends the information contained in these cookies to the server as the request header.

The Servlet API provides the Cookie class to tackle the concept of cookies. This class manipulates all the technologies of the cookie. The constructor of the Cookie class is the following:

         public Cookie(String name ,String value);                    

After the Cookie class is created, some value is stored within this and it is added to the HttpServletReponse object using the addCookie method, as shown below:

         addCookie(cookie);

It is important that the cookie must be added to the response before any other response is created, including the content type.

Http sessions The state of the HTTP can also be maintained by using sessions. Like cookies, sessions are also used to store information except that the information is stored in the server machine under an unique session identification number. These session identification numbers also exist at the client as cookies. When a request is made, then the session identification number is also sent along with the request information so that the server can uniquely identify the client and provide the client information. The Servlet API provides the interface Httpsession which maintains the relevant information such as the unique session identification number and client specific information. The syntax for using HttpSession is as follows:

                      HttpSession session= httpservletrequest.getSession( )

Here httpservletrequest is an object of the HttpServletRequest interface.

Program Using HttpSession to maintain information on the client's state.

import javax.servlet.*; 
import javax.servlet.http.*;
import java.io.*;
public class TestServlet extends HttpServlet
{
    String Name;
    public void init(ServletConfig config) throws ServletException
   {
        super.init(config);
        Name=config.getlnitParameter("name");
    }
  public void doGet(HttpServletRequest req,HttpServletResponse res) throws                  ServletException, IOException
    {
        res.setContent Type("text/html");
        PrintWriter pout=res.getWriter();
         // getting the session object
        HttpSession session=req.getSession();
        pout.write("Getting the Session id of servlet;"+ session.getld());
        pout.write("Here we are setting the session interval");
        session. set MaxInactivelnterval(20);
         // lnactive Interval is set
        pout.write("The Inactive interval:"+ session.getMaxlnactivelnterval());
        session.putValue("name", "Kumar");
        pout.write("Getting the session value:"+ session.getValue("name"));
        session.invalidate();
       pout.close();
    }
       public void destroy(){}
}
                      




About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.