- Java EE Tutorials
- JSP Tutorials
- Recommended Books for Java Server Pages (JSP)
Sessions are mechanism for storing client data across multiple HTTP requests. From one request to another user the HTTP server does not maintain a reference or keep any record of client previous request.
HttpSession Methods
- getAttribute : it returns stored value from session object. It returns null if no value is associated with name.
- setAttribute : It associates a value with name.
- removeAttribute : It removes all the values associated with name.
- getAttributeNames : It returns all attributes names in the session.
- getId : it returns unique id in the session.
- isNew : It determine if session is new to client.
- getcreationTime : It returns time at which session was created.
- getlastAccessedTime : It returns time at which session was accessed last by client.
- getMaxInactiveInterval : It gets maximum amount of time session in seconds that access session before being invalidated.
- setMaxInaxctiveInterval : It sets maximum amount of time session in seconds between client requests before session being invalidated.
Following ways are used to maintain session between client and web server:
Cookies
A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website and stored in a user’s web browser while the user is browsing that website.
A cookie’s value can uniquely identify a client, so cookies are commonly used for session management. Browser stores each message in a small file, called cookie.txt. When you request another page from the server, your browser sends the cookie back to the server. Cookies have lifespan and are flushed by the client browser at the end of lifespan.
Cookie objects have following methods.
- getComment () : Returns comment describing the purpose of the cookie.
- getMaxAge () : Returns maximum specified age of the cookie.
- getName() : Returns name of the cookie.
- getPath() : Returns URL for which cookie is targeted.
- getValue() :Returns value of the cookie.
- setComment(String) : Cookie’s purpose will be described using this comment.
- setMaxAge(int) : Sets maximum age of the cookie. A zero value causes the cookie to be deleted.
- setPath(String) : It determines Cookie should begin with this URL .
- setValue(String) : Sets the value of the cookie. Values with special characters such as white space, brackets, equal sign, comma, double quote, slashes , “at” sign, colon and semicolon should be avoided.
Let’s take example for cookies handling.
First we will create html file as cookie1.jsp. In this html file we are using <form> tag with method and action attributes. In method attribute we are defining HTTP method called post which do not stores requests in browser history and action tag will redirect to another JSP file called cookie2.jsp.
Listing 1: Cookie1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Session Tracking Example</title> </head> <body> <form method = "post" action="cookie2.jsp"> User Name : <input type = "text" name = "uname"> <input type="submit" value="submit" > </form> </body> </html>
Now create JSP file as cookie2.jsp. This file name should be as same as in cookie1.html file. In this JSP file we are using cookie object. Writing data to cookie object is done while loading new page. Means when submit button is pressed in cookie1.jsp page it would store value in a cookie.
Lisitng 2: cookie2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% String name=request.getParameter("uname"); Cookie cookie = new Cookie ("uname",name); response.addCookie(cookie); cookie.setMaxAge(50 * 50); //Time is in Minutes %> <p>Display the value of the Cookie</p> User Name is :<%= request.getParameter("uname")%> </body> </html>
Execute the Cookie1.jsp. Right click on Cookie1.jsp and select Run > Run As. Following output would be seen:
Enter the name and click on submit, the following output would be seen:
Hidden Form Fields
It is hidden (invisible) text field used for maintaining the state of user. We store the information in the hidden field and get it from another servlet.
Following shows how to store value in hidden field.
<input type=”hidden” name=”uname” value=”javabeat”>
Here, name is hidden field name and javabeat is hidden field value. When the form is submitted, the specified name and value are automatically included in the GET or POST data.
URL Rewriting
A static HTML page or form must be dynamically generated to encode every URL. If you cannot verify that every user of web application uses cookies, then you must consider web container need to use URL-rewriting. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting.
A web container attempts to use cookies to store the session ID. If that fails then web container tries to use URL-rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value.
Adding the session ID to a link contain following of methods:
- response.encodeURL (): Associates a session ID with a given URL.
- response.encodeRedirectURL () : If you are using redirection, this method can be used
URL Rewriting Example
Take two JSP files. Say hello1.jsp and hello2.jsp, which interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the contents. We invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp.
Listing 3: hello1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <%@ page session="true" %> <% String url =response.encodeURL ("hello2.jsp"); %> <a href='<%=url%>'>hello2.jsp</a> </body> </html>
Listing 4: hello2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <p>today's date is :<%=new java.util.Date()%></p> </body> </html>
Execute the hello1.jsp. Right click on hello1.jsp and select Run > Run As. Following output would be seen:
Click on the link hello2.jsp, the following output would be seen, (current date would printed):
Previous Tutorial : JSP API || Next Tutorial : JavaBeans in JSP