JSP & Servlet session control

xiaoxiao2021-03-06  110

In the JSP and Servlet specification for J2EE, session processing has a very important location. At present, many of the information is very detailed to explain how conversation is handled. However, rarely involve session control, originally in the servlet specification, servlet provides the HTTPSessionContext interface handling session control function, but after servlet API 2.1, this feature is canceled, refer to the original (AS of Java (TM) Servlet API 2.1 for Security Reasons, With No Replacement. This Interface Will Be Removed In A Future Version of this API.).

In this article, the author will introduce you to a method of session control, using Listener technology to implement HTTPSESSESCONTEXT functional replacement. Many developers will use this feature to complete certain tasks in some occasions, such as: online personnel information viewing, online personnel control, etc.

analysis

This article uses an example mode to introduce the session control function. Use a number of JSP pages, and a Java class completes the entire functional demo. See the table below for details:

Assembly

Features

Com.guipei.listener. SessionListener

Listening components, complete the function of httpsessionContext

Index.jsp

Implement the user login, create a new session

Logout.jsp

Implement the user to exit, the user automatically deletes session

DISPLAY.JSP

Display the user login information, automatically transfer after the user logs in

Session.jsp

List all current sessions

Kill.jsp

Kill the specified session so that this user connection is invalid

achieve

Monitor class com.guipei.listener.SessionListener implements the listening function of Web Application, which implements the HttpSessionListener interface to listen to the sessioncreated (httpsessionEvent SE) method, so we can easily create and destroy events in Session. Treatment of session during the process.

In this class, we create a static instance variable HashTable HT, which is the advantage of using HashTable is that it is a set class for thread security, no need to do more thread processing. Use this Collection class to save the session object we have to control. Easy to process 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 {

// Collect object, save the reference to the session object

Static hashtable ht = new hashtable ();

/ / Implement the HTTPSessionListener interface to complete the session creation event control

Public void sessioncreated (httpsessionever session) {httpsession session = arg0.getations ();

HT.PUT (session.getid (), session);

System.out.println ("CREATE Session:" session.getID ());

}

/ / Implement the HTTPSessionListener interface to complete the session destruction event control

Public void sessiondestroyed (httpsessioneverive) {

HttpSession session = arg0.getsession ();

System.out.println ("Destory session:" session.getID ());

HT.Remove (session.getid ());

}

/ / Return to all session objects

Static public iterator getSet () {

Return ht.values ​​(). Iterator ();

}

/ / Return the specified session object based on the session ID

Static public httpsession getsession (String sessionID) {

Return (httpsession) ht.get (sessionid);

}

}

The page index.jsp hands the user login and creates a new session. After completing the verification, jump to the Display.jsp page.

<% @ Page ContentType = "text / html; charset = GB2312"%>

<%

String strname = null;

String straw = null;

Try {

Strname = Request.getParameter ("name");

Strthning = Request.getParameter ("Thing");

IF ((strname == null) || (Strname.Length () == 0)) {

Throw New Exception ("Null Strname");

}

IF (straw == null) || () == 0))

Throw new Exception ("null strasting");

// add session

Session.SetaTRibute ("name", strname);

Session.SetaTRibute ("Thing", Strthing;

Response.sendRedirect ("Display.jsp");

} catch (exception e) {

}

%>

Welcome </ Title></p> <p></ hEAD></p> <p><body></p> <p><center> Welcome </ center></p> <p><form method = 'pos'></p> <p><table align = 'center'></p> <p><tr></p> <p><TD> Name: </ TD> <TD> <Input Name = 'Name' Type = 'Input' /> </ TD></p> <p></ TR></p> <p><tr></p> <p><TD> Thing: </ td></p> <p><TD> <Input Name = 'Thing' Type = 'Input' /> </ TD></p> <p></ TR></p> <p><tr></p> <p><TD Align = 'Right'> </ td></p> <p><TD Align = 'Right'></p> <p><Button Type = 'Submit'> Submit </ Button></p> <p><Button Type = 'Reset'> Reset </ Button></p> <p></ td></p> <p></ TR></p> <p></ table></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>Page Display.jsp Use the display function after the user login, if the user does not log in, it will automatically forward it to the index.jsp page to ensure that the user logs in.</p> <p><% @ page language = "java" PageEncoding = "GB2312"%></p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><html></p> <p><HEAD></p> <p><Title> Lomboz JSP </ Title></p> <p></ hEAD></p> <p><body bgcolor = "# ffffff"></p> <p><%</p> <p>IF (session.isnew () == true) {</p> <p>Response.sendRedirect ("index.jsp");</p> <p>}</p> <p>Out.println ("Name:" session.getattribute ("name") "<br>");</p> <p>Out.println ("Thing:" Session.gettribute ("Thing") "<br>");</p> <p>Out.println ("session ID:" session.getid () "<br>");</p> <p>Out.println ("CREATE TIME:" session.getcreationTime ());</p> <p>%></p> <p></ body></p> <p></ html></p> <p>The page logout.jsp is used for the user to quit the landing and uses active way to destroy the session.</p> <p><% @ page language = "java" PageEncoding = "GB2312"%></p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><html></p> <p><HEAD></p> <p><Title> Lomboz JSP </ Title></p> <p></ hEAD></p> <p><body bgcolor = "# ffffff"> <%</p> <p>IF (session.isnew ()! = true) {</p> <p>session.INVALIDATE ();</p> <p>}</p> <p>Response.sendRedirect ("index.jsp");</p> <p>%></p> <p></ body></p> <p></ html></p> <p>The page session.jsp lists the current session user and provides a connection to kill.jsp, which can be used as a destruction specified session operation.</p> <p><% @ page language = "java" PageEncoding = "GB2312"%></p> <p><% @ Page Import = 'com.guipei.listener. *, java.util. *'%></p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><html></p> <p><HEAD></p> <p><Title> Lomboz JSP </ Title></p> <p></ hEAD></p> <p><body bgcolor = "# ffffff"></p> <p>List session Object</p> <p><br></p> <p><Table Border = '1'>></p> <p><tr bgcolor = 'Yellow'></p> <p><TD> session ID </ td></p> <p><TD> User Name </ td></p> <p><TD> What Thing </ TD></p> <p><TD> CREATE TIME </ TD></p> <p><TD> Operate </ TD></p> <p></ TR></p> <p><%</p> <p>Iterator itrator = sessionListener.get sett ();</p> <p>While (item.hasnext ()) {</p> <p>Try {</p> <p>Httpsession session1 = (httpsession) item.next ();</p> <p>Out.println ("<TR>");</p> <p>Out.println ("<TD>" Session1.GetId () "</ TD>");</p> <p>Out.println ("<TD>" Session1.GetaTRibute ("Name") "</ TD>");</p> <p>Out.println ("<TD>" Session1.GetaTRibute ("Thing") "</ TD>");</p> <p>Out.println ("<TD>" session1.getcreationTime () "</ td>");</p> <p>Out.println ("<TD> <a href = 'kill.jsp? sessionid =" session1.getid () </p> <p>"'> kill </a> </ td>");</p> <p>Out.println ("</ TR>");</p> <p>System.out.println ("List" session1.getid ());} catch (exception ex) {</p> <p>EX.PrintStackTrace ();</p> <p>Return;</p> <p>}</p> <p>}</p> <p>%></p> <p></ table></p> <p></ body></p> <p></ html></p> <p>The page kill.jsp implements the destruction of the destruction of the specified session, receives a session ID parameter, acquires the corresponding session object from our saved session object collection, call the InvaliDate method, destroy the object.</p> <p><% @ page language = "java" PageEncoding = "GB2312"%></p> <p><% @ page import = "com.guipei.listener. *"%></p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><html></p> <p><HEAD></p> <p><Title> Lomboz JSP </ Title></p> <p></ hEAD></p> <p><body bgcolor = "# ffffff"></p> <p><%</p> <p>// kill the session</p> <p>Try {</p> <p>String stringsid = Request.getParameter ("sessionid");</p> <p>HttpSession session1 = sessionListener.getSession (strsid);</p> <p>IF (session1! = NULL) {</p> <p>Session1.invalidate ();</p> <p>}</p> <p>} catch (exception e) {</p> <p>E.PrintStackTrace ();</p> <p>}</p> <p>Response.sendRedirect ("session.jsp");</p> <p>%></p> <p></ body></p> <p></ html></p> <p>After completing the above code, you will also need to add the following elements in the web.xml description. Make the SessionListener class to play a listener.</p> <p><listener></p> <p><listener-class></p> <p>com.guipei.listener.SessionListener</p> <p></ listener-class></p> <p></ listener></p> <p>to sum up</p> <p>The author is not very clear, why do the servlet specification cancels the HTTPSESSIONCONTEXT interface, although it declares the reason why the cancellation is declared, but we can still easily implement this function through the HTTPSessionListener interface.</p> <p>It is hoped that this article can provide a new method that replaces the HttpSessionContext interface that has been abolished by the servlet specification. Let us easily perform session operations.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-101553.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="101553" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.031</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'YzrlX_2FQjZv7ud_2BEv_2Bm06QxfCmQYBJDdVhLIkNMZJvpjCK7qRYFL1T5f1gDt1Bed22VxmvqdR4Lj8jyQ_2FHmybJg_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>