1 / 45

JAVA Sessions

JAVA Sessions. 1. What is Session Tracking?

meli
Download Presentation

JAVA Sessions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JAVA Sessions 1. What is Session Tracking? There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on-line shopping, it is a real annoyance that the Web server can't easily remember previous transactions. This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what's already in your cart? Even if servers did retain contextual information, you'd still have problems with e-commerce. When you move from the page where you specify what you want to buy (hosted on the regular Web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server remember what you were buying?

  2. JAVA Sessions There are three typical solutions to this problem. Cookies. You can use HTTP cookies to store information about a shopping session, and each subsequent connection can look up the current session and then extract information about that session from some location on the server machine. This is an excellent alternative, and is the most widely used approach. However, even though servlets have a high-level and easy-to-use interface to cookies, there are still a number of relatively tedious details that need to be handled: Extracting the cookie that stores the session identifier from the other cookies (there may be many, after all), Setting an appropriate expiration time for the cookie (sessions interrupted by 24 hours probably should be reset), and Associating information on the server with the session identifier (there may be far too much information to actually store it in the cookie, plus sensitive data like credit card numbers should never go in cookies).

  3. JAVA Sessions 2.URL Rewriting. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. This is also an excellent solution, and even has the advantage that it works with browsers that don't support cookies or where the user has disabled cookies. However, it has most of the same problems as cookies, namely that the server-side program has a lot of straightforward but tedious processing to do. In addition, you have to be very careful that every URL returned to the user (even via indirect means like server redirects) has the extra information appended. And, if the user leaves the session and comes back via a bookmark or link, the session information can be lost.

  4. JAVA Sessions 3) Hidden form fields. HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be used to store information about the session. However, it has the major disadvantage that it only works if every page is dynamically generated, since the whole point is that each session has a unique identifier.

  5. JAVA Sessions Servlets provide a solution: the HttpSession API. This is a high-level interface built on top of cookies or URL-rewriting. In fact, on many servers, they use cookies if the browser supports them, but automatically revert to URL-rewriting when cookies are unsupported or explicitly disabled. But the servlet author doesn't need to bother with many of the details, doesn't have to explicitly manipulate cookies or information appended to the URL, and is automatically given a convenient place to store data that is associated with each session.

  6. JAVA Sessions What is a Session ?A session is pretty much what it sounds, when a user makes a page request to the server, the server creates a temporary session to identify that user. So when that same user goes to another page on that site, the server identifies that user. So a session is a small and temporary unique connection between a server and the user enabling it to identify that user across multiple page requests or visits to that site.

  7. JAVA Sessions What is Session Management ?Ok now you know what is a session. Session management is to use the API provided by your application server to identify the user across multiple page requests. Note that every server has it's own set of API for session management, since we are talking about 'Managing Sessions with Java Servlets', we will be making use of the Servlet API 2.2 which almost all of the Java application servers support.

  8. JAVA Sessions Why use Session Management ?Hundreds and thousands of simultaneous users can be visiting your site and if you can identify each of them separately then it can provide tremendous benefits to you. Following are only some of the uses:

  9. JAVA Sessions Customizations : Your can allow site visitors to customize the look and feel of your site, thus show each user a different view of your site. You can also show different content to different users depending on their preferences.

  10. JAVA Sessions Security : You can allow membership based access to  your site thus making sure that only members get to see special content on your site. After logging in you can identify members from non-members by setting an attribute on the user session to some value. Thus no need to log in again and again.

  11. JAVA Sessions User Behavior : You can log user behavior like how many ad views have been shown to the user. If lot have been shown with no response from the user then it is time to change that ad. This is a great feature really, if you are into making an ad rotation software you can count how many ad views of which advertiser have been shown to the user and if user doesn't click through then better change that ad with some other one instead of wasting ad views of the same ad on this user.

  12. JAVA Sessions HttpSession InterfaceManaging sessions has been made extremely easy by the Servlet API since there is just a single interface involved and that interface is HttpSession interface. You then invoke methods of this interface to interact with the user.

  13. JAVA Sessions Methods of HttpSession InterfaceBefore going into the details of using different methods of this interface, lets first see what are different methods available to us.

  14. JAVA Sessions getAttribute(), getAttributeNames(), setAttribute(), removeAttribute() These methods are used to set, get and remove objects from a user session. We will see later how to use them.

  15. JAVA Sessions getId()  Every session created by the server has a unique 'id' associated with it in order to identify this session from other sessions. This method returns the 'id' of this session.

  16. JAVA Sessions getCreationTime() Simple returns a long value indicating the date and time this session was created, meaning there by that you get the time this user first accessed your site.

  17. JAVA Sessions getLastAccessedTime()  Returns a long value indicating the last time user accessed any resource on this server.

  18. JAVA Sessions getMaxInactiveInterval(), setMaxInactiveInterval()  Return and set the maximum inactive interval in seconds for this session respectively. Note that every session has a maximum inactive interval during which if user doesn't make request to the server, his session is invalidated.

  19. JAVA Sessions isNew() Returns a boolean value indicating if the session is new. It means that either it is the first page of the site user has hit so his session is new and has just been created or that user is not accepting cookies required for managing sessions so this value will then always return true.

  20. JAVA Sessions invalidate()  Simply invalidates a session. You can use this method on a 'logout' page allowing user to end his session. If after invalidation of his session user accesses some resource on the site then a new session will be created for it.

  21. JAVA Sessions

  22. JAVA Sessions

  23. JAVA Sessions

  24. JAVA Sessions

  25. JAVA Sessions

  26. JAVA Sessions 2. The Session Tracking API Using sessions in servlets is quite straightforward, and involves looking up the session object associated with the current request, creating a new session object when necessary, looking up information associated with a session, storing information in a session, and discarding completed or abandoned sessions. 2.1 Looking up the HttpSession object associated with the current request. This is done by calling the getSession method of HttpServletRequest. If this returns null, you can create a new session, but this is so commonly done that there is an option to automatically create a new session if there isn't one already. Just pass true togetSession. Thus, your first step usually looks like this: HttpSession session = request.getSession(true);

  27. JAVA Sessions 2.2 Looking up Information Associated with a Session. HttpSession objects live on the server; they're just automatically associated with the requester by a behind-the-scenes mechanism like cookies or URL-rewriting. These session objects have a builtin data structure that let you store any number of keys and associated values. Here's one example, assuming ShoppingCart is some class you've defined yourself that stores information on items being purchased.

  28. JAVA Sessions HttpSession session = request.getSession(true); ShoppingCartpreviousItems = (ShoppingCart)session.getAttribute("previousItems"); if (previousItems != null) { doSomethingWith(previousItems); } else { previousItems = new ShoppingCart(...); doSomethingElseWith(previousItems); }

  29. JAVA Sessions In most cases, you have a specific attribute name in mind, and want to find the value (if any) already associated with it. However, you can also discover all the attribute names in a given session by calling getAttributeNames, which returns an Enumeration.

  30. JAVA Sessions 2.3 Associating Information with a Session As discussed in the previous section, you read information associated with a session by using getAttribute. To specify information, you  setAttribute, supplying a key and a value. Note that setAttribute replaces any previous values. Sometimes that's what you want (as with the referringPage entry in the example below), but other times you want to retrieve a previous value and augment it (as with the previousItems entry below). Here's an example:

  31. JAVA Sessions HttpSession session = request.getSession(true); session.setAttribute("referringPage", request.getHeader("Referer")); Enumeration previousItems = session.getAttribute("previousItems"); if (previousItems == null) { previousItems = new ShoppingCart(...); } String itemID = request.getParameter("itemID"); previousItems.addEntry(Catalog.getEntry(itemID)); // You still have to do setAttribute, not just modify //the cart, since // the cart may be new and thus not already stored in //the session. session.setAttribute("previousItems", previousItems);

  32. JAVA Sessions Example Session Code package pack1; import java.io.Serializable; public class Counter implements Serializable {//N.B. classes that are used by your Session must implement Serializable private int count = 0; public intgetCount() { return count; } public void increment() { count++; } }

  33. JAVA Sessions //TestSession Java file file imports package pack2; import pack1.Counter; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.*; import javax.servlet.http.*;

  34. JAVA Sessions protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { HttpSession session = request.getSession(true); // declare out Counter object Counter counter; if(session.isNew()) { counter = new Counter(); session.setAttribute("counter", counter); } // incrementing page view count in our Counter object counter = ((Counter)session.getAttribute("counter")); counter.increment();

  35. JAVA Sessions // retrieving session info long currentTime = System.currentTimeMillis(); long creationTime = session.getCreationTime(); long lastAccessed = session.getLastAccessedTime(); long maxInterval = session.getMaxInactiveInterval(); String sessionId = session.getId(); String mode = request.getParameter("mode");

  36. JAVA Sessions // print content out.print("<html><head>"); out.print("<style>body, p { font-family:tahoma;"); out.print("font-size:12pt; } a { text-decoration:none;"); out.print("color:blue; }</style></head>"); out.print("<body>");

  37. JAVA Sessions if(session.isNew()) { out.print("<p>New Session created.</p>"); } else { out.print("<p>Old Session. "); out.print("Age : "); currentTime = System.currentTimeMillis(); out.print( (currentTime - creationTime) / 60000 ); out.print(" minutes.</p>"); }

  38. JAVA Sessions out.print("<p>You have visited this page : "); out.print( counter.getCount() ); out.print(" times.<br>"); out.print("Created at : "); out.print( new Date(creationTime) ); out.print("<br>"); out.print("Last accessed : "); out.print( new Date(lastAccessed) ); out.print("<br>"); out.print("SessionID : "); out.print( sessionId );

  39. JAVA Sessions out.print("</p><p>"); out.print("Note! Session will be inactivated after "); out.print("a period of inactivity of <b>"); out.print( (maxInterval / 60) ); out.print("</b> minutes."); out.print("</p><p>");

  40. JAVA Sessions if( mode != null && mode.equals("invalidate")) { session.invalidate(); out.print("<a href=\"/sessionExample"); out.print("/TestSessionServlet\">"); out.print("Start New Session.</a>"); } else { out.print("<a href=\"/sessionExample/"); out.print("TestSessionServlet?mode=invalidate\">"); out.print("Invalidate this Session.</a>"); }

  41. JAVA Sessions out.print("</p></body></html>"); } finally { out.close(); } }

  42. JAVA Sessions Nota Bene Primitive data types cannot be bound to user session : Most people make the mistake of binding primitive data types like int etc to the user session. This is not possible and you will get a translation-time error.  The HttpSession interface only allows objects to be bound to the session.

  43. JAVA Sessions Smaller the object the better it is : Since session may be required to be maintained across multiple servers, it is better that the size of objects bound to it remain small.

  44. JAVA Sessions Make sure session level objects implement Serializable interface It is imperative that you understand this. All session level objects must implement Serializable interface because if your site spans multiple servers then the session level objects will not be ported to the other server. So in order to properly track user session along with all the bounded objects across multiple servers, your classes must implement Serializable interface.

  45. JAVA Sessions

More Related