Sei sulla pagina 1di 5

Session

Management in JSP
Objectives
Understand fully the concept of sessions in web development. Track user data using sessions. Learn how to set and get session data

Concepts
Hypertext Transfer Protocol is stateless. This means to say that a client running a web browser must always establish a new connection to a web server to have a consistent link between a client running the web browser and the web server (via HTTP post or get method). Therefore, a single HTTP get or post operation become unreliable for a web server on transactions needing more than a single HTTP get or post operation. The act of keeping track of users as they move around a website is known as session tracking. For example, once a user has been authenticated to the web server, the users next HTTP operation either post or get should not cause the web server to ask for the users account and password again. Session management is the technique used by the web developer to make stateless HTTP protocol support session state. The session information is stored on the web server using the session identifier (SESSION ID) generated as a result of the first request from the end user running a web browser. These SESSION IDs and their corresponding data are stored in the web servers local memory, flat files or database.

JSP Sessions
Each visitor of a web site is associated with a session object. As mentioned above, a session is a storage where we put data into it and retrieve this data from it, much like a Hash table. Each visitor will have a different set of data. Table 1. Session Methods Method removeAttribute(String name) setAttribute(String name, Object value)

getCreationTime()

Description Remove the attribute and value from the session Set the object to the named attribute. This method is used to write an attribute and value to the session. Used to return the session created time. The returned time value would be in

Example session.removeAttribute(user); session.setAttribute(userid, uAAxd);

session.getCreationTime()

getLastAccessedTime()

getID()

getAttributeNames()

milliseconds, the time value is midnight January 1, 1970 GMT Return the latest time of the client request associated with the session. By using this method, it is possible to determine the last time the session was accessed before the current request. The returned time value would be in milliseconds and the time values is since midnight January 1, 1970 This method is used to return the unique identifier associated with the session Returns a java.util.Enumeration object that contains the names of all attributes in the HttpSession object. Used to discard the session and releases any objects stored as attributes. This methods helps to reduce memory overhead and achieves improvement in performance. Return the maximum amount of time interval in seconds that the servlet container will keep this session open between client accesses. This returns the maximum amount of time that a session can be inactive before it is deleted. Set the timeout explicitly for each session. A user can use this method to set the default timeout

session.getLastAccessedTime();

session.getID();

invalidate()

Enumeration names = session.getAttributeNames(); while (names.hasMoreElements()){ System.out.println( (String) names.nextElement() ); } session.invalidate();

getMaxInactiveInterval()

session.getMaxInactiveInterval();

setMaxInactiveInterval()

Session.setMaxInactiveInterval(600) //in seconds

How Java Keeps Track of Sessions


CLIENT BROWSER BROWSER BROWSER

jsessionid=EB573E..

jsessionid=EBE573..

SERVER BROWSER BROWSER BROWSER

First HTTP Request: The browser requests a JSP. The servlet engine creates a session object and assigns an ID for the session

First HTTP Response: The server returns the requested page and the ID for the session.

Following HTTP Request: The browser requests a JSP. The servlet engine uses the session ID to associate the browser with this session object.

The figure above shows how the servlet API keeps track of sessions. (servlet is a Java programming language class used to extend the capabilities of a server that host applications accessed via request-response programming model commonly used to extend the applications hosted by web servers). 1. A browser on a client requests a JSP or servlet from the web server, which passes the request to the servlet engine, our Tomcat. 2. The servlet engine checks if the request includes an ID for the Java session. a. If it doesnt, the servlet engine creates a unique ID for the session plus a session object that can be used to store the data for the session. 3. The web server uses the session ID generated to relate each browser to the session object, even though the server still drops the HTTP connection after returning each page. By default, the servlet API uses a cookie to store the session ID within the clients browser. This is an extension of the HTTP protocol. Then when the next request is made, this cookie is added to the request. However, if cookies have been disabled within a browser, this type of session tracking wont work. To get around this problem, the servlet API provides a way to rewrite the URL so it includes the session ID. This is known as URL encoding and it works even if cookies have been disabled within a browser.

Setting and Getting Session Attributes


A Method of the request Object Method Description getSession( ) Returns the HttpSession object associated with this request. If the request is not associated with a session, this method creates a new HttpSession object and returns it Three Methods of the session Object Method Description setAttribute(String name, Object o) Stores any object in the session as an attribute and specifies a name for the attribute getAttribute(String name) Returns the value of the specified attribute as an Object type. If no attribute exists for the specified name, this method returns a null value. removeAttribute(String name) Removes the specified attribute from this session.

Examples: Instantiate a new session object. HttpSession session = request.getSession( ); Setting a String object as an attribute session.setAttribute(productCode, productCode); Setting a user-defined object as an attribute Cart cart = new Cart(productCode); session.setAttribute(cart, cart); Getting a String object from a session String productCode = (String) session.getAttribute(productCode); Getting a user-defined object from a session Cart cart = (Cart) session.getAttribute(cart); if (cart == null ) cart = new Cart( );

Removing a session object session.removeAttribute(productCode); NOTES: A session object is created when a browser makes the first request to a site. It is destroyed when the session ends. A session ends when a specified amount of time elapses without another request or when the user exits the browser.

The session object is a built-in JSP object (implicit). As a result, you do not need to create the session object when working with JSPs.

Tracking Sessions Using URL Encoding


URL Encoding is the process of converting string into valid URL format. The valid URL format means that the URL contains alpha, digit, extra, escape characters. To use URL encoding, you use the encodeURL() method of the response object to encode all the URLs for the JSPs that are used in the application. Once you do that, the session ID is added to a URL whenever the URL is requested from a browser. In the Address box of the browser, you should be able to see that a session ID has been added to the end of the URL, but before the parameters. When you use URL encoding, you must be sure to encode all URLs in the application. If you forget one, the application will lose track of the session as soon as the web server returns a response object that contains a URL that is not encoded. To test an application that uses URL encoding, you need to disable cookies in your browser. Then, the URL for each page in the application should include the ID for the Java session. However, if you enable cookies in your browser, the URLs of the application wont display the ID for the Java session. This shows that the encodeURL() method only rewrites the URLs of the application when necessary. A method of the response object Method Description encodeURL(String url) Returns a string for the specified URL. If necessary, this method encodes the session ID in the URL. If not, it returns the URL unchanged. Encoding a URL in a Form Tag <form action=<%=response.encodeURL(cart) %> method=post> Encoding a URL in an A tag < a href=<%=response.encodeURL(cart?productCode=1423) %> >Add To Cart </a>

Activity
1. Create a simple application comprising of a minimum of JSP 3 JSP pages and maximum of 6 JSP pages. (Create a separate directory for this). This application should demonstrate storing of valuable information regarding its purpose in sessions. In your application, please do include and demonstrate how the different session methods (refer to table 1) are used.

Potrebbero piacerti anche