Similar to the QQ login function, the account has been logged on in one place, and the previous login will be squeezed out during another login.
Principles:
It mainly processes user logon in servlet. servlet maintains the relationship between user and sessionid and the relationship between user and session, and stores them in two maps, when a user logs on, a new record is added to the map. If
If the user already exists in the map, the corresponding records of the user will be deleted. Note that the records in the map will be deleted rather than the session will be destroyed, in this session, add the prompt information to the user, and then set the information of the new user.
Put in map. On the page, you need to constantly verify whether there are any prompts in the session. If yes, it indicates that the session has been squeezed out. Note that the attribute in the session obtained in JSP will not be automatically updated, also
That is to say, if the page is not refreshed, even if the servlet has put a prompt message to the user's session, the page will not get it, therefore, we need to use ajax to continuously send requests to the server to obtain
The user prompt information in the session is dynamic. Once a prompt is found in the session, a prompt is displayed.
Project Structure:
Web. xml
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>LoginPush</display-name> <listener><listener-class>cn.com.hafx.LoginServlet</listener-class> </listener> <servlet> <servlet-name>login</servlet-name> <servlet-class>cn.com.hafx.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/login.do</url-pattern> <url-pattern>/reLogin.do</url-pattern> <url-pattern>/getUserMsg.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app>
Loginservlet. Java
Import Java. io. ioexception; import Java. io. printwriter; import Java. util. hashmap; import Java. util. map; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import javax. servlet. HTTP. httpsession; import javax. servlet. HTTP. httpsessionevent; import javax. servlet. HTTP. httpsessionlistener; import Org. apache. commons. logging. log; import Org. apache. commons. logging. logfactory; /***** @ author lyh * @ version 2013-4-11 * @ see loginservlet * @ since */public class loginservlet extends httpservlet implements httpsessionlistener {/*** serial number */Private Static final long serialversionuid =-2080934157550504694l; /*** log */Private Static log = logfactory. getlog (loginservlet. class);/*** bind the user and session Fixed relationship */public static final map <string, httpsession> user_session = new hashmap <string, httpsession> (); /*** seeionid and user binding relationship */public static final map <string, string> sessionid_user = new hashmap <string, string> (); /*** implement the httpsessionlistener interface to listen to the session creation event */@ override public void sessioncreated (httpsessionevent SE) {string sessionid = Se. getsession (). GETID (); log.info ("create session sessionid = "+ Sessionid);}/*** implement the httpsessionlistener interface to listen to the session destruction event */@ override public void sessiondestroyed (httpsessionevent SE) {string sessionid = Se. getsession (). GETID (); // Delete the user information bound to the current session when the current session is destroyed // Delete the httpsession user_session.remove (sessionid_user.remove (sessionid) of the user bound to the current session simultaneously )); log.info ("Destroy session sessionid =" + sessionid);}/*** User Logon */@ override protected void Service (httpserv Letrequest request, httpservletresponse response) throws servletexception, ioexception {// GET Request command request. setcharacterencoding ("UTF-8"); string servletpath = request. getservletpath (); string uri = servletpath. substring (1, servletpath. lastindexof (". do "); try {// Log On if (" login ". equals (URI) {httpsession session = request. getsession (); string username = request. getparameter ("username"); string pass WORD = request. getparameter ("password"); If (username! = NULL &&! "". Equals (username. trim () {// login successful if (LOGIN (username, password) {// Process User Logon (keep the same account at the same time only one login) userloginhandle (request); // Add user_session.put (username. trim (), session); // Add the sessionid and the user's bound sessionid_user.put (Session. GETID (), username); log.info ("User [" + username + "] online... "); Session. setattribute ("username", username); Session. removeattribute ("usermsg"); // redirect to the home page response. sendr Edirect ("Main. JSP ");} // Logon Failed else {log.info (" User ["+ username +"] logon failed... "); Request. setattribute ("MSG", "Logon Failed. Please log on again! "); // Response. sendredirect ("login. JSP "); Request. getrequestdispatcher ("login. JSP "). forward (request, response) ;}} else {log.info ("User [" + username + "] logon failed... "); Request. setattribute ("MSG", "Logon Failed. Please log on again! "); // Response. sendredirect ("login. JSP "); Request. getrequestdispatcher ("login. JSP "). forward (request, response) ;}// log on to else if ("relogin ". equals (URI) {httpsession session = request. getsession (); string username = (string) session. getattribute ("username"); If (session! = NULL) {// destroy the relevant session // user_session.remove (sessionid_user.remove (session. GETID (); Session. invalidate ();} If (username! = NULL &&! "". Equals (username) {log.info ("User [" + username + "] offline... ");} // redirect to the logon page response. sendredirect ("login. JSP ");} // Ajax validation else if (" getusermsg ". equals (URI) {httpsession session = request. getsession (); response. setcontenttype ("text/html"); response. setcharacterencoding ("UTF-8"); printwriter out = response. getwriter (); out. print (Session. getattribute ("usermsg");} catch (exception e) {log. erro R (E. getclass () + E. getmessage (); printwriter out = response. getwriter (); Out. Print ("Internal Server Error! ") ;}}/***** Description: processing of user logon <br> * @ Param Request * @ see */private void userloginhandle (httpservletrequest request) {// string username = request. getparameter ("username"); // The current sessionid // string sessionid = request. getsession (). GETID (); // Delete the user bound to the current sessionid, user -- httpsession // user_session.remove (sessionid_user.remove (sessionid); // Delete the httpsession session = user bound to the current logon user _ Session. Remove (username); If (session! = NULL) {// delete user sessionid_user.remove (Session. GETID (); Session. removeattribute ("username"); Session. setattribute ("usermsg", "Your account has logged on from another location, and you are forced to go offline! ") ;}}/***** Description: simulate dB login judgment <br> * @ Param username user * @ Param Password * @ return * @ see */private Boolean login (string username, string password) {return ("lyh ". equals (username) & "123456 ". equals (password ));}}
Login. jsp
<% @ Page Language = "Java" contenttype = "text/html; charset = UTF-8" pageencoding = "UTF-8" %> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML>
Main. jsp
<% @ Page Language = "Java" contenttype = "text/html; charset = UTF-8" pageencoding = "UTF-8" %> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML>