المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : How to use Session Scope in JSP



A7med Baraka
02-05-2010, 07:33 AM
A session is an object associated with a visitor. Data can be put in the session and retrieved from it, much like a Hash table. A different set of data is kept for each visitor to the site.
Here is a set of pages that put a user's name in the session, and display it elsewhere. Try out installing and using these.
First write a form, let us call it DemoSession.html
DemoSession.html

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


http://www.java-tips.org/images/stories/tips/j2ee/240606/JSPTip1.1.jpg
The target of the form is "DemoSession.jsp", which saves the user's name in the session.
DemoSession.jsp



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



http://www.java-tips.org/images/stories/tips/j2ee/240606/JSPTip1.2.jpg
The DemoSession.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.
NextPage.jsp



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



http://www.java-tips.org/images/stories/tips/j2ee/240606/JSPTip1.3.jpg
The session is kept around until a timeout period. Then it is assumed that the user is no longer visiting the site, and the session is discarded.

A7med Baraka
02-05-2010, 07:40 AM
<%@ page errorPage="errorpage.jsp" %>

<html>
<head>
<title>UseSession</title>
</head>
<body>
<%
Integer count = (Integer)session.getAttribute("COUNT");
// If COUNT is not found, create it and add it to the session
if ( count == null ) {

count = new Integer(1);
session.setAttribute("COUNT", count);
}
else {
count = new Integer(count.intValue() + 1);
session.setAttribute("COUNT", count);
}
out.println("<b>Hello you have visited this site: "
+ count + " times.</b>");
%>
</body>
</html>