JSP & Servlet session control

xiaoxiao2021-03-06  81

JSP & Servlet session control

Author: guipei

Foreword

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:

Component function com.guipei.listener. SessionListener listening component, complete HTTPSessionContext function index.jsp implement user login, create new session logout.jsp implement users to exit, users automatically delete session display.jsp Show user login information, after login Automatically transfer to session.jsp list all the current session kill.jsp killed 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"); strast.getParameter ("think"); if ((strname == null) || (strname.length () == 0)) {throw new exception ("null ");} if (straw == null) || (" Null Strth "); // Add session session.setttribute (" name ", strname) Session.SetaTribute ("Thing", StRTHING; Response.sendRedirect ("Display.jsp");} Catch (Exception E) {}%> Welcome </ title> </ head > <Body> <center> Welcome </ center> <form method = 'POS T '> <Table Align =' Center '> <TD> <TD> Name: </ TD> <TD> <input name =' name 'type =' input '/> </ td> </ tr> <tr > <TD> Thing: </ td> <TD> <input name = 'Thing' Type = 'Input' /></p> <p></ td> </ tr> <tr> <td align = 'Right'> </ td> <td align = 'Right'> <Button type = 'Submit'> Submit </ button> <button type = 'reset '> reset </ button> </ td> </ tr> </ table> </ form> </ body> </ html> page display.jsp For the display function after the user login, if the user has not launched Request, will automatically forward to the index.jsp page to ensure that the user logs in.</p> <p><% @ page language = "java" PageEncoding = "GB2312"%> <! doctype html public "- // w3c // DTD HTML 4.0 Transitional // EN"> <html> <head> <title> Lomboz JSP </ Title> </ head> <body bgcolor = "# ffffff"></p> <p><% IF (session.isnew () == True) {response.sendredirect ("index.jsp");} out.println ("name:" session.getattribute ("name") "<br>") Out.println ("Thing:" session.gettribute ("Thing") "<br>"); Out.Println ("session ID:" session.getID () "<br>"); OUT .println ("CREATE TIME:" session.getcreationTime ());%></p> <p></ body> </ 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"%> <! doctype html public "- // w3c // DTD HTML 4.0 Transitional // EN"> <html> <head> <title> Lomboz JSP </ Title> </ head> <body bgcolor = "# ffffff"> <% IF (session.isnew ()! = true) {session.invalidate ();} response.sendredirect ("index.jsp");%> < / body> </ html> 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"%> <% @ page import = 'com.guipei.listener. *, java.util. *'%> <! doctype html public "- // w3c / / DTD HTML 4.0 Transitional // En "> <html> <head> <title> Lomboz JSP </ Title> </ head> <body bgcolor =" # ffffff "></p> <p>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></p> <p><% Iterator itrator = sessionListener.get set (); while (item.hasnext ()) {Try {httpsession session1 = (httpsession) item.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> </ htm l> The page kill.jsp implements the function destroying the specified session, receives a session ID parameter, acquires the corresponding session object from the session object collection we save, call the InvaliDate method, destroy the object.</p> <p><% @ page language = "java" PageEncoding = "GB2312"%> <% @ page import = "com.guipei.listener. *"%> <! doctype html public "- // w3c // DTD HTML 4.0 Transitional / / en "> <html> <head> <title> Lomboz JSP </ title> </ head> <body bgcolor =" # fff "> <% // 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> </ 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-104558.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="104558" 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.040</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 = 'HFS1vvDBKBE_2B90HChj9CF8VxuRcZvN9_2FlFSW3K7SWGV3NovNFfVsS2zHsjEOxDHDMfFplhMmgbeoCC7LRGCUqw_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>