JSP & Servlet Session Control

Source: Internet
Author: User
Tags button type exit implement interface session id reset sessions
Js|servlet| Control JSP & servlet Session Control

Author: Guipei

Objective
As an important part of Java EE, the session processing occupies a very important position in the JSP and Servlet specification. At present, a lot of information is very detailed to explain how to deal with session tracking. However, few people are involved with session control, which was originally in the servlet specification, and the servlet provided Httpsessioncontext interface processing session control, but after servlet API 2.1, this feature was canceled and referenced to the original text (as The Java (tm) Servlet API 2.1 for the security reasons with no replacement. This interface'll is removed in a future version of the This API.).

In this article, the author will introduce you to a session control method, using listener technology to achieve httpsessioncontext function replacement. Many developers can use this feature to accomplish certain tasks in some situations, such as: Online staff information viewing, online personnel control and so on.



Analysis
This paper introduces the session control function by example. Use a number of JSP pages, and a Java class to complete the entire feature demo. Please refer to the table below:

Component
Function

Com.guipei.listener. Sessionlistener
Monitor components to complete the Httpsessioncontext function

index.jsp
Implement user login, create a new session

logout.jsp
Implement user exit, user automatically delete session

display.jsp
Display user login information, automatically transferred to the user after landing

session.jsp
List all current Sessions

kill.jsp
Kill the specified session, make this user connection invalid




Realize
The Listener class Com.guipei.listener.SessionListener implements the Web application monitoring function, it realizes the Httpsessionlistener interface, can monitor sessioncreated ( Httpsessionevent se) and sessiondestroyed (Httpsessionevent se) methods, so we can easily handle session control during session creation and destruction events.

In this class, we create a static instance variable hashtable HT, one of the benefits of using Hashtable is that it is a thread-safe collection class that doesn't require us to do more threading. Use this collection class to save the session object that we want to control. Easy to handle related tasks in listening events.

See all code:



Package Com.guipei.listener;



Import java.util.Hashtable;

Import Java.util.Iterator;



Import javax.servlet.http.HttpSession;

Import javax.servlet.http.HttpSessionEvent;

Import Javax.servlet.http.HttpSessionListener;



public class Sessionlistener implements Httpsessionlistener {



Collection object, saving a reference to the Session object

Static Hashtable ht = new Hashtable ();



Implement Httpsessionlistener interface, complete session creation event control

public void sessioncreated (Httpsessionevent arg0) {

HttpSession session = Arg0.getsession ();

Ht.put (Session.getid (), session);

SYSTEM.OUT.PRINTLN ("Create session:" + Session.getid ());

}



Implement Httpsessionlistener interface, complete session destroy event control

public void sessiondestroyed (Httpsessionevent arg0) {

HttpSession session = Arg0.getsession ();

System.out.println ("Destory session:" + Session.getid ());

Ht.remove (Session.getid ());

}



Returns a collection of all session objects

static public iterator Getset () {

Return Ht.values (). iterator ();

}



Returns the specified Session object based on the session ID

static public HttpSession getsession (String sessionId) {

Return (HttpSession) ht.get (sessionId);

}

}






The page index.jsp the ability to process user login and create new sessions. After the validation is complete, jump to the display.jsp page.

<%@ page contenttype= "text/html; charset=gb2312 "%>

<!--Copyright (c) 2002 by Objectlearn. All Rights Reserved. -->

<%

String strName = null;

String strthing = null;

try {

StrName = Request.getparameter ("name");

strthing = Request.getparameter ("thing");

if ((StrName = null) | | (Strname.length () ==0)) {

throw new Exception ("null StrName");

}

if ((strthing = null) | | (Strthing.length () ==0))

throw new Exception ("null strthing");



Add session

Session.setattribute ("name", StrName);

Session.setattribute ("thing", strthing);

Response.sendredirect ("display.jsp");



catch (Exception e) {

}

%>



<title>Welcome</title>


<body>

<center>Welcome</center>



<form method= ' Post ' >

<table align= ' center ' >

<tr>

<td>name:</td>

<td> <input name= ' name ' type= ' input '/> </td>

</tr>

<tr>

<td>thing:</td>

<td> <input name= ' thing ' type= ' input '/> </td>

</tr>

<tr>

&LT;TD align= ' right ' > </td>

&LT;TD align= ' right ' >

<button type= ' Submit ' >submit</button>

<button type= ' Reset ' >reset</button>

</td>

</tr>

</table>

</form>

</body>







Page display.jsp for user login after the display function, if the user has not made a login request, will automatically forward to the Index.jsp page, to ensure that users landing.

<%@ page language= "java" pageencoding= "GB2312"%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >



<title>lomboz jsp</title>


<body bgcolor= "#FFFFFF" >



<%



if (Session.isnew () ==true) {

Response.sendredirect ("index.jsp");

}

Out.println ("Name:" + session.getattribute ("name") + "<br>");

Out.println ("thing:" + session.getattribute ("thing") + "<br>");

OUT.PRINTLN ("Session ID:" + session.getid () + "<br>");

Out.println ("Create Time:" + session.getcreationtime ());



%>



</body>





Page logout.jsp for users to exit the login, the active way to destroy the session.

<%@ page language= "java" pageencoding= "GB2312"%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >



<title>lomboz jsp</title>


<body bgcolor= "#FFFFFF" >

<%

if (Session.isnew ()!=true) {

Session.invalidate ();

}

Response.sendredirect ("index.jsp");

%>

</body>





Page session.jsp lists the current session user and provides a connection to kill.jsp that can be used to destroy the specified session operation.

<%@ page language= "java" pageencoding= "GB2312"%>

<%@ page import= ' com.guipei.listener.*,java.util.* '%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >



<title>lomboz jsp</title>


<body bgcolor= "#FFFFFF" >



List Session Object

<br>

<table border= ' 1 ' >

<tr bgcolor= ' Yellow ' >

<td>session id</td>

<td>user name </td>

<td>what thing </td>

<td>create Time </td>

<td>operate</td>

</tr>



<%

Iterator iterator = Sessionlistener.getset ();

while (Iterator.hasnext ()) {

try{

HttpSession Session1 = (HttpSession) iterator.next ();

Out.println ("<tr>");

Out.println ("<td>" + session1.getid () + "</td>");

Out.println ("<td>" + session1.getattribute ("name") + "</td>");

Out.println ("<td>" + Session1.getattribute ("thing") + "</td>");

Out.println ("<td>" + session1.getcreationtime () + "</td>");

Out.println ("<td> <a href= ' kill.jsp?sessionid=" + session1.getid () +

"' >kill </a> </td>");



Out.println ("</tr>");

SYSTEM.OUT.PRINTLN ("list" + Session1.getid ());

}catch (Exception ex) {

Ex.printstacktrace ();

Return

}

}

%>

</table>

</body>





The page kill.jsp implements the function of destroying the specified session, receives a sessions ID parameter, obtains the corresponding conversation object from the collection of our saved dialog objects, invokes the Invalidate method, and destroys the object.

<%@ page language= "java" pageencoding= "GB2312"%>

<%@ page import= "com.guipei.listener.*"%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >



<title>lomboz jsp</title>


<body bgcolor= "#FFFFFF" >

<%

Kill the session

try {

String Strsid = Request.getparameter ("SessionID");

HttpSession Session1 = sessionlistener.getsession (STRSID);

if (session1!=null) {

Session1.invalidate ();

}

catch (Exception e) {

E.printstacktrace ();

}

Response.sendredirect ("session.jsp");

%>



</body>







After you complete the above code, you also need to add the following elements to the web.xml description. Enables the Sessionlistener class to play the listening function.

<listener>

<listener-class>

Com.guipei.listener.SessionListener

</listener-class>

</listener>



Summarize
The authors are not quite sure why the servlet specification cancels the Httpsessioncontext interface, although it declares the reason for the cancellation, but we can still easily implement this functionality through the Httpsessionlistener interface.

Hopefully this article will provide a new way to replace the Httpsessioncontext interface that has been abolished by the servlet specification. Let's make it easy for us to do session operations.





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.