Chapter: Internet & World Wide Web HOW TO PROGRAM - Servlets: Bonus for Java™ Developers

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Session Tracking - Servlets

Many e-businesses can personalize users’ browsing experiences, tailoring Web pages to their users’ individual preferences and letting users bypass irrelevant content.

Session Tracking

 

Many e-businesses can personalize users’ browsing experiences, tailoring Web pages to their users’ individual preferences and letting users bypass irrelevant content. This is done by tracking the consumer’s movement through the Internet and combining that data with in-formation provided by the consumer, which could include billing information, interests and hobbies, among other things. Personalization is making it easier and more pleasant for many people to surf the Internet and find what they want. Consumers and companies can benefit from the unique treatment resulting from personalization. Providing content of special inter-est to your visitor can help establish a relationship that you can build upon each time that person returns to your site. Targeting consumers with personal offers, advertisements, pro-motions and services may lead to more customer loyalty—many customers enjoy the indi-vidual attention that a customized site provides. Originally, the Internet lacked personal assistance when compared with the individual service often experienced in bricks-and-mor-tar stores. Sophisticated technology helps many Web sites offer a personal touch to their vis-itors. For example, Web sites such as MSN.com and CNN.com allow you to customize their home page to suit your needs. Online shopping sites often customize their Web pages to in-dividuals, and such sites must distinguish between clients so the company can determine the proper items and charge the proper amount for each client. Personalization is important for Internet marketing and for managing customer relationships to increase customer loyalty.

Hand in hand with the promise of personalization, however, comes the problem of pri-vacy invasion. What if the e-business to which you give your personal data sells or gives those data to another organization without your knowledge? What if you do not want your movements on the Internet to be tracked by unknown parties? What if an unauthorized party gains access to your private data, such as credit-card numbers or medical history? These are some of the many questions that must be addressed by consumers, e-businesses and lawmakers alike.

 

As we have discussed, the request/response mechanism of the Web is based on HTTP. Unfortunately, HTTP is a stateless protocol—it does not support persistent information that could help a Web server determine that a request is from a particular client. As far as a Web server is concerned, every request could be from the same client or every request could be from a different client. Thus, sites like MSN.com and CNN.com need a mecha-nism to identify individual clients. To help the server distinguish between clients, each client must identify itself to the server. There are a number of popular techniques for dis-tinguishing between clients. We introduce two techniques to track clients individually— cookies (Section 30.7.1) and session tracking (Section 30.7.2). Two other techniques not discussed in this chapter are using input form elements of type "hidden" and URL rewriting. With "hidden" form elements, the servlet can write session-tracking data into a form in the Web page it returns to the client to satisfy a prior request. When the user sub-mits the form in the new Web page, all the form data, including the "hidden" fields, are sent to the form handler on the server. With URL rewriting, the servlet embeds session-tracking information as get parameters directly in the URLs of hyperlinks that the user might click to make the next request to the Web server.


1. Cookies

 

A popular way to customize Web pages is via cookies. Browsers can store cookies on the user’s computer for retrieval later in the same browsing session or in future browsing ses-sions. For example, cookies could be used in a shopping application to store unique identi-fiers for the users. When users add items to their online shopping carts or perform other tasks resulting in a request to the Web server, the server receives cookies containing unique identifiers for each user. The server then uses the unique identifier to locate the shopping carts and perform the necessary processing. Cookies could also be used to indicate the cli-ent’s shopping preferences. When the servlet receives the client’s next communication, the servlet can examine the cookie(s) it sent to the client in a previous communication, identify the client’s preferences and immediately display products of interest to the client.

 

Cookies are text-based data that are sent by servlets (or other similar server-side tech-nologies) as part of responses to clients. Every HTTP-based interaction between a client and a server includes a header containing information about the request (when the commu-nication is from the client to the server) or information about the response (when the com-munication is from the server to the client). When an HttpServlet receives a request, the header includes information such as the request type (e.g., get or post) and the cookies that are sent by the server to be stored on the client machine. When the server for-mulates its response, the header information includes any cookies the server wants to store on the client computer and other information such as the MIME type of the response.

Depending on the maximum age of a cookie, the Web browser either maintains the cookie for the duration of the browsing session (i.e., until the user closes the Web browser) or stores the cookie on the client computer for future use. When the browser requests a resource from a server, cookies previously sent to the client by that server are returned to the server as part of the request formulated by the browser. Cookies are deleted automati-cally when they expire (i.e., reach their maximum age).

 

Figure 30.21 demonstrates cookies. The example allows the user to select a favorite programming language and post the choice to the server. The response is a Web page in which the user can select another favorite language or click a link to view a list of book recommendations. When the user selects the list of book recommendations, a get request is sent to the server. The cookies previously stored on the client are read by the servlet and used to form a Web page containing the book recommendations.

 

CookieServlet (Fig. 30.21) handles both the get and the post requests. The CookieSelectLanguage.html document of Fig. 30.22 contains four radio buttons (C, C++, Java and VB 6) and a Submit button. When the user presses Submit, the CookieServlet is invoked with a post request. The servlet adds a cookie containing the selected language to the response header and sends an XHTML document to the client. Each time the user clicks Submit, a cookie is sent to the client.

 

    // Fig. 9.21: CookieServlet.java

    // Using cookies to store data on the client computer.

    package com.deitel.advjhtp1.servlets;

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    import java.util.*;

      public class CookieServlet extends HttpServlet {

      private final Map books = new HashMap();

      // initialize Map books

      public void init()

      {

      books.put( "C", "0130895725" );

      books.put( "C++", "0130895717" );

      books.put( "Java", "0130125075" );

      books.put( "VB6", "0134569555" );

      }

      // receive language selection and send cookie containing

      // recommended book to the client

      protected void doPost( HttpServletRequest request,

      HttpServletResponse response )

      throws ServletException, IOException

      {

      String language = request.getParameter( "language" );

      String isbn = books.get( language ).toString();

      Cookie cookie = new Cookie( language, isbn );

      response.addCookie( cookie );  // must precede getWriter

      response.setContentType( "text/html" );

      PrintWriter out = response.getWriter();

              // send XHTML page to client

 

      // start XHTML document

      out.println( "<?xml version = \"1.0\"?>" );

out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +

"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +

"/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );

 

out.println(

"<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

 

      // head section of document

      out.println( "<head>" );

      out.println( "<title>Welcome to Cookies</title>" );

      out.println( "</head>" );

 

      // body section of document

      out.println( "<body>" );

      out.println( "<p>Welcome to Cookies! You selected " +

      language + "</p>" );      

           

      out.println( "<p><a href = " +

      "\"/advjhtp1/servlets/CookieSelectLanguage.html\">" +

      "Click here to choose    another language</a></p>" );

           

      out.println( "<p><a href = \"/advjhtp1/cookies\">" +

      "Click here to get book recommendations</a></p>" );

      out.println( "</body>" );

 

      // end XHTML document

      out.println( "</html>" );

 

out.close();    // close stream

      }    

           

      // read cookies from client and create XHTML document

      // containing recommended books

      protected void doGet( HttpServletRequest request,

      HttpServletResponse response )

      throws ServletException, IOException

      {

      Cookie cookies[] = request.getCookies();  // get cookies

     

      response.setContentType( "text/html" );

      PrintWriter out = response.getWriter();

     

      // start XHTML document

      out.println( "<?xml version = \"1.0\"?>" );

     

      out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +

      "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +

      "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );

     

      out.println(

      "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

     

      // head section of document

      out.println( "<head>" );

      out.println( "<title>Recommendations</title>" );

      out.println( "</head>" );

 

      // body section of document

      out.println( "<body>" );

 

      // if there are any cookies, recommend a book for each ISBN

      if ( cookies != null && cookies.length != 0 ) {

      out.println( "<h1>Recommendations</h1>" );

      out.println( "<p>" );

 

      // get the name of each cookie

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

      out.println( cookies[ i ].getName() +

      " How to   Program. ISBN#: " +

      cookies[   i ].getValue() + "<br />" );

           

      out.println( "</p>" );

      }

      else {   // there were no cookies

      out.println( "<h1>No Recommendations</h1>" );

      out.println( "<p>You did not select a language.</p>" );

      }

 

      out.println( "</body>" );

 

      // end XHTML document

      out.println( "</html>" );

      out.close();          // close stream

      }

      }

 

Fig. 30.21  Storing user data on the client computer with cookies

Line 11 defines Map books as a HashMap in which we store key/value pairs that use the programming language as the key and the ISBN number of the recommended book as the value. The CookieServlet init method (line 14–20) populates books with four key/ value pairs of books. Method doPost (lines 24–69) is invoked in response to the post request from the XHTML document of Fig. 30.22. Line 28 uses method getParameter to obtain the user’s language selection (the value of the selected radio button on the Web page). Line 29 obtains the ISBN number for the selected language from books.

 

Line 30 creates a new Cookie object (package javax.servlet.http), using the language and isbn values as the cookie name and cookie value, respectively. The cookie name identifies the cookie; the cookie value is the information associated with the cookie. Browsers that support cookies must be able to store a minimum of 20 cookies per Web site and 300 cookies per user. Browsers may limit the cookie size to 4K (4096 bytes). Each cookie stored on the client includes a domain. The browser sends a cookie only to the domain stored in the cookie.

Line 32 adds the cookie to the response with method addCookie of interface HttpServletResponse. Cookies are sent to the client as part of the HTTP header. The header information is always provided to the client first, so the cookies should be added to the response with addCookie before any data is written as part of the response. After the cookie is added, the servlet sends an XHTML document to the client (see the second screen capture of Fig. 30.22).

The XHTML document sent to the client in response to a post request includes a hyperlink that invokes method doGet (lines 73–123). The method reads any Cookies that were written to the client in doPost. For each Cookie written, the servlet recom-mends a Deitel book on the subject. Up to four books are displayed on the Web page created by the servlet.

 

Line 77 retrieves the cookies from the client using HttpServletRequest method getCookies, which returns an array of Cookie objects. When a get or post opera-tion is performed to invoke a servlet, the cookies associated with that server’s domain are automatically sent to the servlet.

 

If method getCookies does not return null (i.e., there were no cookies), lines 106–109 retrieve the name of each Cookie using Cookie method getName, retrieve the value of each Cookie using Cookie method getValue and write a line to the client indicating the name of a recommended book and its ISBN number.

Figure 30.22 shows the XHTML document the user loads to select a language. When the user presses Submit, the value of the currently selected radio button is sent to the server as part of the post request to the CookieServlet, which we refer to as cookies in this example.

 

      <?xml version = "1.0"?>

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

    <!-- Fig. 9.22: CookieSelectLanguage.html -->

 

      <html xmlns = "http://www.w3.org/1999/xhtml">

      <head>

      <title>Using Cookies</title>

        </head>

        <body>

        <form action = "/advjhtp1/cookies" method = "post">

      <p>Select a programming language:</p>

      <p>

      <input type = "radio" name = "language"

      value = "C" />C <br />

     

      <input type = "radio" name = "language"

      value = "C++" />C++ <br />

     

      <!-- this radio button checked by default -->

      <input type = "radio" name = "language"

      value = "Java" checked = "checked" />Java<br />

     

      <input type = "radio" name = "language"

      value = "VB6" />VB 6

      </p>

     

      <p><input type = "submit" value = "Submit" /></p>

     

      </form>

      </body>

      </html>




 

Fig. 30.22 CookieSelectLanguage.html document for selecting a program-ming language and posting the data to the CookieServlet

 

We use our advjhtp1 context root to demonstrate the servlet of Fig. 30.21. Place CookieSelectLanguage.html in the servlets directory created previously. Place CookieServlet.class in the classes subdirectory of WEB-INF in the advjhtp1 context root. Then, edit the web.xml deployment descriptor in the WEB-INF directory to include the information specified in Fig. 30.23. Restart Tomcat and type the following URL in your Web browser:

http://localhost:8080/advjhtp1/servlets/

CookieSelectLanguage.html

 

When the Web page appears, select a language and press the Submit button in the Web page to invoke the servlet.

 

Various Cookie methods are provided to manipulate the members of a Cookie. Some of these methods are listed in Fig. 30.24.

 





 2. Session Tracking with HttpSession

 

Java provides enhanced session tracking support with the servlet API’s HttpSession in-terface. To demonstrate basic session-tracking techniques, we modified the servlet from Fig. 30.21 to use HttpSession objects (Fig. 30.25). Once again, the servlet handles both get and post requests. The document SessionSelectLanguage.html of Fig. 30.26 contains four radio buttons (C, C++, Java and VB 6) and a Submit button. When the user presses Submit, SessionServlet is invoked with a post request. The servlet responds by creating an object of type HttpSession for the client (or using an existing session for the client) and adds the selected language and an ISBN number for the recommended book to the HttpSession object. Then, the servlet sends an XHTML page to the client. Each time the user clicks Submit, a new language/ISBN pair is added to the HttpSession object.

     // Fig. 9.25: SessionServlet.java

    // Using HttpSession to maintain client state information.

    package com.deitel.advjhtp1.servlets;

      import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    import java.util.*;

 

      public class SessionServlet extends HttpServlet {

      private final Map books = new HashMap();

 

      // initialize Map books

      public void init()

      {

      books.put( "C", "0130895725" );

      books.put( "C++", "0130895717" );

      books.put( "Java", "0130125075" );

      books.put( "VB6", "0134569555" );

      }

 

      // receive language selection and create HttpSession object

      // containing recommended book for the client

      protected void doPost( HttpServletRequest request,

      HttpServletResponse response )

      throws ServletException, IOException

      {

      String language = request.getParameter( "language" );

 

      // Get the user's session object.

      // Create a session (true) if one does not exist.

      HttpSession session = request.getSession( true );


// add a value for user's choice to session

session.setAttribute( language, books.get( language ) );

 

      response.setContentType( "text/html" );

      PrintWriter out = response.getWriter();

 

              // send XHTML page to client

1

      // start XHTML document

      out.println( "<?xml version = \"1.0\"?>" );

          out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +

          "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +

          "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );

         

          out.println(

          "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

      // head section of document

      out.println( "<head>" );

      out.println( "<title>Welcome to Sessions</title>" );

      out.println( "</head>" );

      // body section of document

out.println( "<body>" );

out.println( "<p>Welcome to Sessions! You selected " +

 

          language + ".</p>" );

 

          // display information about the session

          out.println( "<p>Your unique session ID is: " +

          session.getId() + "<br />" );

                  

          out.println(

          "This " +     ( session.isNew() ? "is" : "is not" ) +

          " a new session<br />" );

                  

          out.println( "The session was created at: " +

          new Date(   session.getCreationTime() ) + "<br />" );

                  

          out.println( "You last accessed the session at: " +

          new Date( session.getLastAccessedTime() ) + "<br />" );

                  

          out.println( "The maximum inactive interval is: " +

          session.getMaxInactiveInterval() + " seconds</p>" );

                  

          out.println( "<p><a href = " +

          "\"servlets/SessionSelectLanguage.html\">" +

          "Click here to choose another language</a></p>" );

                  

          out.println( "<p><a href = \"sessions\">" +

      "Click here to get book recommendations</a></p>" );

      out.println( "</body>" );

      "Click here to get book recommendations</a></p>" );

      out.println( "</body>" );

      // end XHTML document

      out.println( "</html>" );

          out.close();  // close stream

          }       

      // read session attributes and create XHTML document

      // containing recommended books

      protected void doGet( HttpServletRequest request,

      HttpServletResponse response )

      throws ServletException, IOException

      {

      // Get the user's session object.

 

      // Do not create a session (false) if one does not exist. HttpSession session = request.getSession( false );

       // get names of session object's values

       Enumeration valueNames;

       if ( session != null )

       valueNames = session.getAttributeNames();

       else

       valueNames = null;

       PrintWriter out = response.getWriter();

response.setContentType( "text/html" );

 

// start XHTML document

out.println( "<?xml version = \"1.0\"?>" );

 

       out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +

       "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +

       "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );

 

       out.println(

       "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

 

       // head section of document

       out.println( "<head>" );

       out.println( "<title>Recommendations</title>" );

       out.println( "</head>" );

 

       // body section of document

       out.println( "<body>" );

 

              if ( valueNames != null &&

       valueNames.hasMoreElements() ) {

       out.println( "<h1>Recommendations</h1>" );

       out.println( "<p>" );

       // get value for each name in valueNames


while ( valueNames.hasMoreElements() ) {


          name = valueNames.nextElement().toString();


          value = session.getAttribute( name ).toString();


          out.println( name + " How to Program. " +


          "ISBN#: " + value + "<br />" );


          }


       


out.println( "</p>" );

       }

       else {

       out.println( "<h1>No Recommendations</h1>" );

       out.println( "<p>You did not select a language.</p>" );

       }

              out.println( "</body>" );

 

       // end XHTML document

       out.println( "</html>" );

              out.close();         // close stream

       }

}

 


Fig. 30.25  Maintaining state information with HttpSession objects

Most of class SessionServlet is identical to CookieServlet (Fig. 30.21), so we concentrate on only the new features here. When the user selects a language from the document SessionSelectLanguage.html (Fig. 30.26) and presses Submit, method doPost (lines 24–90) is invoked. Line 28 gets the user’s language selection. Then, line 32 uses method getSession of interface HttpServletRequest to obtain the HttpSession object for the client. If the server has an existing HttpSession object for the client from a previous request, method getSession returns that HttpSession object. Otherwise, the true argument to method getSession indi-cates that the servlet should create a unique new HttpSession object for the client. A false argument would cause method getSession to return null if the HttpSes-sion object for the client did not already exist. Using a false argument could help deter-mine whether a client has logged into a Web application.

 

Like a cookie, an HttpSession object can store name/value pairs. In session termi-nology, these are called attributes, and they are placed into an HttpSession object with method setAttribute. Line 35 uses setAttribute to put the language and the cor-responding recommended book’s ISBN number into the HttpSession object. One of the primary benefits of using HttpSession objects rather than cookies is that HttpSes-sion objects can store any object (not just Strings) as the value of an attribute. This allows Java programmers flexibility in determining the type of state information they wish to maintain for clients of their Web applications. If an attribute with a particular name already exists when setAttribute is called, the object associated with that attribute name is replaced.

After the values are added to the HttpSession object, the servlet sends an XHTML document to the client (see the second screen capture of Fig. 30.26). In this example, the document contains various information about the HttpSession object for the current client. Line 64 uses HttpSession method getID to obtain the session’s unique ID number. Line 67 determines whether the session is new or already exists with method isNew, which returns true or false. Line 71 obtains the time at which the session was created with method getCreationTime. Line 74 obtains the time at which the session was last accessed with method getLastAccessedTime. Line 77 uses method get-MaxInactiveInterval to obtain the maximum amount of time that an HttpSes-sion object can be inactive before the servlet container discards it.

 

The XHTML document sent to the client in response to a post request includes a hyperlink that invokes method doGet (lines 94–159). The method obtains the HttpSes-sion object for the client with method getSession (line 100). We do not want to make any recommendations if the client does not have an existing HttpSession object. So, this call to getSession uses a false argument. Thus, getSession returns an HttpSession object only if one already exists for the client.

 

If method getSession does not return null, line 106 uses HttpSession method getAttributeNames to retrieve an Enumeration of the attribute names (i.e., the names used as the first argument to HttpSession method setAttribute). Each name is passed as an argument to HttpSession method getAttribute (line 141) to retrieve the ISBN of a book from the HttpSession object. Method getAttribute receives the name and returns an Object reference to the corresponding value. Next, a line is written in the response to the client containing the title of the recommended book and that book’s ISBN number.

 

Figure 30.26 shows the XHTML document the user loads to select a language. When the user presses Submit, the value of the currently selected radio button is sent to the server as part of the post request to the SessionServlet, which we refer to as ses-sions in this example.

We use our advjhtp1 context root to demonstrate the servlet of Fig. 30.25. Place

 

SessionSelectLanguage.html in the servlets directory created previously. Place SessionServlet.class in the classes subdirectory of WEB-INF in the advjhtp1 context root. Then, edit the web.xml deployment descriptor in the WEB-INF directory to include the information specified in Fig. 30.27. Restart Tomcat and type the following URL in your Web browser:

 

http://localhost:8080/advjhtp1/servlets/

SessionSelectLanguage.html

 

When the Web page appears, select a language, and press the Submit button in the Web page to invoke the servlet.

 

      <?xml version = "1.0"?>

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

    <!-- Fig. 9.26: SessionSelectLanguage.html -->

 

      <html xmlns = "http://www.w3.org/1999/xhtml">

      <head>

      <title>Using Sessions</title>

        </head>

 

        <body>

        <form action = "/advjhtp1/sessions" method = "post">

 

        <p>Select a programming language:</p>

<p>

<input type = "radio"   name = "language"

value = "C" />C <br /> 

         

<input type = "radio"   name = "language"

value = "C++" />C++ <br />

         

<!-- this radio button checked by default -->

<input type = "radio"   name = "language"

value = "Java" checked = "checked" />Java<br />

         

<input type = "radio"   name = "language"

value = "VB6" />VB 6   

     </p>     

     <p><input type = "submit" value = "Submit" /></p>   

     </form>

     </body>

     </html>





Fig. 30.26 SessionSelectLanguage.html document for selecting a rogramming language and posting the data to the SessionServlet

 



Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.