JSP Sessions

A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable is associated with that session. In case of web applications the default time-out value for session variable is 20 minutes, which can be changed as per the requirement.

Here is a set of pages that put a user’s name in the session, and display ion another page.  Try out installing and using these.

First we have a form, let us call it FirstPage.html

<HTML> <BODY> <FORM METHOD=POST ACTION="Save.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20> 
<P><INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>

The target of the form is “Save.jsp”, which saves the user’s name in the session.  Note the variable  “session“.  This is another variable that is normally made available in JSPs, just like out and requestvariables.  (In the @page directive, you can indicate that you do not need sessions, in which case the “session” variable will not be made available.)

<%    String name = request.getParameter( "username" );    session.setAttribute( "theName", name ); %> <HTML> <BODY> <A HREF="NextPage.jsp">Continue</A> </BODY> </HTML>

The Save.jsp saves the user’s name in the session, and puts a link to another page, NextPage.jsp.

NextPage.jsp shows how to retrieve the saved name.

<HTML> <BODY> Hello, <%= session.getAttribute( "theName" ) %> </BODY> </HTML>

Leave a Reply

Your email address will not be published. Required fields are marked *