The implementation method of Java multiuser login limit _java

Source: Internet
Author: User

Recently more idle do not have a project to do, and then smoothed down the usual work will encounter some of the common problems, the first thought of the problem of multiple user login restrictions, the following on this issue to do a little thinking to explain.

Related reading:

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

1. Design Scene

1 The same time does not allow a user to log in more than one

2 The user has logged in a, now login from B is allowed, but will be squeezed out of a (given that the user in a place after logging in because of certain circumstances ran to B, but also want to continue the work before, so need to login system)

3 B After the squeeze off a, a and other operations when the system will give a hint, the user logged in elsewhere, if not my operation may be a password leakage, please modify the password.

2, Thinking Guide map

When each user logs in, we usually save the user's information in session, so that the user can get the basic information of the user when they do the operation. However, this session is private and is visible only to the current user (if you agree that users will be given different sessions when they log in to different browsers, this is the root cause of the multiple user logins). So then the question comes, when a user log in how to know whether they are online, believe that smart you have thought, this is not good half, the online user information stored in a public place the problem is not solved, online a check, the solution is unmatched, roughly for the following two kinds of

1 Identify online users in the database

2) stored in the application

After a lot of consideration, we will find that the solution one needs to solve many difficult problems (user abnormal exit has not had time to modify the state, frequent access to the database impact performance, etc.), which for a demanding perfect you are obviously inappropriate, so we adopted the program two, The online user information is saved to the application, which is specifically designed as follows.

1) Login Flowchart

2) The Operation flow chart after being squeezed off

3, Code

  1) Login method

@RequestMapping (value = "/login", method = requestmethod.post) public String Login (string userName, string password, Redi Rectattributes redirectattributes, HttpServletRequest request) {//To determine whether the user has been online and processed (eliminated online) String Loginlimite =
Limitelogin.loginlimite (Request, userName);
Determine if the username and password are correct String result = Userservice.login (userName, password); if (Result.equals ("Success")) {request.getsession (). setattribute ("Now_user", Userservice.findbyusername (UserName)
);
Create token and verify String Jwttoken = Tokenservice.createuserauthtoken (Userservice.findbyusername (UserName));/Generate token
System.out.println (Jwttoken); Userauthenticationtoken AuthToken = Tokenservice.retrieveuserauthtoken (jwttoken);//token parsing System.out.println (
Authtoken.isauthenticated ());
SYSTEM.OUT.PRINTLN ("id =" + userauthenticationtoken.getcurrenttoken (). Getuseruuid ());
The user dropped the line and redirected to the saved link Object url = request.getsession (). getattribute ("Redirect_link"); if (URL!= null) {request.getsession (). RemoveAttribute ("Redirect_link"); return "R"Edirect: "+ url.tostring ();}
Return "index";
} redirectattributes.addflashattribute ("message", result);
return "Redirect:/other/tologin"; }

2) Logon decision is online

@Service @Transactional public class Limitelogin {private static Logger log = Logger.getlogger (Sessionlistener.class); p Rivate static map<string, string> Loginusermap = new hashmap<> ();//store online user private static map<string, Strin
g> loginouttime = new hashmap<> ();//store excludes user Time @Autowired private userservice userservice; public string Loginlimite (HttpServletRequest request, String userName) {User user = Userservice.findbyusername (userName
);
String sessionId = Request.getsession (). GetId (); For (String Key:loginUserMap.keySet ()) {//user has logged on to another key.equals (User.getusername ()) &&! Loginusermap.containsvalue (sessionId)) {log.info ("User:" + user.getusername () + ", on" + Dateutil.dateformat (new Date ()) YYYY-MM-DD HH:mm:ss ") +" was removed!
");
Loginouttime.put (User.getusername (), Dateutil.dateformat (New Date (), "Yyyy-mm-dd HH:mm:ss"));
Loginusermap.remove (User.getusername ());
Break
} loginusermap.put (User.getusername (), sessionId); Request.getsession (). Getservletcontext(). setattribute ("Loginusermap", Loginusermap);
Request.getsession (). Getservletcontext (). setattribute ("Loginouttime", loginouttime);
Return "Success"; }
}

3 Login Interceptor (not logged in to the Jump login page)

public class Logininterceptor extends Handlerinterceptoradapter {@Override public boolean prehandle (httpservletrequest
Request, HttpServletResponse response, Object handler) throws Exception {HttpSession session = Request.getsession ();
User user = (user) Session.getattribute ("Now_user");
if (Session.getattribute ("now_user") = = null) {Response.sendredirect (Request.getcontextpath () + "/other/tologin");
return false;
}//Multiuser login limit judgment, and give the prompt information Boolean islogin = false; if (user!= null) {map<string, string> Loginusermap = (map<string, string>) Session.getservletcontext (). GetA
Ttribute ("Loginusermap");
String sessionId = Session.getid (); For (String Key:loginUserMap.keySet ()) {//user has logged on to another key.equals (User.getusername ()) &&!
Loginusermap.containsvalue (sessionId)) {IsLogin = true; break;}} } if (IsLogin) {map<string, string> loginouttime = (map<string, string>) Session.getservletcontext ().
GetAttribute ("Loginouttime"); Session.setattribute ("mess", "User:" + user.getusername () + ", in" + Loginouttime.get (User.getusername ()) + "has been logged in elsewhere!");
Loginouttime.remove (User.getusername ());
Session.getservletcontext (). setattribute ("Loginusermap", loginouttime);
Response.sendredirect (Request.getcontextpath () + "/other/tologin");
return false;
return Super.prehandle (Request, response, handler);
@Override public void Posthandle (HttpServletRequest request, httpservletresponse response, Object handler, Modelandview Modelandview) throws Exception {Super.posthandle (request, response, Handler, Modelandview); @Override Pub LIC void Aftercompletion (HttpServletRequest request, httpservletresponse response, Object handler, Exception ex) throws E xception {super.aftercompletion (request, response, Handler, ex);}

  4 when the session is destroyed, the key value saved in the Loginusermap is cleared

Public Classsessionlistener implements Httpsessionlistener {
private static Logger log = Logger.getlogger ( Sessionlistener.class);
@Override public
void sessioncreated (Httpsessionevent event) {
}
@Override public
Void Sessiondestroyed (Httpsessionevent event) {
HttpSession session = Event.getsession ();
String sessionId = Session.getid ();
When the session is destroyed, the key value saved in the Loginusermap is purged of the
user user = (user) Session.getattribute ("Now_user");
if (user!= null) {
map<string, string> loginusermap = (map<string, string>) event.getsession (). Getservletcontext (). getattribute ("Loginusermap");
if (Loginusermap.get (User.getusername ()). Equals (SessionId)) {
log.info ("Clean User from Application:" + User.getusername ());
Loginusermap.remove (User.getusername ());
Event.getsession (). Getservletcontext (). setattribute ("Loginusermap", Loginusermap);}}}

 5) Web.xml

<!--session Listener multiple User login restrictions, quit clearing session information while clearing application store user login information-->
<listener>
< Listener-class>com.service.limitelogin.sessionlistener</listener-class>
</listener>

  6 page code (used to give the prompt, the elimination of the user's session information is squeezed out, otherwise the message will always be displayed)

<script type= "Text/javascript" >
$ (document). Ready (function () {
var message= ' ${mess} ';
if (Message!= "") {
$.ajax ({
type: ' Get ',
async:false,
cache:false,
URL: '/other/ Clearusersession ',
dataType: ',
data: {},
success:function (data) {
}
});
$ (' #mess '). HTML (message);
}
);
</script>

7) Clear the user session code to squeeze out

/**
* Multiple User login restrictions, clear session information (login information, tips) *
*
@param request
* * @return
/
@ResponseBody
@ Requestmapping (value = "/clearusersession") public
String clearusersession (httpservletrequest request) {
HttpSession HttpSession = Request.getsession ();
Httpsession.invalidate ();
Httpsession.removeattribute ("Now_user");
Httpsession.removeattribute ("mess");
Return "Success";
}

To do this development work

4. Operation result

The above is a small set to introduce Java multiuser login restrictions to achieve the method, 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!

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.