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
Topics Covered in the Blog - Synopsis
Showing posts with label httpsession. Show all posts
Showing posts with label httpsession. Show all posts
Thursday, March 24, 2011
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 http session,
using httpsession,
using session persistense
| Reactions: |
Tuesday, March 15, 2011
Chapter 15: The Session
In the previous chapter we took a look at how the HTTP Request can help us move data from the JSP to the Servlet and vice versa and the methods that are available in the Request object that would help us handle the data it carries.
In this chapter, we are going to look at the Session which is a super-set of the request and can contain data that needs to be retained across different pages.
So, lets get started!!!
The HTTP Session:
The Session is the place where data can be stored and retrieved across multiple hits from the same browser for a certain period of time. For example, lets say you want to login to your online banking website and the browser asks you to enter your login id and password after every click? It would be irritating isn’t it?
Exactly yes.
Thankfully we have the Http session.
When we logon to our bank website and enter our login id and password, the application saves our credentials in the session and uses it when we navigate between screens on the banks website.
Note: For reasons of safety and security, usually sessions in sensitive websites like a bank website or a stock brokers site, the session expires automatically after 5 minutes of inactivity or if the user presses the back or refresh buttons.
Getting the Session Object:
The session object can be obtained from the Request using the below line of code:
HttpSession session = request.getSession();
Setting & Getting Attributes from the Session:
We can set and retrieve attributes from the session using the setAttribute & getAttribute methods.
Ex:
session.setAttribute(“Key”, value); //Setting the value
Object obj = session.getAttribute(“Key”); //Getting the value
Here, “Key” is the identifier that will be used to locate the value saved in the session. The “Key” can be used to retrieve the value using the getAttribute() method.
Other Session Methods:
Some other methods available in the Session are:
1. getId() – Every session has a unique id and this method is used to get that id
2. getCreationTime() – To find out when the session was created
3. getLastAccessedTime() – To find out when the session was accessed last
4. getAttributeNames() – To retrieve all the values stored in the session as an Enumeration
To wrap up, sessions are what you can use to track a single user over a short time period (say 5 or 10 mins usually). You get the session object (HttpSession) from the request object. To track multiple users in your application, you can use the Context. Don't worry, that's our next stop…
For now, this chapter is over!!!
Previous Chapter: Chapter 14 - The Request Object
Next Chapter: Chapter 16 - Servlet Context
In this chapter, we are going to look at the Session which is a super-set of the request and can contain data that needs to be retained across different pages.
So, lets get started!!!
The HTTP Session:
The Session is the place where data can be stored and retrieved across multiple hits from the same browser for a certain period of time. For example, lets say you want to login to your online banking website and the browser asks you to enter your login id and password after every click? It would be irritating isn’t it?
Exactly yes.
Thankfully we have the Http session.
When we logon to our bank website and enter our login id and password, the application saves our credentials in the session and uses it when we navigate between screens on the banks website.
Note: For reasons of safety and security, usually sessions in sensitive websites like a bank website or a stock brokers site, the session expires automatically after 5 minutes of inactivity or if the user presses the back or refresh buttons.
Getting the Session Object:
The session object can be obtained from the Request using the below line of code:
HttpSession session = request.getSession();
Setting & Getting Attributes from the Session:
We can set and retrieve attributes from the session using the setAttribute & getAttribute methods.
Ex:
session.setAttribute(“Key”, value); //Setting the value
Object obj = session.getAttribute(“Key”); //Getting the value
Here, “Key” is the identifier that will be used to locate the value saved in the session. The “Key” can be used to retrieve the value using the getAttribute() method.
Other Session Methods:
Some other methods available in the Session are:
1. getId() – Every session has a unique id and this method is used to get that id
2. getCreationTime() – To find out when the session was created
3. getLastAccessedTime() – To find out when the session was accessed last
4. getAttributeNames() – To retrieve all the values stored in the session as an Enumeration
To wrap up, sessions are what you can use to track a single user over a short time period (say 5 or 10 mins usually). You get the session object (HttpSession) from the request object. To track multiple users in your application, you can use the Context. Don't worry, that's our next stop…
For now, this chapter is over!!!
Previous Chapter: Chapter 14 - The Request Object
Next Chapter: Chapter 16 - Servlet Context
Labels:
getting scwcd certified,
http session,
httpsession,
j2ee session,
jsp and servlets,
scwcd,
scwcd certification,
session scope,
the session
| 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.
