[ Team LiB ] |
![]() ![]() |
Storing Data in a session ObjectWhen dealing with HTTP, there is no permanent connection between a browser and a Web server. When the browser needs a page from the Web server, it opens a connection, retrieves the page, and then closes the connection. After that, the Web server has no idea what is happening on the browser. The browser could crash, or the entire client computer could be turned off, and the Web server would be oblivious. HTTP Persistent Connections
Furthermore, when another connection is made, the Web server does not associate the new connection with any other that has been made in the past. In other words, HTTP is not session-oriented. Sessions allow an application to remember something about a client that persists between connections. In the first part of this hour, we saved information that we did not want to forget by passing it back and forth between the client and application. In this way, we created a primitive session. Servlets and JSPs do have a notion of a session. Instead of playing toss with variables, servlets and JSPs can store information on the server using a single key that the client remembers. Servlets and JSPs use an HttpSession object to accomplish this. Using the session Object in a JSPJavaServer Pages have several built-in objects. You have already seen two of them: request and out. The next important one is called session, and it's an instance of HttpSession. The three methods that you use the most in the session object are getAttribute, setAttribute, and removeAttribute. The declarations for these methods are public void setAttribute(String name, Object value) throws IllegalStateException public Object getAttribute(String name) throws IllegalStateException public void removeAttribute(String name) throws IllegalStateException These methods act much like the get and put methods in the Hashtable class. That is, setAttribute associates a name with a value, and getAttribute returns the value associated with a name or returns null if there is no value associated. For example, to store some data in a session, you would type the following: session.setAttribute("someKey", "here is my data"); To retrieve the data back out of the session, you would type this: String myData = (String) session.getAttribute("someKey"); An IllegalStateException is thrown when you try to get or set an attribute on an invalid session. A session becomes invalid either when you call its invalidate method or after the session has timed out. The servlet engine keeps track of how long it has been since a session has been accessed; after a certain period of inactivity, the session is marked as invalid. You can configure the amount of time it takes to time out a session, either on a per-session basis or for all sessions. Specifying the Session Timeout Duration
Listing 12.4 shows the Login.jsp page modified to support the session object. Notice that it no longer needs to use hidden form variables. Listing 12.4 Source Code for Login2.jsp<%@ page language="java" import="java.util.*" %> <html> <body bgcolor="#ffffff"> <% // Get the login information. String userName = request.getParameter("username"); String password = request.getParameter("password"); // Store the username in the session. session.setAttribute("username", userName); %> Welcome, <%=userName%>! <form action="ColorServlet2" method="POST"> <p> Please enter your favorite color: <select name="color"> <option value="blue" SELECTED>Blue</option> <option value="red">Red</option> <option value="green">Green</option> <option value="yellow">Yellow</option> <option value="mauve">Mauve</option> </select> <p> <input type="submit" value="Choose color!"> </form> </body> </html> Having Trouble with the Example?
Using the session Object in a ServletYou have probably guessed this already, but the session object you use in a servlet is identical to the one you use in a JSP. The only difference is that it isn't already conveniently sitting around in a variable named session. Instead, you must get the session object from the request object. JSPs Automatically Obtain a Session
To get the session object from the request object, just call the getSession method: HttpSession session = request.getSession(); Inside a servlet, you use the same getAttribute and setAttribute methods to update session variables as you do in a JSP. After all, the session object is an instance of HttpSession in both a servlet and a JSP. Obtain a Session Before Starting Your Response
Listing 12.5 shows the necessary modifications to ColorServlet to make it use HttpSession rather than form variables. Listing 12.5 Source Code for ColorServlet2.javapackage examples; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class ColorServlet2 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // Tell the Web server that the response is HTML. response.setContentType("text/html"); // Get the PrintWriter for writing out the response. PrintWriter out = response.getWriter(); // Fetch the color parameter. String color = request.getParameter("color"); // Get the username from the session. HttpSession session = request.getSession(); String userName = (String) session.getAttribute("username"); // Write the HTML back to the browser. out.println("<html>"); out.println("<body bgcolor=\"#ffffff\">"); out.println("Well, I see that "+userName+ "'s favorite color is "+color+"."); out.println("</body>"); out.println("</html>"); } } HttpSessions Work Only in HttpServlets
![]() |
[ Team LiB ] |
![]() ![]() |