Exporteren (0) Afdrukken
Alles uitvouwen
EN
Deze inhoud is niet beschikbaar in uw taal, maar wel in het Engels.

How to Maintain Session Data with Session Affinity

Updated: September 25, 2014

The following steps show you how to build an application that maintains session data by using session affinity (also called sticky sessions) and the javax.servlet.http.HttpSession object.

The application will look similar to the following:

Session state example

  1. Use the code created at either one of the following topics as your starting point:

  2. Familiarity with building an application and deploying it to Azure, as described at Creating a Hello World Application for Azure in Eclipse.

  1. Modify your Azure project settings to maintain session affinity, as described at Session Affinity.

  2. Modify index.jsp to use the following code:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1" 
        import="com.microsoft.windowsazure.serviceruntime.*"
        import="java.util.*"
        import="java.text.DateFormat"
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Session affinity example</title>
    <head/>
    <body>
    <p/>
    <%
    
    // Track the number of times this session has been visited.
    Integer visits = (Integer) session.getAttribute("visits");
    
    if (null == visits)
    {
        // Visits are not yet being maintained in session data.
        // Initialize this as the first visit. 
        visits = new Integer(1); 
    }
    else
    {
        // Visits are being maintained in session data.
        // Increment the visit tracker. 
        visits = new Integer(visits.intValue() + 1);  
    }
    
    // Update the session data to include the current count of visits.
    session.setAttribute("visits", visits); 
     
    // See if the user name is already part of the session data.
    String name;
    name = (String) session.getAttribute("username");
     
    if (null == name)
    {
        // The user name does not exist in the session data.
        // See if the user provided a name in the form.
        name = request.getParameter("username");
        if (null != name && "" != name)
        {
            // Store the username as session data. 
            session.setAttribute("username", name);
    
             // Welcome the new user.
         %>
        <p>Welcome <%= name %>!</p>
        <% 
        }
        else
        {
            // A name has not been entered by the user for this session.
            // Display a form and retrieve the user's namee.
            %>
           <form action="<%=request.getRequestURI() %>" method="post">
            Enter your name: <input type="text" name="username" /> (Press the <b>Enter</b> key when done)
            </form> 
            <%
        }
    }
    else
    { 
        // Welcome the returning user.
        %>
        <p>Welcome back <%= name %>!</p>
        <% 
    }
    
    // Display the session information.
    DateFormat dfDate = DateFormat.getDateInstance(DateFormat.FULL);
    DateFormat dfTime = DateFormat.getTimeInstance();
    
    long creationTime = session.getCreationTime();
    long lastAccessedTime = session.getLastAccessedTime();
    
    Date dateCreated = new Date(creationTime);
    Date dateLastAccessed = new Date(lastAccessedTime);
    
    %>
    <p/>
    <table border=1 width=90% >
    <tr><th>Session information</th><th>Value</th></tr>
    <tr><td>Session ID</td><td><%= session.getId() %></td></tr>
    <tr><td>New or existing</td><td><%= (session.isNew() ? "New" : "Existing") %></td></tr>
    <tr><td>Created</td><td><%= dfDate.format(dateCreated) %> <%= dfTime.format(dateCreated) %></td></tr>
    <tr><td>Last accessed</td><td><%= dfDate.format(dateLastAccessed) %> <%= dfTime.format(dateLastAccessed) %></td></tr>
    <tr><td>Maximum inactive interval</td><td><%= Integer.toString(session.getMaxInactiveInterval()) %> seconds</td></tr>
    <tr><td>Visits or refreshes by you to this session</td><td><%= visits.intValue() %></td></tr>
    <tr><td>Azure deployment ID</td><td><%= RoleEnvironment.getCurrentRoleInstance().getId() %></td></tr>
    <tr><th>Session attributes</th><th>Value</th></tr>
    <%
    
    // Determine the sessions attributes, by name.
    Enumeration<String> e = session.getAttributeNames();
    String attributeName;
    Object attributeValue;
    
    // Display any stored attributes.
    while (e.hasMoreElements())
    {
        attributeName = e.nextElement();
        attributeValue = session.getAttribute(attributeName);
        %>
        <tr><td><%= attributeName %></td><td><%= attributeValue.toString() %></td></tr> 
        <%
    }
    %>
    </table>
    
    <p/>
    <!-- Allow the user to create a new session. -->
    <form action="newsession.jsp" method="post">
        <input type="submit" name="newSession" value="Create new session" />
    </form> 
    </body>
    
    </html>
    
    
  3. If you used Creating a Hello World Application for Azure in Eclipse as your starting point for this example (instead of Using the Azure Service Runtime Library in JSP), make the following changes to index.jsp.

    • Remove the following import statement:

      import="com.microsoft.windowsazure.serviceruntime.*"

    • Remove the following html statement:

      <tr><td>Azure deployment ID</td><td><%= RoleEnvironment.getCurrentRoleInstance().getId() %></td></tr>

    If you later decide you want to use the Azure Service Runtime library, follow the instructions at Using the Azure Service Runtime Library in JSP.

  4. Create a file named newsession.jsp.

    1. Within Eclipse’s Project Explorer view, expand MyHelloWorld.

    2. Right-click WebContent, click New, and then click JSP File.

    3. In the New JSP File dialog, name the file newsession.jsp and click Next.

    4. In the Select JSP Template dialog, for purposes of this tutorial select New JSP File (html) and click Finish.

    5. Use the following contents for newssession.jsp.

      <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
          pageEncoding="ISO-8859-1"%>
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <title>New session page</title>
      </head>
      <body>
      <%
          // Invalidate the current session.
          session.invalidate();
      
          // Return the user to the initial page.
          String sslOffloadingProtocol = request.getHeader("X-FORWARDED-PROTO");
          if (sslOffloadingProtocol == null ||  !sslOffloadingProtocol.equalsIgnoreCase("https")) 
          {
              response.sendRedirect("index.jsp");
          }
          else
          {    
              // Handle scenarios where user terminated SSL at load balancer. This is applicable for the 
              // SSL Offloading feature or any other load balancer which sets the X-FORWARDED-PROTO header.
              StringBuffer completeRequestURL = new StringBuffer(sslOffloadingProtocol);
              completeRequestURL.append("://");
              completeRequestURL.append(request.getServerName());
              completeRequestURL.append("/stickysessions/index.jsp");
      
              response.sendRedirect(completeRequestURL.toString());
          }
      %>
      </body>
      </html>
      
  5. In the Azure toolbar, click the Publish to Azure Cloud icon to deploy your application to Azure. For additional information on deploying to Azure emulator, see Creating a Hello World Application for Azure in Eclipse.

  6. After the deployment is ready, within your browser, launch the URL for your application. You can now view the session data.

To further experiment, you could try actions such as entering a value for the user name, refreshing the browser, browsing to another site and returning to your application, closing the browser and reopening it, clicking the Create new session button, etc.

For roles with session affinity enabled, the user’s HTTP requests will continue being redirected to the same Azure role instance indefinitely, or until the user restarts the browser, even if the session is invalidated by your application at some point.

If your application has some code that is intentionally session stateful, and some code that is session stateless, consider splitting your application into two parts (two separate WAR deployments), one that is session stateful and one that is session stateless, and deploy them in two different Azure roles. The session stateful role would reside in the role with session affinity enabled, and the session stateless role would reside in the role with session affinity disabled. Splitting your session stateful and stateless code into separate roles in this manner will help ensure an optimal level of scalability for your Azure deployment.

See Also

Weergeven:
© 2014 Microsoft