Questions
Question 1:
Which of the following two methods are used to track or store the session ID?
A. encodeURL()
B. sessionTrack()
C. sessionUpdate()
D. encodeRedirectURL()
Question 2:
How do you create a session?
A. createSession()
B. makeSession()
C. callSession()
D. getSession()
Question 3:
How do you retrieve a session object across multiple requests to the same or different servlets within the same WebApp?
A. retrieveSession()
B. findSession()
C. getSession()
D. callSession()
Question 4:
How do you store objects into a session object?
A. put(String, Object)
B. setAttribute(String, Object)
C. addObject(Object)
D. putObject(String, Object)
Question 5:
How do you know if a session is alive?
A. Look in the cookies.
B. getSession(false)
C. isSessionAlive()
D. Exception thrown if you try to create one when one already exists.
Question 6:
How do you destroy or expunge a session?
A. Session.isAlive = false;
B. Session.isNew(false)
C. invalidate()
D. removeSession()
Question 7:
How do you know when a particular object is added to a session?
A. getCreationTime()
B. getAttribute(Date)
C. Session.attributeDate(index)
D. attributeAdded(HttpSessionBindingEvent)
Question 8:
How do you know when a session is created?
A. sessionDidActivate(HttpSessionEvent)
B. You check with sessionIsAlive().
C. You only know when it is killed.
D. When the SESSIONID becomes null.
Question 9:
How do you know when a session is destroyed?
A. sessionBound(HttpSessionEvent)
B. sessionFinalize(HttpSessionEvent)
C. sessionWillPassivate(HttpSessionEvent)
D. valueBound(HttpSessionEvent)
Question 10:
Given that URL-rewriting must be used for session management, identify the query string attribute used when URL-rewriting.
A. sessionid
B. servletid
C. jsessionid
D. containerid
Question 11:
Where are cookies stored?
A. On the server.
B. In web.xml.
C. On the client.
D. In HTML.
Question 12:
Where are session IDs stored?
A. In cookies.
B. In HTML form fields.
C. In query strings.
D. Session IDs are not stored.
Question 13:
Which two technique can be used by a Web container to manage session IDs?
A. deleteAttribute(String)
B. attributeRemove(String)
C. removeAttribute(String)
D. setAttribute(null)
Question 14:
How do you get the date stamp of the session's creation?
A. getCreationTime()
B. sessionDate()
C. getSession(Date)
D. From the response object.
Answers:
Answer 1: A and D. You append the session ID in URLs by calling the response's encodeURL(URL) (or encodeRedirectURL()) method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged.
Answer 2: D. To get the current session in a servlet, you call the getSession() method of HttpServletRequest. You have one parameter to think about. If you don't provide a boolean, this method will create a session if one doesn't exist. The same behavior occurs when you provide a true boolean. However, the container will not create a new session if it doesn't already exist when you use a false argument.
Answer 3: C. This is the same question as #2, but stated differently. You call the getSession() method of HttpServletRequest to create a session.
Answer 4: B. You use the setAttribute(java.lang.String name, java.lang.Object value) method to add objects to a session. The other methods listed are incorrect.
Answer 5: B. This is somewhat difficult. You use getSession(false) method and test for a null result.
HttpSession session = request.getSession(false);
if (session = null) {
//do something about lacking a session
}
If you get a null then the session is alive. You can also check for the session ID with getId(), which returns the id of the session as a String representing the unique identifier assigned to this session. If the session is dead, it will return a null.
Answer 6: C. Only the invalidate() method can destroy a session. Notice that the session can't be referenced after this method has been called. A and D are incorrect and B isn't used properly.
Answer 7: D. The attributeAdded(HttpSessionBindingEvent se) method gets called as the notification that an attribute has been added to a session. The other options are incorrect.
Answer 8: A. The sessionDidActivate(HttpSessionEvent) method is called when the session has just been activated. The other options are incorrect.
Answer 9: C. The sessionWillPassivate(HttpSessionEvent) method is called as the notification that the session is about to be passivated. This is strange language so don't feel bad. They should have used another term such as alive or destroy. A and B are incorrect. D (valueBound(HttpSessionBindingEvent)) is the notification to the object that it is being bound to a session, but doesn't tell you about the session being destroyed.
Answer 10: C. The jsessionid is the parameter that is appended to URLs by the encodeURL() method when cookies are not available to maintain state. The other options are incorrect.
Answer 11: C. Cookies are stored on the client only.
Answer 12: A and C. Session IDs are stored in cookies on the client machine. If cookies are turned off, session IDs can be stored in query strings.
Answer 13: C. The removeAttribute(java.lang.String name) method removes an attribute. It deletes it from the session object. The other options are incorrect.
Answer 14: A. The getCreationTime() method returns a long containing the date stamp of creation. The other options are incorrect.
Previous Chapter: Quick Recap - Chapters 20 to 24
Next Chapter: Chapter 25 - Introduction to Servlet Exception Handling
Topics Covered in the Blog - Synopsis
Showing posts with label using httpsession. Show all posts
Showing posts with label using httpsession. Show all posts
Thursday, March 24, 2011
Quick Recap: Chapters 20 to 24
Let us now quickly review what we learnt about Sessions in the previous chapters.
Session Introduction:
• We need Sessions to maintain or persist user information during a sequence of events on a website by a user
• Session persistence is usually implemented using Cookies but it can be implemented using URL Rewriting, or hidden form fields
• The getAttribute and setAttribute methods of the HttpSession are used to set and retrieve values from the Session
• You can get a session by using the getSession method of the Request class.
HttpSession session = request.getSession(true);
Session Event Listeners:
• The common event listeners we will encounter are: HttpSessionActivationListener, HttpSessionAttributeListener and HttpSessionBindingListener
• Each has methods that can help us capture and process actions like when a session is created/destroyed, when a value is added/removed from the session etc.
Session Invalidation:
• Invalidating a session after a certain time period is a common occurrence
• Usually websites that display sensitive information have a time-out of around 10 mins
• The session would automatically expire after the time-out is reached (If the session is inactive)
Key Terms we learnt in these chapters:
• Session
• Session ID
• Session Timeout
• Session Attribute
• Session Events
• Listeners
Previous Chapter: Chapter 24 - Session Tracking through URL Rewriting
Next Chapter: Self Test - Chapters 20 to 24
Session Introduction:
• We need Sessions to maintain or persist user information during a sequence of events on a website by a user
• Session persistence is usually implemented using Cookies but it can be implemented using URL Rewriting, or hidden form fields
• The getAttribute and setAttribute methods of the HttpSession are used to set and retrieve values from the Session
• You can get a session by using the getSession method of the Request class.
HttpSession session = request.getSession(true);
Session Event Listeners:
• The common event listeners we will encounter are: HttpSessionActivationListener, HttpSessionAttributeListener and HttpSessionBindingListener
• Each has methods that can help us capture and process actions like when a session is created/destroyed, when a value is added/removed from the session etc.
Session Invalidation:
• Invalidating a session after a certain time period is a common occurrence
• Usually websites that display sensitive information have a time-out of around 10 mins
• The session would automatically expire after the time-out is reached (If the session is inactive)
Key Terms we learnt in these chapters:
• Session
• Session ID
• Session Timeout
• Session Attribute
• Session Events
• Listeners
Previous Chapter: Chapter 24 - Session Tracking through URL Rewriting
Next Chapter: Self Test - Chapters 20 to 24
Chapter 24: Session Tracking Through a URL Rather Than a Cookie
Session Tracking is very useful as you might have learnt in the past few chapters. There is also a feature wherein you can use URL Rewriting instead of using cookies (all our examples in the past chapters were using cookies so this one is new). In this chapter, you are going to learn just that.
So, lets get started!!!
URL Rewriting:
A Web container associates a session with a user by sending and receiving an identifier. This session ID is passed between the client and server. You could place this identifier in the HTML, but servlets are already designed to track this identifier if it is placed in a cookie or in the query string. The cookie is the easiest and happens automatically for you when you create a session. If the user turns off cookies then you can send the identifier back and forth in the query string by including it in every URL that is returned to the client. Though this is a bit of a painful task and is not necessarily used always, it is advised to learn it to cope with situations where cookie tracking is turned off frequently by your users and you still need to use sessions.
You append the session ID in URLs by calling the response's encodeURL(URL) or the encodeRedirectURL() method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged.
Example Code using URL Rewriting:
Now that we know how to append a session ID in the URL, lets look at an example that does that for us.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestURLRewriteServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
HttpSession session = request.getSession(true);
session.setAttribute("sessionNumber", new Integer(22));
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("< html >");
out.println("< body bgcolor=\"white\" > ");
out.println("< head >");
String title = "Session ID Is In URL";
out.println("< title >" + title + "< / title >");
out.println("< / head >");
out.println("< body >");
out.println("< center >");
out.println("< h1 >" + title + "< / h1 >");
out.println("< P >");
out.print(response.encodeURL("ExampleURL"));
out.println("< P >");
out.print(response.encodeURL("ExampleURL?name=" + "Car&value=Ferrari"));
out.println("< / center >");
out.println("< / body >");
out.println(" < / html >");
out.println("< / body >");
out.println("< / html >");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
When I first ran this code, my cookies were turned on. I saw this in my browser:
ExampleURL?name=Car&value=Ferrari
However, I then turned off cookies and received this on the next visit:
ExampleURL;jsessionid=62A027E37975F305B07555859780E423?name=Car&value=Ferrari
The JSESSIONID attributed displayed in the output above is used to track sessions when cookies are turned off. This JSESSIONID attribute would get appended to the query strings (URL) when we use the encodeURL() or encodeRedirectURL() methods.
You will probably see this attribute mentioned on the exam. So, just remember whatever you learnt in this chapter…
Previous Chapter: Chapter 23 - Invalidating Sessions
Next Chapter: Quick Recap - Chapters 20 to 24
So, lets get started!!!
URL Rewriting:
A Web container associates a session with a user by sending and receiving an identifier. This session ID is passed between the client and server. You could place this identifier in the HTML, but servlets are already designed to track this identifier if it is placed in a cookie or in the query string. The cookie is the easiest and happens automatically for you when you create a session. If the user turns off cookies then you can send the identifier back and forth in the query string by including it in every URL that is returned to the client. Though this is a bit of a painful task and is not necessarily used always, it is advised to learn it to cope with situations where cookie tracking is turned off frequently by your users and you still need to use sessions.
You append the session ID in URLs by calling the response's encodeURL(URL) or the encodeRedirectURL() method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged.
Exam Trivia:
The encodeURL method will use URL rewriting only if cookies are disabled else it will not modify the URL and the session will continue to use cookies. Remember that for the exam. Unless the question explicitly states that the cookies are turned off, don't assume it is and think that the URL will be modified by this method
Example Code using URL Rewriting:
Now that we know how to append a session ID in the URL, lets look at an example that does that for us.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestURLRewriteServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
HttpSession session = request.getSession(true);
session.setAttribute("sessionNumber", new Integer(22));
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("< html >");
out.println("< body bgcolor=\"white\" > ");
out.println("< head >");
String title = "Session ID Is In URL";
out.println("< title >" + title + "< / title >");
out.println("< / head >");
out.println("< body >");
out.println("< center >");
out.println("< h1 >" + title + "< / h1 >");
out.println("< P >");
out.print(response.encodeURL("ExampleURL"));
out.println("< P >");
out.print(response.encodeURL("ExampleURL?name=" + "Car&value=Ferrari"));
out.println("< / center >");
out.println("< / body >");
out.println(" < / html >");
out.println("< / body >");
out.println("< / html >");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
When I first ran this code, my cookies were turned on. I saw this in my browser:
ExampleURL?name=Car&value=Ferrari
However, I then turned off cookies and received this on the next visit:
ExampleURL;jsessionid=62A027E37975F305B07555859780E423?name=Car&value=Ferrari
The JSESSIONID attributed displayed in the output above is used to track sessions when cookies are turned off. This JSESSIONID attribute would get appended to the query strings (URL) when we use the encodeURL() or encodeRedirectURL() methods.
You will probably see this attribute mentioned on the exam. So, just remember whatever you learnt in this chapter…
Previous Chapter: Chapter 23 - Invalidating Sessions
Next Chapter: Quick Recap - Chapters 20 to 24
Labels:
session management,
session tracking through url rewriting,
url rewriting,
using httpsession,
using http session
| Reactions: |
Chapter 22: Session Event Listeners
In one of the previous chapters, Interfaces & Listeners in the web context we saw about interfaces and event listeners. In this chapter we are going to take a look at the Event Listener that is linked to the HttpSession.
So, lets get started!!!
Session Event Listeners
The listeners that can be used to capture session event actions are:
1. HttpSessionActivationListener
2. HttpSessionAttributeListener
3. HttpSessionBindingListener
Lets look at them one by one in detail.
HttpSessionActivationListener
The purpose of this listener is to look for events such as when a session will be activated or passivated. The listener in turn extends the java.util.EventListener. The methods in it are:
• sessionDidActivate(HttpSessionEvent se) - This is the notification that the session has just been activated.
• sessionWillPassivate(HttpSessionEvent se)- This is the notification that the session is about to be passivated.
HttpSessionAttributeListener:
The HttpSessionAttributeListener interface enables an object to monitor changes to the attribute lists of sessions within a given Web application. The HttpSessionAttributeListener in turn extends java.util.EventListener. The methods in it are
• attributeAdded(HttpSessionBindingEvent se)- This is the notification that an attribute has been added to a session.
• attributeRemoved(HttpSessionBindingEvent se)- This is the notification that an attribute has been removed from a session.
• attributeReplaced(HttpSessionBindingEvent se)- This is the notification that an attribute has been replaced in a session.
We can use these methods when monitoring the attributes of a particular session.
HttpSessionBindingListener
The last listener we are going to look at is the HttpSessionBindingListener. The HttpSessionBindingListener is used to track the events surrounding the binding and unbinding of a session. This event listener causes an object to be notified when it is bound to or unbound from a session. The interface is HttpSessionBindingListener in turn extends java.util.EventListener.
This will be triggered when a servlet is coded to explicitly unbind an attribute from a session, due to a session being invalidated or a session timeout. The methods in it are
• valueBound(HttpSessionBindingEvent event)- This is the notification to the object that it is being bound to a session and identifies the session.
• valueUnbound(HttpSessionBindingEvent event)- This is the notification to the object that it is being unbound from a session and identifies the session.
You might want to know when an object is added or removed from a session to handle, say, a shopping cart checkout. And this listener is just designed to help you with that.
Code Examples to Understand the Listener Usage:
Now that we know what these listeners are, lets look at a sample code that is going to handle these events. As you already know, if a class has to handle certain events, someone has to generate them, right? So here, the first code example is going to generate our events and the second guy is going to handle them.
Code 1:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestSessionEventsServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
// Activities that trigger listener events
HttpSession session = request.getSession(true);
session.setAttribute("attributeName", "firstValue");
session.setAttribute("attributeName", "firstValue");
session.removeAttribute("attributeName");
session.invalidate();
}
}
The above code does nothing but, create a session and then set/remove attributes and then invalidate the session.
Code 2:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionActivityListener
implements HttpSessionListener,
HttpSessionAttributeListener
{
public void attributeAdded(HttpSessionBindingEvent event)
{
//do something when attribute is added
}
public void attributeRemoved(HttpSessionBindingEvent
event) {
{
//do something when attribute is removed
}
public void attributeReplaced(HttpSessionBindingEvent
event) {
{
//do something when an attribute is replaced
}
public void sessionCreated(HttpSessionEvent event) {
{
//do something when session is created
}
public void sessionDestroyed(HttpSessionEvent event) {
{
//do something when session is destroyed
}
}
The first servlet created the events we wished to capture and this above class will handle them. Actually I havent put any event handling code in any of the methods. They are all blank. But, in realtime, you would want to have code inside each of the event handling methods that would let you do something. For ex: when an attribute from session is removed which you feel is very important, you might log an error message for debugging purposes.
The even listeners are pretty useful when used appropriately. Well, that's about this chapter. Lets move on to the next one!!!
Previous Chapter: Chapter 21 - Storing & Retrieving Session Objects
Next Chapter: Chapter 23 - Invalidating Sessions
So, lets get started!!!
Session Event Listeners
The listeners that can be used to capture session event actions are:
1. HttpSessionActivationListener
2. HttpSessionAttributeListener
3. HttpSessionBindingListener
Lets look at them one by one in detail.
HttpSessionActivationListener
The purpose of this listener is to look for events such as when a session will be activated or passivated. The listener in turn extends the java.util.EventListener. The methods in it are:
• sessionDidActivate(HttpSessionEvent se) - This is the notification that the session has just been activated.
• sessionWillPassivate(HttpSessionEvent se)- This is the notification that the session is about to be passivated.
Exam Trivia:
Session Moving Between JVMs The specification dictates that a container that migrates a session between VMs or persists sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener.
HttpSessionAttributeListener:
The HttpSessionAttributeListener interface enables an object to monitor changes to the attribute lists of sessions within a given Web application. The HttpSessionAttributeListener in turn extends java.util.EventListener. The methods in it are
• attributeAdded(HttpSessionBindingEvent se)- This is the notification that an attribute has been added to a session.
• attributeRemoved(HttpSessionBindingEvent se)- This is the notification that an attribute has been removed from a session.
• attributeReplaced(HttpSessionBindingEvent se)- This is the notification that an attribute has been replaced in a session.
We can use these methods when monitoring the attributes of a particular session.
HttpSessionBindingListener
The last listener we are going to look at is the HttpSessionBindingListener. The HttpSessionBindingListener is used to track the events surrounding the binding and unbinding of a session. This event listener causes an object to be notified when it is bound to or unbound from a session. The interface is HttpSessionBindingListener in turn extends java.util.EventListener.
This will be triggered when a servlet is coded to explicitly unbind an attribute from a session, due to a session being invalidated or a session timeout. The methods in it are
• valueBound(HttpSessionBindingEvent event)- This is the notification to the object that it is being bound to a session and identifies the session.
• valueUnbound(HttpSessionBindingEvent event)- This is the notification to the object that it is being unbound from a session and identifies the session.
You might want to know when an object is added or removed from a session to handle, say, a shopping cart checkout. And this listener is just designed to help you with that.
Code Examples to Understand the Listener Usage:
Now that we know what these listeners are, lets look at a sample code that is going to handle these events. As you already know, if a class has to handle certain events, someone has to generate them, right? So here, the first code example is going to generate our events and the second guy is going to handle them.
Code 1:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestSessionEventsServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
// Activities that trigger listener events
HttpSession session = request.getSession(true);
session.setAttribute("attributeName", "firstValue");
session.setAttribute("attributeName", "firstValue");
session.removeAttribute("attributeName");
session.invalidate();
}
}
The above code does nothing but, create a session and then set/remove attributes and then invalidate the session.
Code 2:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionActivityListener
implements HttpSessionListener,
HttpSessionAttributeListener
{
public void attributeAdded(HttpSessionBindingEvent event)
{
//do something when attribute is added
}
public void attributeRemoved(HttpSessionBindingEvent
event) {
{
//do something when attribute is removed
}
public void attributeReplaced(HttpSessionBindingEvent
event) {
{
//do something when an attribute is replaced
}
public void sessionCreated(HttpSessionEvent event) {
{
//do something when session is created
}
public void sessionDestroyed(HttpSessionEvent event) {
{
//do something when session is destroyed
}
}
The first servlet created the events we wished to capture and this above class will handle them. Actually I havent put any event handling code in any of the methods. They are all blank. But, in realtime, you would want to have code inside each of the event handling methods that would let you do something. For ex: when an attribute from session is removed which you feel is very important, you might log an error message for debugging purposes.
The even listeners are pretty useful when used appropriately. Well, that's about this chapter. Lets move on to the next one!!!
Previous Chapter: Chapter 21 - Storing & Retrieving Session Objects
Next Chapter: Chapter 23 - Invalidating Sessions
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
• 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
Chapter 20: Introduction to Session Management
In one of the previous chapters, we saw what a Session is, what its purpose is and how it is used. In fact, one of our readers even posted a comment stating that the description was very simple and did not cover the full length and breadth of Session Management. Well my friends, that was just the introduction and in the next few chapters, I will probably bore you to death with the details of Session Management.
So, lets get started!!!
Why do we need a Session?
When one page needs to share information with another, the scope of the data broadens beyond processing a single request. This is because, when a response gets committed, all the data that was held in the request that generated that response is destroyed. So, if you want that data in another page, you will be looking at a blank request object with no data in it. When such a need arises, you must send the data from one page to the server and from the server to the next requested page, whether it be the same page or another page altogether. There are several ways to share state information between requests. However, the primary or the easiest way is to use sessions.
How Do Sessions Work?
The container generates a session ID. When you create a session, the server saves the session ID on the client's machine as a cookie. If cookies are turned off then it appends the ID in the URL. On the server, whatever you add to the session object gets placed in server memory—very resource intensive. The server associates that object in memory with the session ID. When the user sends a new request, the session ID is sent too. The server can then match the objects in its memory with that session ID. This is how we maintain client state.
What are Cookies?
In the previous paragraph about how sessions work, we used the term cookies. A cookie is a tiny text file that is maintained by the browser to do things like store unique IDs. They are normally small (~1KB) and saved in the OS cookie directory or folder. There are numerous browsers that handle cookies in various ways. You can go to c:\documents and settings\your login and search for cookies folder and try seeing what kind of files are placed in it by your browser.
In the old days they were used for all sorts of things, including storing personal data like passwords. The popularity of doing so has waned. Today, especially with servlets, it is better to store most information in sessions than cookies. But it is still important to understand cookies before discussing sessions.
As you can see in the image above, there are many cookies on my machine. Those shown are only a few that have been created on my Windows 7 Sony VAIO Laptop. Originally, folks put actual data like names and addresses in cookies because there wasn't anywhere else to save these valuable pieces of data. Today, the information in a cookie is primarily an identifier of sorts.
Vendors implement session IDs differently. Let us dig into Tomcat to see how it handles sessions IDs. The following snippet, edited for clarity, is how a session ID is generated:
/**
* Generate and return a new session identifier.
*/
protected synchronized String generateSessionId() {
// Generate a byte array containing a session ID
Random random = getRandom();
//int SESSION_ID_SIZE= 16;
byte bytes[] = new byte[SESSION_ID_SIZE];
getRandom().nextBytes(bytes);
bytes = getDigest().digest(bytes);
// The remainder of routine converts
// the byte array to a String of hexadecimal digits.
// This returns something like:
// 62A027E37975F305B07555859780E423
// see Listing 6.6
return (result.toString());
}
Web sites keep track of your activities (such as a shopping cart) with a standard session ID, which assigns each visitor a unique, random number. The servlet specification doesn't address how browsers are supposed to store the session ID. Some browsers store it in memory (but send/receive in request/response header as a cookie), while most store it in a cookie file. For example, when I recently visited Amazon, its servers sent my browser a new session ID which was stored in a cookie file called administrator@amazon[1].txt. In this cookie was the following session ID, among other things like date timestamp:
session-id
002-0150365-1700034
amazon.com/
Cookies have been the target of privacy advocates since the beginning of the internet. Cookies are now used for many things, including the suspicious tracking of your activities as you surf the Internet. Some people call the use of cookies to track activity Web bugs. Some companies are paid to monitor you as much as possible to create a profile. And since that is not in the scope of the exam, we arent going to bother much about them.
Most of the cookies on our machines are not used for anything sinister. You can thwart all this by turning off cookies and images. You can do this in IE by going to View -> Internet Options -> Advanced -> selecting Prompt before accepting Cookies, and clicking OK.
In fact, cookies are used for good far more often than bad. For example, when I go to Amazon.com, I get a familiar view because they remember what I did on my last visit. Amazon can do that because it placed a file on my machine called administrator@amazon[1].txt (the browser actually does this) containing this:
session-id
432-5447995-1125358
amazon.com/
0
4322765824
89901156
321345632
79444758
*
session-id-time
8731881600
amazon.com/
0
9985765824
44191156
185745632
09789758
*
ubid-main
0883061-5210078
amazon.com/
0
6796341376
69581269
777869456
29476039
*
x-main
3xBkjhwcqmPgTz7hgffU8UoFvMDSWX
amazon.com/
0
7896341376
1969969
939053232
9770408
*
I like the idea of Amazon tracking my activities. They are open about it and I can stop them any time I wish. But, it becomes problematic when companies do it stealthily or use it to trouble you. In this case Amazon is a genuine website and I seriously have 0 problems with them saving a cookie in my laptop. Afterall, it is going to help me the next time I visit their site so I practically have no issues with it.
The following are the four most frequently used methods for persisting data between views:
• Field-field: Value of a field in a request is copied to value of same field in response.
• Hidden form field: Data is placed in the HTML in a hidden form field.
• Query string: Some data is appended to the query string or a hyperlink in the HTML.
• Cookie: A small text file created by the browser that stores data sent by the server.
These four approaches are the ones most often used; however, session technology does more for you. The following section describes how Java uses sessions to help you maintain client state.
Using Session Objects
The HttpSession object is very powerful and has many features. Before we dig deep into the world of Sessions, let us take a look at the important methods they have so that we can use them effectively.
• getAttribute(java.lang.String name) - Returns an Object associated with that name that was stored in the session object.
• getAttributeNames() - Returns an Enumeration object that lists the names of the objects stored in the session object.
• getCreationTime() - Returns a long containing the date stamp of creation.
• getId() - Returns the id of the session as a String representing the unique identifier assigned to this session.
• getLastAccessedTime() - Returns a long containing the date stamp of the last time the session was accessed.
• getMaxInactiveInterval() - Returns an integer representing the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
• invalidate() - This destroys a session. It can't be referenced after this method has been called.
• isNew() - This tells you whether the client knows about the session. In other words, the has session been created by the server, but the client hasn't acknowledged receiving the session ID yet.
• removeAttribute(java.lang.String name) - This removes an attribute. It deletes it from the session object.
• setAttribute(java.lang.String name, java.lang.Object value) - You use this method to add objects to a session.
• setMaxInactiveInterval(int interval) - Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.
• getValue(java.lang.String name) - Returns an Object associated with that name that was stored in the session object. As of Version 2.2, this method is replaced by getAttribute(). The getAttribute() method will be on the exam, not this one, but it is here for completeness.
• getValueNames() - Returns a String array with a list of names associated with the objects added to a given session. As of Version 2.2, this method is replaced by getAttributeNames(). The getAttributeNames() method will be on the exam, not this one, but it is here for completeness.
• putValue(java.lang.String name, java.lang.Object value) - You use this method to add objects to a session. This has been deprecated. As of Version 2.2, this method is replaced by setAttribute(java.lang.String, java.lang.Object). The setAttribute() method will be on the exam, not this one, but it is here for completeness.
• removeValue(java.lang.String name) - This removes a value, but retains an attribute name in the session. The name is valid but the object is null. This has been deprecated. As of Version 2.2, this method is replaced by removeAttribute(). The removeAttribute() method will be on the exam, not this one, but it is here for completeness.
The preceding methods are the ones that will appear on the exam. For the moment, just relax and don't worry about how and when to use these methods. That is exactly what I am going to explain in the subsequent chapters.
Previous Chapter: Self Test - Chapters 6 to 19
Next Chapter: Chapter 21 - Storing & Retrieving Session Objects
So, lets get started!!!
Why do we need a Session?
When one page needs to share information with another, the scope of the data broadens beyond processing a single request. This is because, when a response gets committed, all the data that was held in the request that generated that response is destroyed. So, if you want that data in another page, you will be looking at a blank request object with no data in it. When such a need arises, you must send the data from one page to the server and from the server to the next requested page, whether it be the same page or another page altogether. There are several ways to share state information between requests. However, the primary or the easiest way is to use sessions.
How Do Sessions Work?
The container generates a session ID. When you create a session, the server saves the session ID on the client's machine as a cookie. If cookies are turned off then it appends the ID in the URL. On the server, whatever you add to the session object gets placed in server memory—very resource intensive. The server associates that object in memory with the session ID. When the user sends a new request, the session ID is sent too. The server can then match the objects in its memory with that session ID. This is how we maintain client state.
What are Cookies?
In the previous paragraph about how sessions work, we used the term cookies. A cookie is a tiny text file that is maintained by the browser to do things like store unique IDs. They are normally small (~1KB) and saved in the OS cookie directory or folder. There are numerous browsers that handle cookies in various ways. You can go to c:\documents and settings\your login and search for cookies folder and try seeing what kind of files are placed in it by your browser.
In the old days they were used for all sorts of things, including storing personal data like passwords. The popularity of doing so has waned. Today, especially with servlets, it is better to store most information in sessions than cookies. But it is still important to understand cookies before discussing sessions.
As you can see in the image above, there are many cookies on my machine. Those shown are only a few that have been created on my Windows 7 Sony VAIO Laptop. Originally, folks put actual data like names and addresses in cookies because there wasn't anywhere else to save these valuable pieces of data. Today, the information in a cookie is primarily an identifier of sorts.
Vendors implement session IDs differently. Let us dig into Tomcat to see how it handles sessions IDs. The following snippet, edited for clarity, is how a session ID is generated:
/**
* Generate and return a new session identifier.
*/
protected synchronized String generateSessionId() {
// Generate a byte array containing a session ID
Random random = getRandom();
//int SESSION_ID_SIZE= 16;
byte bytes[] = new byte[SESSION_ID_SIZE];
getRandom().nextBytes(bytes);
bytes = getDigest().digest(bytes);
// The remainder of routine converts
// the byte array to a String of hexadecimal digits.
// This returns something like:
// 62A027E37975F305B07555859780E423
// see Listing 6.6
return (result.toString());
}
Web sites keep track of your activities (such as a shopping cart) with a standard session ID, which assigns each visitor a unique, random number. The servlet specification doesn't address how browsers are supposed to store the session ID. Some browsers store it in memory (but send/receive in request/response header as a cookie), while most store it in a cookie file. For example, when I recently visited Amazon, its servers sent my browser a new session ID which was stored in a cookie file called administrator@amazon[1].txt. In this cookie was the following session ID, among other things like date timestamp:
session-id
002-0150365-1700034
amazon.com/
Cookies have been the target of privacy advocates since the beginning of the internet. Cookies are now used for many things, including the suspicious tracking of your activities as you surf the Internet. Some people call the use of cookies to track activity Web bugs. Some companies are paid to monitor you as much as possible to create a profile. And since that is not in the scope of the exam, we arent going to bother much about them.
Most of the cookies on our machines are not used for anything sinister. You can thwart all this by turning off cookies and images. You can do this in IE by going to View -> Internet Options -> Advanced -> selecting Prompt before accepting Cookies, and clicking OK.
In fact, cookies are used for good far more often than bad. For example, when I go to Amazon.com, I get a familiar view because they remember what I did on my last visit. Amazon can do that because it placed a file on my machine called administrator@amazon[1].txt (the browser actually does this) containing this:
session-id
432-5447995-1125358
amazon.com/
0
4322765824
89901156
321345632
79444758
*
session-id-time
8731881600
amazon.com/
0
9985765824
44191156
185745632
09789758
*
ubid-main
0883061-5210078
amazon.com/
0
6796341376
69581269
777869456
29476039
*
x-main
3xBkjhwcqmPgTz7hgffU8UoFvMDSWX
amazon.com/
0
7896341376
1969969
939053232
9770408
*
I like the idea of Amazon tracking my activities. They are open about it and I can stop them any time I wish. But, it becomes problematic when companies do it stealthily or use it to trouble you. In this case Amazon is a genuine website and I seriously have 0 problems with them saving a cookie in my laptop. Afterall, it is going to help me the next time I visit their site so I practically have no issues with it.
The following are the four most frequently used methods for persisting data between views:
• Field-field: Value of a field in a request is copied to value of same field in response.
• Hidden form field: Data is placed in the HTML in a hidden form field.
• Query string: Some data is appended to the query string or a hyperlink in the HTML.
• Cookie: A small text file created by the browser that stores data sent by the server.
These four approaches are the ones most often used; however, session technology does more for you. The following section describes how Java uses sessions to help you maintain client state.
Using Session Objects
The HttpSession object is very powerful and has many features. Before we dig deep into the world of Sessions, let us take a look at the important methods they have so that we can use them effectively.
• getAttribute(java.lang.String name) - Returns an Object associated with that name that was stored in the session object.
• getAttributeNames() - Returns an Enumeration object that lists the names of the objects stored in the session object.
• getCreationTime() - Returns a long containing the date stamp of creation.
• getId() - Returns the id of the session as a String representing the unique identifier assigned to this session.
• getLastAccessedTime() - Returns a long containing the date stamp of the last time the session was accessed.
• getMaxInactiveInterval() - Returns an integer representing the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
• invalidate() - This destroys a session. It can't be referenced after this method has been called.
• isNew() - This tells you whether the client knows about the session. In other words, the has session been created by the server, but the client hasn't acknowledged receiving the session ID yet.
• removeAttribute(java.lang.String name) - This removes an attribute. It deletes it from the session object.
• setAttribute(java.lang.String name, java.lang.Object value) - You use this method to add objects to a session.
• setMaxInactiveInterval(int interval) - Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.
• getValue(java.lang.String name) - Returns an Object associated with that name that was stored in the session object. As of Version 2.2, this method is replaced by getAttribute(). The getAttribute() method will be on the exam, not this one, but it is here for completeness.
• getValueNames() - Returns a String array with a list of names associated with the objects added to a given session. As of Version 2.2, this method is replaced by getAttributeNames(). The getAttributeNames() method will be on the exam, not this one, but it is here for completeness.
• putValue(java.lang.String name, java.lang.Object value) - You use this method to add objects to a session. This has been deprecated. As of Version 2.2, this method is replaced by setAttribute(java.lang.String, java.lang.Object). The setAttribute() method will be on the exam, not this one, but it is here for completeness.
• removeValue(java.lang.String name) - This removes a value, but retains an attribute name in the session. The name is valid but the object is null. This has been deprecated. As of Version 2.2, this method is replaced by removeAttribute(). The removeAttribute() method will be on the exam, not this one, but it is here for completeness.
The preceding methods are the ones that will appear on the exam. For the moment, just relax and don't worry about how and when to use these methods. That is exactly what I am going to explain in the subsequent chapters.
Previous Chapter: Self Test - Chapters 6 to 19
Next Chapter: Chapter 21 - Storing & Retrieving Session Objects
Labels:
getattribute,
httpsession,
session management,
setattribute,
using httpsession,
using http session,
using session persistense
| Reactions: |
Subscribe to:
Posts (Atom)
© 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.
