Thursday, March 24, 2011

Chapter 21: Storing and Retrieving Session Objects

By now, you are already familiar with what a Session is and what it is used for. In this chapter we are going to see how to:

• Retrieve a session object across multiple requests to the same or different servlets within the same WebApp.
• Store objects into a session object.
• Retrieve objects from a session object.

So, without any further delays, lets get started!!!

Storing & Retrieving Session Objects:

Using the session is easier said that done. Explaining it as paragraphs would be an arduous and not to mention a boring task. So lets take a look at some sample code that will tell us how to achieve session persistence in our code.

Let me remind you that, please pay attention to the code. You can easily overlook/miss many of the nuances of the session usage and that could cost you dearly in the exam.

Example Code 1:

In this below example, we are going to see how to obtain or rather create a new session and use it.
/**
* Return the session associated with this Request
* If it doesn't, then creating one if necessary
*/
public HttpSession getSession(boolean create)
{
if( System.getSecurityManager() != null )
{
PrivilegedGetSession dp = new PrivilegedGetSession(create);
return (HttpSession)AccessController.doPrivileged(dp);
}
return doGetSession(create);
}

private HttpSession doGetSession(boolean create)
{
// Check if Context exists if not, a session cannot exist
if (context == null)
return (null);

// Return the current session if it exists and is valid
if ((session != null) && !session.isValid())
session = null;
if (session != null)
return (session.getSession());

// Return the requested session if it exists and is valid
Manager manager = null;
if (context != null)
manager = context.getManager();
if (manager == null)
return (null);
if (requestedSessionId != null)
{
try
{
session = manager.findSession(requestedSessionId);
} catch (IOException e) {
session = null;
}
if ((session != null) && !session.isValid())
session = null;
if (session != null) {
return (session.getSession());
}
}

// Create a new session if requested & response is not committed
if (!create)
return (null);
if ((context != null) && (response != null) && context.getCookies() &&
response.getResponse().isCommitted())
{
throw new IllegalStateException(sm.getString("httpRequestBase.createCommitted"));
}

session = manager.createSession();
if (session != null)
return (session.getSession());
else
return (null);
}

/**
* Return true if the session identifier
* included in this request came from a cookie.
*/
public boolean isRequestedSessionIdFromCookie()
{
if (requestedSessionId != null)
return (requestedSessionCookie);
else
return (false);
}

/**
* Return true if the session identifier
* included in this request came from the request URI.
*/
public boolean isRequestedSessionIdFromURL()
{
if (requestedSessionId != null)
return (requestedSessionURL);
else
return (false);
}
Actually, above is how your Tomcat server handles your request to create a session object. Now that we know this let us take a look at another example that is going to actually use this session to do something worthwhile.

Example Code 2:

This is quite a long piece of code. In this example, we will be accessing the session, setting some attributes in it as well as getting some. Also, we are accessing the cookies in the request and using them all to print out some stuff in the web browser.

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;


public class TestSessionsServlet extends HttpServlet
{
// The regular doPost method
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request,response);
}
// The regular doGet method
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{

// Get the session associated with this request
// A new session would get created if it doesn't exist
HttpSession session = request.getSession(true);

// Set some value into the session as attribute
session.setAttribute("sessionId", new Integer(22));

// Try to read some data from the Session
String cookieName = request.getParameter("cookiename");
String cookieValue = request.getParameter("cookievalue");

// It is always a good idea to check for null if a value is
// picked up from the session. If the value you are looking
// for doesn't exist, you will end up with
// a NullPointerException
if (cookieName != null && cookieValue != null)
{
Cookie cookie = new Cookie(cookieName, cookieValue);
response.addCookie(cookie);
}

// Write some stuff on the browser
PrintWriter out = response.getWriter();
response.setContentType("text/html");

out.println("< html >");
out.println(" < head >");
out.println(" < title >Session Detail Report< / title >");
out.println(" < / head >");
out.println(" < body >");
out.println(" < center >");
out.println(" < h2 >Session Detail Report< / h2 >");

String url=request.getScheme()+ "://"+request.getServerName()+
":"+request.getServerPort()+ request.getRequestURI();

out.println(" < table width=\"100%\" border=\"1\" + " cellspacing=\"0\" cellpadding=\"1\" >");
out.println(" < tr >");
out.println(" < td colspan=2 >"+url+"< / td >");
out.println(" < / tr >");
printVoid(out);
out.println(" < tr >");
out.println(" < td colspan=2 >");
out.print("< form action=\""); out.println(url + "\" method=POST >");
out.println("Attribute Name:< input type=text "+"length=20 name=cookiename > < br >");
out.println("Attribute Value:< input type=text"+"length=20 name=cookievalue > < br >");
out.println("< input type=submit >< / form >");
out.println(" < / td >");
out.println(" < / tr >");

printHeader(out,"Cookies in this request:");

// Get all cookies from the Request
Cookie[] cookies = request.getCookies();

if (cookies!=null)

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

Cookie cookie = cookies[i];

printValue(out,cookie.getName(), cookie.getValue());

}

printVoid(out);


printHeader(out,"Session Details:");

SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss.SSS z");

printValue(out,"Requested Session Id:", request.getRequestedSessionId());

printValue(out,"Current Session Id:", session.getId());

printValue(out,"Session Created Time:",

format.format(new Date(session.getCreationTime())));

printValue(out,"Session Last Accessed Time:",

format.format(new Date(session.getLastAccessedTime())));

printValue(out,"Session Max Inactive " + "Interval Seconds:", Integer.toString(session.getMaxInactiveInterval()));

printVoid(out);


printHeader(out,"Session values:");

Enumeration enum = session.getAttributeNames();

while (enum.hasMoreElements())

{

String key = (String) enum.nextElement();

Object val = session.getAttribute(key);

printValue(out,key,val.toString());

}

printVoid(out);


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

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

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

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

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

out.flush();

}


// Utility methods
public void printHeader(PrintWriter out, String header)
{
out.println(" < tr >");
out.println(" < td bgcolor=\"#999999\" "); out.println(" "colspan=\"2\" >");
out.println(" < b >"+header+"< / b >");
out.println(" < / td >");
out.println(" < / tr >");
}

public void printValue(PrintWriter out, String key, String val)
{
if (val!=null) {
if (val.length()>255)
val=val.substring(0,128)+" (... more)";
}
out.println(" < tr >");
out.println(" < td bgcolor=\"#cccccc\" >"+ key + "< / td >");
out.println(" < td bgcolor=\"#ffffff\" >"+ val + "< / td >");
out.println(" < / tr >");
}

public void printVoid(PrintWriter out)
{
out.println("< tr > < td bgcolor=\"#ffffff\" "+"colspan=\"2\" > < / td >< / tr >");
}
}

You can do a lot more with the details above but to keep it simple, we aren’t attempting anything complicated since this is one of our first examples of using Sessions.

The output of the above servlet would vary based on time and the list of attributes that are already existent in the Session.

It would be a good exercise to deploy this servlet in your local tomcat server instance and observe the output. So, I am not going to paste the resultant browser output here. Sorry about that :) but you will definitely thank me for not doing it because, this exercise will help you nicely…

Previous Chapter: Chapter 20 - Introduction to Session Management

Next Chapter: Chapter 21 - Session Event Listeners

No comments:

Post a Comment

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers