Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Advanced Java Programming (Java EE) - Servlets - Lab exercise - HTTP Sessions 31242/32549/ Java EEAdvanced Internet Programming INFO: What's New FAQ Software Machines Oracle Assignments MODULES: 00 Admin 01 Intro 02 Architecture 03 Servlets 04 JSP 05 JDBC 06 RMI 06 JNDI 07 EJB 08 XML 08 Web Services 09 Security 10 Transactions 11 Legacy 12 Review 99 Design LINKS: START page Faculty of IT UTS Module: Servlets Lab exercise - HTTP Sessions This laboratory exercise involves modifying your Counter servlet to introduce a second counter. The second counter should keep count of how many times the current user has accessed the servlet, and this counter will be different for each user. Level of Difficulty: 4 (moderately difficult) Estimated time: 20 minutes Pre-requisites: Completed the Counter servlet lab exercise A SessionCounter servlet The goal of this exercise is to create a servlet that, when invoked, will print out two different counter values: the original CounterServlet value (total number of times the servlet has been invoked since it was reloaded); a counter that keeps count of the number of times the current user has invoked the servlet in his/her current session. This requires the use of sessions and session variables in your servlet. The state problem As you know, HTTP is a stateless protocol. This means that a web server sees each incoming request as being completely independent from all earlier requests. However many web applications need to keep state information at the server, so the statelessness of HTTP is a problem. For example, when you access an online banking application, you first log in with your account number and PIN, and then as you click through various pages on the bank's web site, the application running on the bank's web server needs to keep track of who you are. Another example is the ubiquitous shopping cart. As you browse through a product catalog, and add items to your cart, the web application needs to keep track of which items are currently in your cart. In web application terminology, the word session refers to the interaction between a user and a web application, where the web application keeps state information about the user's interactions even though they span multiple HTTP requests. A session typically lasts for a single browsing session. If a user closes their browser and re-opens it and goes back to the web application, they will have to begin a new session. If a user doesn't access the web application for a period of time, their session might time out (whether or not it does is application-dependent). There are different ways to implement sessions on top of the stateless HTTP protocol. The two typical ways are using cookies and URL rewriting. These will be described in the lecture notes. Sessions and Java Java servlets have built-in support for session management that simplifies the task of creating a web application that requires a session-based interaction with a user. The abstraction used in Java is the notion of session attributes that can be stored in a session object. The session object acts like a container. You can store attributes (name/value pairs) into the session object, and you can retrieve attributes out of the session object. Attributes that are stored in the session object will still keep their value in between successive HTTP requests. Each "attribute value" is, of course, a Java object. Each attribute stored in the session has a name, and a value. The name is just a String. The value is a Java object. The HttpSession class uses the methods setAttribute() and getAttribute for storing and retrieving attributes in sessions respectively. Where do you get the session object from in the first place? From the request object. You get the session from the request. If there was already a session established, then you will have access to all the variables stored in the session. However if there was not already a session established, one will be created automatically (by default), and you will then have access to a blank session object in which you can store variables. Now for some code snippets: Getting hold of a session object (from the request): HttpSession sess = request.getSession(); Storing an object into the session: Integer counterVal = new Integer(105); sess.setAttribute("sessionCounter", counterVal); Retrieving an object from the session: Integer newCounterVal = (Integer) sess.getAttribute("sessionCounter"); Alternatively, 2 and 3 can be simplified by using auto-boxing and auto-unboxing, introduced in J2SE 5.0 (September 30, 2004) and Java EE 5 (May 11, 2006). So 2 and 3 can be: int counterVal = 105; /* counterVal is auto-boxed to an Integer object and it is stored in the session */ sess.setAttribute("sessionCounter", counterVal); /* * the object returned from the session is casted to Integer then * auto-unboxed to an int value. */ int newCounterVal = (Integer) sess.getAttribute("sessionCounter"); SessionCounterServlet With that knowledge, work on modifying your CounterServlet to add a second counter - one that keeps track of the number of accesses a user has made in the current session. To test, try accessing your servlet from two different browsers (e.g. Firefox and IE on the same machine, or two different browsers on two different machines). Don't just use two different windows belonging to the same browser (because different browser windows still share cookie data, which is used to maintain sessions). Aside: common usage pattern for sessions Typically a servlet has to be able to deal with the situation when a session does not already exist and has to be initialised. One way to do this is to retrieve an attribute from the session, and if it is null (or if a flag is set to indicate that the session is new), then automatically initialise the attribute and store it in the session. This means that your servlet can both deal with existing session attributes and automatically set up a new session attribute when needed. Here is a code sample: HttpSession sess = request.getSession(); Integer sesscounter = (Integer) sess.getAttribute("numAccesses"); if (sess.isNew() || sesscounter == null) { sesscounter = new Integer(0); sess.setAttribute("numAccesses", sesscounter); } URL Rewriting The following SessionServletApp servlet illustrates the use of URL rewriting when cookies aren't supported in your browser. This servlet also illustrates the use of Servlet API to extract various information related to a session. For this servlet to work, it assumes it is mapped to the URL "session-app". /* Retrieve the count value from the session */ Integer ival = (Integer) session.getAttribute("numAccesses"); /* If the counter is not currently contained in the session, one needs to be created: */ if (ival == null) { ival = new Integer(1); } else { ival = new Integer(ival.intValue() + 1); } session.setAttribute("numAccesses", ival); /* Print out how many times the user has hit the current page: */ out.println("You have hit this page " + ival + " times.

"); out.println("Click here"); out.println(" to ensure that session tracking is working even " + "if cookies aren't supported.
"); out.println("

"); /* Finally, demonstrate some of the more common methods in the HttpSession object surrounding sessions: */ out.println("

Request and Session Data:

"); out.println("Session ID in Request: " + request.getRequestedSessionId()); out.println("
Session ID in Request from Cookie: " + request.isRequestedSessionIdFromCookie()); out.println("
Session ID in Request from URL: " + request.isRequestedSessionIdFromURL()); out.println("
Valid Session ID: " + request.isRequestedSessionIdValid()); out.println("

Session Data:

"); out.println("New Session: " + session.isNew()); out.println("
Session ID: " + session.getId()); out.println("
Creation Time: " + new java.util.Date(session.getCreationTime())); out.println("
Last Accessed Time: " + new java.util.Date(session.getLastAccessedTime())); Ensure your browser accepts cookies by going to Edit -> Preferences -> Under "History" select "Remember history" (Firefox) or Tools -> Privacy -> Sites (Internet Explorer). If the browser is not allowed to accept cookies, please enable it to accept cookies for this exercise to work. You may need to start the browser again for any changes to take place. When you access the servlet for the very first time, observe the information returned from the server. Among many things, it should display the session as new. If you press 'Reload' button, the new session should be displayed as false. Also, the request session id from cookie and URL are true and false respectively. This is because you browser is set to accept cookies. Now, disable the cookies by going to Edit -> Preferences -> Under "History" select "Use custom settings for history" and uncheck "Accept cookies from sites" (Firefox) (see Tools -> Options -> Privacy/ Tools->Privacy-Sites). Restart the browser to take effect of this new change (in Firefox it is sufficient to reload the page). Don't forget to reset to the setting you had before after the exercise. Access your servlet as before and session should be correctly reported as new. Press Reload button and what you should observe is that the session is still reported as new (same behaviour for multiple reloads). Remember, earlier new session is only reported for the first time you access the page and false for any subsequent accesses (within a session). Even though you didn't use Cookies explicitly, Weblogic uses a temporary cookie to store the current session. Since your browser is set not to accept any cookies (including temporary cookies), sessions do not work correctly. However, press on 'Click here' link to enable URL writing and watch the URL that appears in the Address/Location bar. You should notice some extra text on the end of the URL indicating that URL rewriting is now being used to maintain the session state when cookies are disabled. What is also interesting to observe is that the display correctly reports the requested session id is from a URL and not from a Cookie. © 2008 University of Technology, Sydney. All Rights Reserved. Redistribution without permission prohibited.