Servlets and Web Sessions

The Hypertext Transfer Protocol (HTTP) is by design a stateless protocol. However, an effective Web application requires that a series of requests from a particular client be grouped together. The notion of grouping multiple requests from a single client is typically referred to as a Web session.

Conventional Methods for Session Tracking Are Difficult

In the early days of the Web, few mechanisms were available for session tracking. The earliest of these was hidden form fields in pages. Later, this was supplanted by the use of cookies and URL rewriting. Cookies are defined text objects that can be placed in the user's offline store, via their browser. Subsequent requests to a site retrieve the cookie, which serves the session information. URL rewriting does much the same thing except it adds the session information to the extended URL of subsequent requests.

These early mechanisms were not ideal. Hidden fields are hard to manage. As for cookies, many users rejected them because they considered cookies to be a violation of their privacy. URL rewriting displays a messy URL to the user. In each case, you are storing user session information on the client, where it is subject to attack. (Malicious hackers can change the data in the cookies to wreak havoc in your Web system.) Finally, shipping volumes of client data over the wire can slow down even the fastest Web servers.

The Servlet Specification to the Rescue

A major advantage of the servlet specification over other dynamic content generation technologies is its support for session tracking that keeps the user information on the server. Via the server, cookies can be stored in a database and made persistent. By design, URL rewriting persists only during an active HTTP session.

The servlet object that tracks a user's state is called javax.servlet.http.HttpSession, which is available as part of the HttpServletRequest object. This mechanism enables session information to be automatically handled by WebLogic Server. Developers don't need to deal with the details of tracking sessions.

Session Identification

Every session is given a unique, randomly generated session identification number. The servlet engine uses this number to track sessions. WebLogic Server automatically handles the assignment of session ID numbers and transparently places session information in the client browser. This information is a placeholder to match the browser to the HttpSession object that is automatically created for each user session. In addition, as of Version 5.1 and above, WebLogic Server supports the capability to configure the length of the session ID.

Technically, WebLogic Server automatically creates temporary cookies for each browser session with a very long number, the session identifier, each time a session is created. WebLogic Server places these temporary cookies in the client browser. This cookie is sent along with each subsequent request that the browser makes. WebLogic Server automatically maps the session identifier to the HttpSession object it is tracking for that user. When the servlet is invoked to handle the request, WebLogic Server locates the appropriate HttpSession and automatically hands that off to the servlet.

If a browser has disabled cookies, WebLogic Server automatically attempts to use URL rewriting, which involves adding information usually kept in the cookie to the end of the URL string.

For most standard Web browser clients, the default length of session IDs is acceptable. In other cases, such as for wireless (WAP) devices, shorter session IDs are required. Where possible, the best practice is to use the longest session ID possible to ensure security. The longer the session ID, the more difficult it is for attackers to randomly guess numbers that might be valid session IDs and masquerade as a valid user.


Accessing the Session Object

The session object exists during the lifetime of the session and is available for each new request by the same client. A reference to the HttpSession object can be obtained from the HttpServletRequest object using the HttpServletRequest.getSession() method like this:

HttpSession session = request.getSession (false);

This method takes a Boolean. If the value is true, a new session object is created if one does not already exist. If the value is false, the server does not create a new session object. For reasons that become apparent later, you typically want to set a value of false when you call this method.

What to Put in Your Session

There are a number of things you could store in a session object, including:

  • Virtual shopping carts to hold the items that a user is currently interested in purchasing.

  • A history of what a resources user has looked at during the current session. For example, if you are building an e-commerce site, you'll want to see what pages the user has visited during the session, to help decide what other things to show him or her.

There also are things that you would not want to store in a session object, including long-term data, such as a user record or profile.

Recognizing New Sessions

Use the isNew() method of the HttpSession object to determine if you are accessing a new session. For example, you can use this method to force users to log in each time they begin a new session, which prevents them from bypassing your security mechanisms.

After you acquire the session object, check to see if it is null (that is, its value has not already been set). If it is not null, then you can continue using the session. If it is null, you simply redirect the client browser to the login page for your Web application:

HttpSession session = request.getSession (false);

If (session==null) {
// We  Send a Redirect
responseObj.sendRedirect("http://www.blahblah.com/login");

}

What NOT to Do

On the other hand, do not do something like this:

// An Example of What Not to Do:
HttpSession session = request.getSession (true);
// Check to See If the Session Is New
If (session.isNew()) {
// We  Send a Redirect
responseObj.sendRedirect("http://www.blahblah.com/login");
}

In this code, we ask for the session object as usual. However, because we set the parameter value equal to true in the getSession method, a new session is created if one does not already exist. Unfortunately, this leaves a security hole: Someone could create a large number of session objects, which could eat up memory on your server for as long as he or she wanted to make requests.

Check for new sessions in your servlets to ensure that someone is not trying to “work around” your security measures by not logging in.


Storing and Accessing Session Data

Session data is stored in the session object (HttpSession) via name/value pairs. With each name, which is a string value, the HttpSession object stores a value. This value can be any Java type.

Store user information such as shopping carts in a session object for your servlets.


The servlet specification defines four methods that you can use to access the values in the HttpSession object. These are:

  • public Object getAttribute (String name)— Returns the object bound with the specified name in this session, or null if no object is bound under the name.

  • public void setAttribute (String name, Object attribute)— Binds an object to this session using the name specified.

  • public Enumeration getAttributeNames()— Returns an Enumeration of string objects containing the names of all the objects bound to this session.

  • public void removeAttribute(String name)— Removes the object bound with the specified name from this session.

The Scope of a Session

In WebLogic Server, a session begins when a user first accesses the site and a servlet instructs that a new session be created. WebLogic Server creates the HTTP session object and attaches cookies to the browser for the duration of the browser session. The browser session is a single continuous period of time in which the Web browser is active on the client. If the user shuts down the Web browser, these particular cookies disappear. While the particular HTTP session object is stored in WebLogic Server until a timeout is reached, the removal of the cookie from the browser means that the HTTP session object for that browser is no longer accessible.

The timeout interval for sessions is specified in the WebLogic Server configuration. If there is no request to WebLogic Server for the duration of the timeout interval, WebLogic Server automatically invalidates and removes the HTTP session. If a user returns to WebLogic Server after the session has been closed, that user has to log in again, and any information that you have kept in the HTTP session object is gone.

It is also possible to declare the session to end in your servlets, as we see in this next section.

HttpSession objects themselves should not be considered to be available outside the scope of the request. Therefore, you should not pass references to the session objects that you receive in your session() method. If you want to use those values elsewhere, you should make a clone() of them first.

Note that this refers to the HttpSession objects themselves and not the attributes that you bind into it. Attributes are available outside of the scope of the session.


Invalidating a Session

Invalidate a session when a user performs some specific action, such as logging out. Use the invalidate() method of the HttpSession object, like this:

// Create the Session Object
HttpSession session = request.getSession (false);
// Invalidate the Session
session.invalidate();

The HTTP session is cleared and invalid for further use. The next time the user visits your servlet, a new session object is created.

When users want to log out, do so by invalidating their session.


Sessions, Inactivity, and Time

The HttpSession object supports other useful methods:

  • public long getCreationTime();— Returns a long integer that represents when the session was created. To print the creation time of the object:

    HttpSession session = request.getSession (true);
    // Get the Creation Time and Print it
    system.out.println(session.getCreationTime());
    
  • public String getId();— Returns a long integer of the ID number that WebLogic Server has associated with the session. To print the ID number of the servlet session:

    HttpSession session = request.getSession (true);
    // Get the Creation Time and Print it
    system.out.println(session.getID());
    
  • public long getLastAccessedTime();— Returns a long integer that represents the last time the session object was accessed.

  • public int getMaxInactiveInterval();— Returns an integer that represents the number of seconds that the session can be inactive before it is automatically removed by WebLogic Server.

  • public void setMaxInactiveInterval(int interval);— Sets the number of seconds that the session can be inactive before the session is invalidated.

Sessions consume resources in WebLogic Server. For that reason, set your inactive intervals to be as short as possible.


Sessions and Servlets Example

Building servlets to use sessions is relatively simple. As an example, let's build a servlet that counts the number of times you have visited a given page. To do so, insert a counter object into the session object for the user. Each time the user revisits the page, we update and increment the counter object.

First, import the necessary classes and declare your class name:

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

public class SessionServlet extends HttpServlet {

    /*
       Next, create a method to handle the
       GET request for your servlet:
    */

public void doGet (HttpServletRequest req, HttpServletResponse
res)
       throws ServletException, IOException
  {
    /*
       Get the session object
    */
    HttpSession session = req.getSession(true);

    /* set content type and other
       response header fields first */
    res.setContentType("text/html");

    /*
       then write the data of the response
    */
    PrintWriter out = res.getWriter();
    out.println("<HEAD><TITLE> " + "SessionServlet Output " +
                "</TITLE></HEAD><BODY>");
    out.println("<h1> SessionServlet Output </h1>");

    /*
      Retrieve the count value from the session
    */
Integer ival = (Integer)
session.getAttribute("sessiontest.counter");

    /*
      If the counter is not currently contained in the session,
      one needs to be created:
    */

    if (ival==null) {
      ival = new Integer(1);
    } else {
      ival = new Integer(ival.intValue() + 1);
    }

    session.setAttribute("sessiontest.counter", ival);

    /*
      And print out how many times the user has hit the
      current page:
    */
    out.println("You have hit this page <b>" + ival +
    "</b> times.<p>");
    out.println("Click <a href=" + res.encodeURL("session") +
                ">here</a>");
    out.println(" to ensure that session tracking is working even
" +
                "if cookies aren't supported.<br>");
    out.println("<p>");

    /*
      Finally, demonstrate some of the more common methods in the
      HttpSession object surrounding sessions:
    */
    out.println("<h3>Request and Session Data:</h3>");
    out.println("Session ID in Request: " +
                req.getRequestedSessionId());
    out.println("<br>Session ID in Request from Cookie: " +
                req.isRequestedSessionIdFromCookie());
    out.println("<br>Session ID in Request from URL: " +
                req.isRequestedSessionIdFromURL());
    out.println("<br>Valid Session ID: " +
                req.isRequestedSessionIdValid());
    out.println("<h3>Session Data:</h3>");
    out.println("New Session: " + session.isNew());
    out.println("<br>Session ID: " + session.getId());
    out.println("<br>Creation Time: " + session.getCreation-
Time());
    out.println("<br>Last Accessed Time: " +
                session.getLastAccessedTime());
					 
    out.println("</BODY>");
  }
}

The output of this servlet looks something like Figure 3-13.

Figure 3-13. Servlet Output


If you click refresh to visit this page multiple times, you'll see that the counter increments each time by incrementing the HTTP session object. If you restart the Web browser, the counter restarts at 1 because the previous session has been removed from WebLogic Server.

Deploying the Session Servlet in WebLogic Server

In order to deploy the session servlet, you can use the code included on the CD accompanying this book. It is located in the file named sessionServlet.war, which is located in the subdirectory /examples/ch3. It is deployed using the same process used for the Hello servlet example and every other application sample.

The Servlet API enables you to specify that the objects you place in the HTTP session can be notified when they are added to or removed from the session object. This is an advanced technique, which is not discussed in detail in this book. However, you can learn more about session notification from the servlet API documentation, at http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpSessionBindingListener.html.

To specify the objects that you want to be notified when they are removed from or added to a session, implement this interface, including the two methods:

public void valueBound(HttpSessionBindingEvent event)
public void valueUnBound(HttpSessionBindingEvent event)

Your class definition may look like this:

import javax.servlet.http;

public class myObjectInSession implements
HttpSessionBindingListener  {

These methods on the object are called when the object is bound and unbound into the HttpSession object. The single parameter is an instance of HttpSessionBindingEvent, which includes information about the event that has happened. More information on this class is available at

http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpSessionBindingEvent.html.


Baking Your Own Cookies

While WebLogic Server uses cookies for its internal mechanisms, it also enables developers to create their own cookies either in conjunction with servlet sessions or alone. Cookies are very useful for storing long-term identities for users. For example, you might want users to be recognized when they return to the bookstore so they do not have to log in every time. To facilitate this, place a cookie on the user's Web browser using the APIs provided in the servlet engine. (This assumes that the user permits cookies to be attached to his or her Web browser.)

A cookie contains the following data:

  • Name

  • A single value

  • Optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number

Cookies can store information over a long period of time. However, this does not mean that they are appropriate for storing sensitive data. For long-term storage of sensitive data, the best practice is to use a database. Using WebLogic Server to access a database via the J2EE standards is covered in Chapter 5, Using Databases and Transactions with JDBC and JTA.


Cookies vs. Servlet Sessions

Servlet sessions have a limitation in that they are only active for a short period of time. Typically, servlet sessions only last as long as the lifetime of the browser session, or a (shorter) defined period of time. Once the Web browser is exited or the session “times out,” WebLogic Server automatically disposes of the HttpSession object.

When you want your Web application automatically to recognize a given user without requiring him or her to log back in, use a cookie.

Here are other examples of when to use servlets and when to use cookies.

Problems best solved with a servlet session:

  • Tracking a user shopping cart

  • Caching data such as account balances that the user might look up more than once during a session

  • Storing references or addresses of resources on which you are relying

Problems best solved with a cookie:

  • “Remembering users” over a long period of time

Dealing with Users

Web applications typically attempt to personalize content. In the WebAuction application, when a given user logs in, only that user's auction items are displayed. Similarly, an online bookstore might use a recommendation engine to recommend books according to your personal tastes, when you visit the site.

How to Track Users

For the most part, WebLogic Server handles users and logins automatically. Security on components is handled by configuring the Web application deployment descriptor. WebLogic Server has its own security store, and supports connections to external security stores. WebLogic Server automatically maps users of your Web application to known security stores. When a user visits your site, WebLogic Server handles authentication and permissions for you. Chapter 12 contains a complete example of coding and configuring user login and tracking for a Web-based application.

Creating a Cookie

The process of creating a cookie is very simple. First, you need to create the cookie object by creating an instance of the cookie class, which is part of the servlet package. The constructor for a cookie class takes two parameters: a name for the cookie and a value. This value is the information that you want to store, such as the user's name or any arbitrary string value. To create a cookie, put the following in your servlet:

Cookie myCookie = new Cookie(" Cookie name ", "63");

Then, add your cookie to the HTTP response:

response.addCookie(myCookie);

Note that the values stored in cookies can only be strings. Therefore, you should text-encode all data that you store in a cookie. Once you add a cookie to your response object, WebLogic Server automatically places it in the client browser, which stores it on the local computer disk.

Getting Cookies

When WebLogic Server invokes a servlet, the cookies sent by the browser are included in the HttpServletRequest object that is passed as a parameter to your service method. These are stored as an array of cookie objects. To access them, use the following code:

Cookie[] cookies = request.getCookies();

Once you have the cookie objects, you can search for your specific cookie. You can use the getname() method to look at each cookie's name:

// Assign the Name of the First
// Cookie in The Array to String foo
String foo = Cookies[0].getname();

Note that you can use more than one cookie. The typical browser supports 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4KB each.


Useful Methods for Dealing with Cookies

There are a number of other methods that you can use with cookies:

  • public void setComment(String comment); and public String getComment();— Can be used to set the comment field in your cookie. This is very useful for occasions when individuals are browsing their cookie store on their Web browser. To set the comment field in a cookie named myCookie, place the following code in your servlet:

// Set the Comment Field in Cookie myCookiemyCookie.setComment("gumby999");

  • public void setMaxAge(int expiry); and public int getMaxAge();— Set and get the number of seconds before the cookie expires. A value of negative one (-1) means that the cookie expires when the Web browser exits. To make your cookies last indefinitely, set the value as high as possible:

// Set the cookie myCookie to last indefinitely
myCookie.setMaxAge(Integer.MAX_VALUE);

  • public String getValue() and public void setValue(String newValue)— Enable you to access the value stored in the cookie and set the value stored in the cookie, respectively.

  • public void setSecure(boolean); and public boolean getSecure();— Enable you to set the security settings for the cookie. The following code requires that the cookie be sent only over a secure channel such as SSL:

// Require That the Cookie myCookie
// Only Be Sent over Secure Channels
myCookie.setSecure(true);

URL Rewriting

What if a client does not accept cookies? URL rewriting is a way of dealing with clients who do not accept cookies. URL rewriting works by adding a session ID to the end of the URL returned to clients in your response method. It can be used in place of cookies by your application. URL rewriting only lasts for the scope of the session.

Using URL rewriting is also important when using Web frames and redirects. Depending on timing or the type of request, the cookie may not be sent with subsequent requests from the browser. If you notice that your Web site mysteriously loses contact with the user sessions when frames are being used, you should attempt to enable URL rewriting to solve the problem.

WebLogic Server uses URL rewriting at the beginning of every session to ascertain whether the client supports cookies. If the client browser does support cookies, then WebLogic Server automatically uses cookies. If not, WebLogic Server can be configured to use URL rewriting.

To enable URL rewriting in WebLogic Server, set the "URLRewritingEnabled" attribute in <session-descriptor> to true in the WebLogic Server–specific deployment descriptor, weblogic.xml. (The default value for this attribute is true.)

<session-descriptor>
  <session-param>
    <param-name>
      URLRewritingEnabled
    </param-name>
    <param-value>
      true
    </param-value>
  </session-param>
</session-descriptor>

Using URL Rewriting in Applications

URL rewriting requires a method in the servlet response object to encode the URL. This method takes two forms:

  • public String encodeURL(String url);— Includes the logic required to encode the session information in the returned URL. WebLogic Server automatically determines whether the session ID needs to be encoded in the URL. If the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary. To encode the URL, add the following code to your servlet:

// Add the Session Information Via URL Encoding
myHttpServletResponse.encodeURL(thisURL);

  • public String encodeRedirectURL(String url);— Performs the same task as the previous method, except it is specially geared to redirects in the response object. For redirection you should have the following in your servlet:

// Sending a Redirect with URL Encoded session ID
myHttpServletResponse.sendRedirect
         (myHttpServletResponse.encodeRedirectUrl(anotherURL));

So, if your original URL was:

<a href="foo.jsp">bar</a>

You would use the HttpServletResponse.encodeURL() method, on that URL:

  out.println("<a href=""
+ response.encodeURL("<a href="foo.jsp">")
+ "">bar</a>");

Note that all servlets in an application must use URL rewriting for this to work properly.

Testing URL Rewriting

Once you get URL rewriting engaged, the clients that you point at your server see a difference. In fact, you see something like this:

http://www.shinn.com/index.html;jsessionid=1234

The Session ID number is encoded at the end of the URL for each page.

Servlet/JSP developers should always use the URL encoding methods when embedding URLs in their HTML so that WebLogic Server can properly take advantage of URL rewriting if the client's browser does not accept cookies.


Custom Cookies for Personalization

Applications that remember users over long periods of time and across browser sessions set their own cookie (different from the cookies used by WebLogic Server) after the user logs in to the site. In subsequent contact with the server that set the cookie, the browser piggybacks that cookie onto the request. The application can check to see whether that cookie exists and log in the user automatically, without requiring a user name and password for authentication.

This kind of behavior is common in many e-commerce sites. For example, Amazon.com remembers users by a cookie stored in the browser. When you return to their site, you do not need to log in again.

The first step in implementing a custom login cookie is to add the mechanism to set and look for the cookie in your pages. The following is a trivial doGet method that indicates how to look for a cookie showing that the user does not need to log in:

public void doGet(HttpServletRequest req, HttpServletResponse
res)
    throws IOException
{
    boolean cookieFound = false;
    Cookie thisCookie = null;

    /*
      Ask for the session object associated with the request.
      Because we are passing a parameter of false, a new
      session is not automatically created.
    */
    HttpSession session = req.getSession (false);

    // If we were unable to find a new session...
    if (session==null) {

       // Try to retrieve the cookie from the request.
       Cookie[] cookies = req.getCookies();

       /*
          Look through all the cookies and see if the
    cookie with the login info is there.
       */
       for(int i=0; i < cookies.length; i++) {
           thisCookie = cookies[i];
           if (thisCookie.getName().equals("LoginCookie")) {
             cookieFound = true;
             break;
           }
       }

       /*
          If we found the cookie, then we know who this is because
          the value of the cookie is the username of this user.  We
           first create a new session.  Next, we refresh
           the cookie stored in the browser.
       */
       if (cookieFound) {

           // Create a new session for this user.
           HttpSession session = req.getSession (true);

          /*
              If you are assigning a user name to each user, then
            you'll likely want to update that value in the session
              that you just created.
          */
          session.setAttribute("username", this-
Cookie.getValue());

          // Set this cookie so that it will live indefinitely.
          thisCookie.setMaxAge(Integer.MAX_VALUE);

         // Add the cookie to the response
         res.addCookie(thisCookie);
     } else {
         /*
           If we were unable to find a session and we were unable
           to find a cookie for this user, then we redirect
           to our login page.
         */
responseObj.sendRedirect("http://www.blahblah.com/login");
            }
          }

         // Continue with the business of the servlet here...
}

Long-Term CookieServlet Example

In this example, we use the preceding code to create two servlets. The first servlet, CookieServlet, checks to see if your browser has a cookie stored named “LoginCookie”. If you do not have this cookie, you are redirected to another servlet. This second servlet, putCookieServlet, creates a new “LoginCookie” and places it in your browser. When you visit the CookieServlet again, it recognizes that you have the appropriate cookie and allows you to access the site.

putCookieServlet.java

This servlet takes a request, creates a new cookie, places that in the user browser, and replies to the HTML page. This HTML page reports that the cookie has been implanted in the browser:

package com.learnweblogic.examples.ch3;

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

public class putCookieServlet extends HttpServlet {

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

    // Create a new cookie object:
    Cookie thisCookie = new Cookie("LoginCookie", "Michael");

    // Set this cookie so that it will live indefinitely.
    thisCookie.setMaxAge(Integer.MAX_VALUE);

    // Add the cookie to the response
    res.addCookie(thisCookie);

    /*
      Set the appropriate return content type, and begin to compose
      the HTML page:
    */
    res.setContentType("text/html");
    PrintWriterout = res.getWriter();

    out.println("<html>");
    out.println("<head><title>putCookieServlet</title></head>");
              out.println("<body>");

    out.println("A cookie has been added to your browser." +
      "Now go back and visit the CookieServlet.");

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

  }

}

CookieServlet.java

This servlet takes a request and checks to see if a user has the appropriate cookie in the browser. If not, the user is automatically redirected to the putCookieServlet, which is contained in the same Web application. If the user has the correct cookie, then a welcome message is displayed:

package com.learnweblogic.examples.ch3;

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

public class cookieServlet extends HttpServlet {

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

    boolean cookieFound = false;
    Cookie thisCookie = null;

    /*
      Ask for the session object associated with the request.
      Because we are passing a parameter of false, a new
      session is not automatically created.
    */
    HttpSession session = req.getSession (false);

    // If we were unable to find a new session...
    if (session==null) {
      // Try to retrieve the cookie from the request.
      Cookie[] cookies = req.getCookies();

      /*
         Look through all the cookies and see if the
         cookie with the login info is there.
      */
      for(int i=0; i < cookies.length; i++) {
        thisCookie = cookies[i];
        if (thisCookie.getName().equals("LoginCookie")) {
          cookieFound = true;
          break;
        }
      }

      /*
         If we found the cookie, then we know who this is because
         the value of the cookie is the username of this user.  We
         first create a new session.  Next, we refresh
         the cookie stored in the browser.
      */
      if (cookieFound == true) {

        // Create a new session for this user.
        session = req.getSession (true);

        /*
           If you assign a user name to each user,
           update that value in the session
           that you just created.
        */
        session.setAttribute("username", thisCookie.getValue());

        // Set this cookie so that it lives indefinitely.
        thisCookie.setMaxAge(Integer.MAX_VALUE);

        // Add the cookie to the response
        res.addCookie(thisCookie);

        /*
        Set the appropriate return content type, and begin to compose
         the HTML page:
        */
        res.setContentType("text/html");
        PrintWriter     out = res.getWriter();

        out.println("<html>");
        out.println("<head><title>CookieServlet</title></head>");
        out.println("<body>");

    out.println("You had visited us before at the put cookie servlet!"
       + "Welcome!");

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

  } else {
        /*
          If we were unable to find a session or
          a cookie for this user, then we redirect
          to our login page.
        */
        res.sendRedirect(
          " /cookieServlet/putCookieServlet");

      }
    }

    // Continue the servlet here...

  }
}

Notice that the servlet uses the sendRedirect() method on the HTTP response object to instruct the browser to redirect to another URL. In this case, the redirect automatically goes to the servlet that installs the cookie on the browser, putCookieServlet.

In a real-world situation, you want your application to recognize new users and automatically log them in to WebLogic Server. In Chapter 12, Developing Security with WebLogic Server JNDI and JAAS we further discuss how to have your application log in an existing user.

Deploying the CookieServlet in WebLogic Server

To deploy the cookie servlet, use the code included on the CD accompanying this book, in /code/ch3/cookieServlet.war.

Step 0: Installing the CookieServlet Application

Follow the steps used in previous examples to build and deploy the application code. Be sure to create a new directory for your work.

Step 1: Modifying Browser Settings

To view the cookie servlet, modify your Web browser to enable you to see better what happens with cookies. If you are using Netscape Navigator Version 4, locate the Preferences option in the Edit menu. Choose the Advanced option in the left-hand panel. You see a screen such as the one in Figure 3-14.

Figure 3-14. Netscape Navigator's Preferences Dialog


Select the option to warn you before accepting cookies. This enables you to see any cookies that WebLogic Server intends to put into your browser. Microsoft Internet Explorer requires that you modify the settings and set your Internet security configuration for the browser. If you decide not to modify your browser settings, you won't see the details of the cookie placement—but the example still works.

Step 2: Visiting the CookieServlet

Visit the CookieServlet by pointing your Web browser at the deployment location for your WebLogic Server instance. If you have deployed on your local machine, at port 7001 (the default), you can view the example at http://127.0.0.1:7001/cookieServlet/cookieServlet.

You should be immediately redirected to the putCookieServlet (see Figure 3-15), which tells you the following:

Figure 3-15. Response from putCookieServlet


Click OK. You should see the cookie servlet display (see Figure 3-16).

Figure 3-16. CookieServlet Display


Step 3: Revisiting the CookieServlet

Visit the CookieServlet again, with the same Web browser, at http://127.0.0.1:7001/cookieServlet/putCookieServlet.

You should see the cookie servlet shown in Figure 3-17.

Figure 3-17. Revisiting the CookieServlet


The CookieServlet recognizes that you now have the correct cookie in your Web browser and welcomes you.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.165.247