A perfect solution for Java web development to prevent multiple users from repeatedly logging in _java

Source: Internet
Author: User
Tags getmessage java web log4j

In the current Web project, there are many situations where the same account information can be logged in at different login entries this time, this is not so good.

Recommended reading:

Implementation method of Java multiuser login limit

There are two kinds of solutions now:

1, the user's login information with a flag bit of the field to save, each login success on the Mark 1, logout sign for 0, when marked 1 when not allowed to log in.

2, the user's login information stored in the application built-in scope, and then use the session listener to monitor the logon situation of each logged-on user.

Obviously, the first way to log in every time need to operate the database, a number of unnecessary performance overhead, and in the event of a sudden computer shutdown, it will never log on, the availability is relatively low.

But the second way is different, the operability is strong, it is easy to maintain the information of all online users.

The following is mainly about the implementation of the second approach:

1, in processing logins login method, first query the database to verify the existence of the user, if there is a decision to determine whether the login account has been locked, and then remove all the login information from the application built-in scope object to see if the username account has been logged in, if the login , on a friendly note, the contrary means that you can log in, and the login information is stored as a key-value pair in the application.

The code is as follows:

404 @Action (value= "Login", results={@Result (name= "index", location= "index.jsp"), if the method of each access is not used before using 0 configuration, or @action. Public String Login () throws Exception {try{User result = Userservice.login (User.getfuusername (), User.getfupassword 
()); if (result!=null) {if (Result.getfustatus ()!=null && result.getfustatus () ==0) {super.setrequestattr ( Constant.message, "Sorry, the user has been locked!" 
"); 
return "error"; } map<string, string> loginusermap = (map<string, string>) super.getapplicationattr (Constant.LOGIN_USER_ 
MAP); 
Boolean isexist = false; 
String sessionId = Super.getsessionid (false); 
if (loginusermap==null) {loginusermap = new hashmap<string, string> (); For (String Username:loginUserMap.keySet ()) {//To determine if the logged in user's information has been saved or if the same user is logged on repeatedly, allow login if (!username.equals) . Getfuusername ()) | | 
Loginusermap.containsvalue (SessionId)) {continue; 
} isexist = true; 
Break } if (isexist) {super.setrequestattr (constant.message, "Sorry, the user is logged in!") 
"); 
return "error"; }else {loginusermap.put (Result.getfuusername (), sessionId); 
}//Login successful super.setsessionattr (constant.login_user, result); 
Super.setapplicationattr (Constant.login_user_map, Loginusermap); Logger.info (Result.getfuusername () + "Login successful!" 
"); 
If a value is Fromurl in the session, jump to the page string fromurl = (string) super.getsessionattr (Constant.from_url); 
if (fromurl!=null) {super.setsessionattr (constant.from_url, NULL); 
Super.getresponse (). Sendredirect (Fromurl.tostring ()); 
return null; 
Return "index"; 
} catch (Exception e) {e.printstacktrace (); 
Logger.info ("Login failed:" +e.getmessage ()); 
} super.setrequestattr ("Message", "Username or password error"); 
return "error"; }

2, login after processing, consider the end of the session, then the corresponding login users should also log in accordingly. We can write a session listener, listening to the destruction of Sessioon, we will log off the user, that is, from the application to remove. Indicates that the user has been offline.

The code is as follows:

Package com.facelook.util; 
Import Java.util.Map; 
Import javax.servlet.http.HttpSessionEvent; 
Import Javax.servlet.http.HttpSessionListener; 
Import Org.apache.log4j.Logger; 
Import Com.facelook.entity.User; 
public class Sessionlistener implements httpsessionlistener{ 
private Logger Logger = Logger.getlogger ( This.getclass ()); 
@Override public 
void sessioncreated (Httpsessionevent event) { 
} 
@Override public 
Void Sessiondestroyed (Httpsessionevent event) { 
//to purge the 
user user = (user) of the key value saved in Loginusermap when session is destroyed) Event.getsession (). getattribute ("Loginuser"); 
if (user!=null) { 
map<string, string> loginusermap = (map<string, string>) event.getsession (). Getservletcontext (). getattribute ("Loginusermap"); 
Loginusermap.remove (User.getfuusername ()); 
Event.getsession (). Getservletcontext (). setattribute ("Loginusermap", Loginusermap);}} 

The Web.xml is configured as follows:

<!--session listener--> 
<listener> 
<listener-class>com.facelook.util.sessionlistener </listener-class> 
</listener>

3, in addition, there is a problem, if the user suddenly closed the browser or page without clicking the Exit button. You can then use the Beforeunload event to trigger when the browser is refreshed or closed.

Event $ (window) that is invoked when it is refreshed or closed 
. bind (' Beforeunload ', function () { 
$.ajax ({ 
URL: "${ctx}/system/user/user! Logout.action ", 
type:" Post ", 
success:function () { 
alert (" You have logged out "); 
} 
) 
;

But if some objective reason, such as computer suddenly shutdown, automatic restart, and so on, these can not be avoided, so only wait for server-side session sessions to reset before the login.

Unless you are a module that counts all online personnel, the administrator can log in the status management of the online personnel, and destroy the users who have problems.

Next, briefly introduce the management of the online personnel module:

1, the first need a session listener to listen to all the answer to create the situation, this time to create a session can be count+1, and then destroy the time count-1, In addition, a ServletContext listener is needed to monitor the life cycle of the Web application, get the ServletContext object, and then count the total number of online personnel to store it.

The specific code is as follows:

Package com.facelook.util; 
Import Java.util.Map; 
Import Javax.servlet.ServletContext; 
Import javax.servlet.ServletContextEvent; 
Import Javax.servlet.ServletContextListener; 
Import javax.servlet.http.HttpSessionEvent; 
Import Javax.servlet.http.HttpSessionListener; 
Import Org.apache.log4j.Logger; 
Import Com.facelook.entity.User; 
public class Sessionlistener implements httpsessionlistener,servletcontextlistener{private int count; 
Private ServletContext ServletContext = null; 
Public Sessionlistener () {count = 0; 
Private Logger Logger = Logger.getlogger (This.getclass ()); 
@Override public void sessioncreated (Httpsessionevent event) {count++; 
SetContext (event); 
Logger.info ("***************the http session is created...***************"); @Override public void sessiondestroyed (Httpsessionevent event) {//To purge the user user of the key value saved in Loginusermap when session is destroyed 
(User) Event.getsession (). getattribute ("Loginuser"); if (user!=null) {map<string, string> Loginusermap =(Map<string, string>) event.getsession (). Getservletcontext (). getattribute ("Loginusermap"); 
Loginusermap.remove (User.getfuusername ()); 
Event.getsession (). Getservletcontext (). setattribute ("Loginusermap", Loginusermap); 
} count--; 
SetContext (event); 
Logger.info ("***************the http session is destroyed...***************"); public void SetContext (Httpsessionevent httpsessionevent) {httpsessionevent.getsession (). Getservletcontext (). 
SetAttribute ("online", count); 
@Override public void contextdestroyed (Servletcontextevent servletcontextevent) {this.servletcontext = null; 
Logger.info ("***************the servlet context is destroyed...***************"); @Override public void contextinitialized (Servletcontextevent servletcontextevent) {this.servletcontext = Servletcont 
Extevent.getservletcontext (); 
Logger.info ("***************the servlet context is initialized...***************"); } 
}

2, creating a method for managing the online user's modules in Useraction, and supporting the ability to force exits;

/** * Exit Login * @return * @throws servletexception * @throws ioexception/Public String logout () throws Servletexcept Ion, ioexception{try {map<string, string> Loginusermap = (map<string, string>) super.getapplicationattr (Co Nstant. 
LOGIN_USER_MAP); 
User user = (user) super.getsessionattr (constant.login_user); 
Super.removeattribute (CONSTANT.LOGIN_USER_MAP); 
Loginusermap.remove (User.getfuusername ()); 
Super.setapplicationattr (CONSTANT.LOGIN_USER_MAP,LOGINUSERMAP); Logger.info ("Exit login successful!") 
"); 
catch (Exception e) {e.printstacktrace (); 
Logger.error ("Exit Login failed:" +e.getmessage ()); 
} return INPUT; 
/** * Online User management * @return/public String Loginmanager () {return SUCCESS; /** * Force exit Other User * @return/public String Logoutother () {try {string username = Servletactioncontext.getrequest ( 
). GetParameter ("username"); map<string, string> Loginusermap = (map<string, string>) super.getapplicationattr (Constant.LOGIN_USER_ 
MAP); if (Username!=null &AMP;&Amp 
Loginusermap.containskey (username)) {loginusermap.remove (username); 
Super.setapplicationattr (Constant.login_user_map, Loginusermap); 
} catch (Exception e) {e.printstacktrace (); 
Logger.info ("Force exit Failure:" +e.getmessage ()); 
return null; }

3, in the Management page load online users list;

After the corresponding method is defined, add the online list to the corresponding administration page, as follows:

<% @page import= "Java.util.Map"%> <% @page import= "java.util.Map.Entry"%> <%@ page language= "Java" pageencoding= "UTF-8"%> <%@ include file= "/common/taglib.jsp"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">  

All right, start the deployment project, then start the service, enter the online user Management module, the simple effect of the following figure:

It should be noted that the current logged-on user does not allow you to force out of your logon information.

This way, basically can prevent multiple user login case!

The above is a small series to introduce the Java Web development to prevent multiple users to repeat the perfect solution to login, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.