最近有一个需求,不容许多个设备同时登录一个帐号,因为我仍是一个初学者,对于这个需求我能想到的解决办法就是建立一个全局的map集合,用来存储用户的帐号以及登录成功时的session(这里存session是为了方便数据处理),在session中设置一个logined的属性来标识用户的登录状态,为防止恶意篡改和用户退出后能够在其余地方登录(从map集合中去掉登录信息),logined属性的值设置用户的帐号。javascript
下面我添加一个用来学习的小项目:css
项目采用ssm框架,maven工程,结构以下:html
ssm框架的配置这里就再也不赘述了,须要实现以上需求,咱们须要本身写一个类继承HttpSessionListener,因为咱们是要在session被销毁的同时在map集合中一样去除登录信息,故这里须要重写HttpSessionListener的sessionDestroyed方法,在web.xml文件中对该监听进行配置。项目完整代码以下:java
控制层jquery
LoginController.javaweb
package com.lzy.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.lzy.bean.Acc; import com.lzy.service.LoginService; import com.lzy.util.LoginMap; @Controller public class LoginController { @Autowired LoginService ls; @RequestMapping("/login") public ModelAndView RSLogin() { ModelAndView mav=new ModelAndView(); mav.setViewName("login"); return mav; } @RequestMapping("/logining") public ModelAndView logining( @RequestParam(value="username",defaultValue="1") String username, @RequestParam(value="password",defaultValue="1") String password, HttpServletRequest req ) { System.out.println(username+" "+password+" "); ModelAndView mav=new ModelAndView(); if(LoginMap.isExist(username)) { System.out.println(username+"已登录..."); System.out.println(LoginMap.getMessHttpSession(username).getId()); mav.setViewName("logined"); mav.addObject("username", username); }else { List<Acc> accountList = ls.getAccount(username,password); if(accountList!=null&&!accountList.isEmpty()) { req.getSession().setAttribute("logined", username); LoginMap.setMess(username,req.getSession()); System.out.println(LoginMap.getMessHttpSession(username).getAttribute("logined")); mav.setViewName("success"); mav.addObject("username",username); }else { mav.setViewName("register"); } } return mav; } @RequestMapping("/register1") public ModelAndView register( @RequestParam("username") String username, @RequestParam("password") String password ) { Acc acc=new Acc(); acc.setUsername(username); acc.setPassword(password); int num = ls.insertAccount(acc); System.out.println(num); ModelAndView mav=new ModelAndView(); if(num>0) { mav.setViewName("login"); }else { mav.setViewName("register"); } return mav; } @ResponseBody @RequestMapping("/quit") public String quit(HttpServletRequest req) { if(req.getSession(false).getAttribute("logined")!=null) { String username = (String)req.getSession(false).getAttribute("logined"); LoginMap.remove(username); req.getSession(false).invalidate(); return "invaliate successful..."; }else { return "this session not found..."; } } @ResponseBody @RequestMapping("/writeToSession") public String testSession(@RequestParam("username") String username) { System.out.println(username); LoginMap.getMessHttpSession(username).setAttribute("writed", "my word..."); return (String)LoginMap.getMessHttpSession(username).getAttribute("writed"); } }
test请求控制(只是用来比较值观的观察数据是否插入完成的,无关紧要)Test1.javaajax
package com.lzy.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.lzy.util.LoginMap; @Controller public class Test1 { @ResponseBody @RequestMapping("/test") public String Test( @RequestParam("username") String username, HttpServletRequest req ) { return (String)LoginMap.getMessHttpSession(username).getAttribute("logined") +" "+ LoginMap.getMessHttpSession(username).getAttribute("writed"); } }
服务层:spring
LoginService.javabootstrap
package com.lzy.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.lzy.bean.Acc; import com.lzy.bean.AccExample; import com.lzy.bean.AccExample.Criteria; import com.lzy.dao.AccMapper; @Service public class LoginService { @Autowired AccMapper am; public List<Acc> getAccount(String username, String password) { AccExample example=new AccExample(); Criteria ec = example.createCriteria(); ec.andUsernameEqualTo(username); ec.andPasswordEqualTo(password); return am.selectByExample(example); } public int insertAccount(Acc record) { return am.insertSelective(record); } }
util包(工具类):session
LoginMap.java
建立全局map集合存储用户登录信息,提供了一些简单的获取session(getMessHttpSession()),添加键值对到map集合(setMess()),经过用户名从map集合里移除该键值对(remove()),根据用户名判断map集合中用户是否存在(isExist())几个经常使用的方法。
package com.lzy.util; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; public class LoginMap { private static Map<String, HttpSession> map=new HashMap<>(); public static Map<String, HttpSession> getMap() { return map; } public static HttpSession getMessHttpSession(String username) { return map.get(username); } public static void setMess(String username,HttpSession httpSession) { map.put(username, httpSession); } public static boolean remove(String username) { HttpSession judge = map.get(username); if(judge!=null) { return map.remove(username, judge); } return true; } public static boolean isExist(String username) { if(map.get(username)!=null) { return true; } return false; } }
LoginSessionDestroyed.java
重写destroyed方法后的类
package com.lzy.util; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** * * @author admin * session listener,we need delete this session message from LoginMap when this session destroyed * we override sessionDestroyed method */ public class LoginSessionDestroyed implements HttpSessionListener{ @Override public void sessionCreated(HttpSessionEvent se) { } @Override public void sessionDestroyed(HttpSessionEvent se) { HttpSession session = se.getSession(); System.out.println("Destroyed:"+session.getId()); System.out.println("Destroyed:"+session.getAttribute("logined")); System.out.println("Destroyed:"+LoginMap.getMap().size()); System.out.println("Destroyed:"+LoginMap.remove((String)session.getAttribute("logined"))); System.out.println("Destroyed-:"+LoginMap.getMap().size()); System.out.println("Destroyed-:"+session.getId()); } }
把下面这段代码放到web.xml中:
<!-- session listener,we need delete this session message from LoginMap when this session destroyed --> <listener> <listener-class>com.lzy.util.LoginSessionDestroyed</listener-class> </listener>
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" 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>ssm_lzy</display-name> <!-- 启动spring的容器 --> <!-- needed for ContextLoaderListener --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- springmvc --> <!-- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- session listener,we need delete this session message from LoginMap when this session destroyed --> <listener> <listener-class>com.lzy.util.LoginSessionDestroyed</listener-class> </listener> </web-app>
到这里就完成了全部的编写以及配置。
结果:
aaa 123
aaa
test:aaa
test:null
aaa 123
aaa已登录...
1B121BDC2695FAE387A37C74250D119D
Destroyed:1B121BDC2695FAE387A37C74250D119D
Destroyed:aaa
Destroyed:0
Destroyed:true
Destroyed-:0
Destroyed-:1B121BDC2695FAE387A37C74250D119D
aaa 123
aaa
aaa 123
aaa已登录...
DE36495191F6922262AF6F3597EC3162
test:aaa
test:null
test:aaa
test:null
aaa 123
aaa已登录...
DE36495191F6922262AF6F3597EC3162
aaa
test:aaa
test:my word...
Destroyed:DE36495191F6922262AF6F3597EC3162
Destroyed:aaa
Destroyed:0
Destroyed:true
Destroyed-:0
Destroyed-:DE36495191F6922262AF6F3597EC3162
aaa 123
aaa
test:aaa
test:null
aaa 123
aaa已登录...
0B97575FDF99060F32DDD0C03F2AB377
aaa
aaa 123
aaa已登录...
0B97575FDF99060F32DDD0C03F2AB377
test:aaa
test:my word...
aaa 123
aaa已登录...
0B97575FDF99060F32DDD0C03F2AB377
bbb 123
1
bbb 123
bbb
test:bbb
test:null
bbb
Destroyed:0B97575FDF99060F32DDD0C03F2AB377
Destroyed:aaa
Destroyed:1
Destroyed:true
Destroyed-:1
Destroyed-:0B97575FDF99060F32DDD0C03F2AB377
Destroyed:3191C4C94610844DE7796E681C6B4BC9
Destroyed:bbb
Destroyed:0
Destroyed:true
Destroyed-:0
Destroyed-:3191C4C94610844DE7796E681C6B4BC9
最后再贴如下前台代码吧:
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> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>login</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="static/css/bootstrap.css"> <link rel="stylesheet" href="static/css/login.css"> <script src="static/js/jquery-3.2.1.js"></script> <script type="text/javascript"> var setHUN=function(obj){ $("#hiddUsername").val($(obj).val()); } </script> </head> <body> <form action="http://192.168.0.199:8080/testSession1/logining" method="post"> <span>username:</span><input type="text" id="username" name="username" oninput="setHUN(this)"><br> <span>password:</span><input type="password" name="password"><br> <input type="submit" value="login"> </form> <br> <form action="http://192.168.0.199:8080/testSession1/quit" method="post"> <input type="text" id="hiddUsername" name="username"> <input type="submit" id="quit" value="quit"> </form> <script src="static/js/bootstrap.js"></script> <script src="static/js/login.js"></script> <!-- 重用,退出功能 --> <script src="static/js/quit.js"></script> </body> </html>
register.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> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>register</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="static/css/bootstrap.css"> <link rel="stylesheet" href="static/css/login.css"> </head> <body> <form action="http://192.168.0.199:8080/testSession1/register1" method="post"> <span>username:</span><input type="text" name="username"><br> <span>password:</span><input type="password" name="password"><br> <input type="submit" value="register"> </form> <br> <input type="button" id="quit" value="quit"> <script src="static/js/jquery-3.2.1.js"></script> <script src="static/js/bootstrap.js"></script> <!-- 重用,退出功能 --> <script src="static/js/quit.js"></script> </body> </html>
success.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> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>success</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="static/css/bootstrap.css"> </head> <body> <h1>logining successful...</h1> <p><%=request.getAttribute("username") %></p> <form action="http://192.168.0.199:8080/testSession1/test" method="post"> <input type="hidden" name="username" value=<%=request.getAttribute("username") %>> <input type="submit" value="test"> </form> <a href="http://192.168.0.199:8080/testSession1/writeToSession?username=<%=request.getAttribute("username") %>">write to Session</a> </body> </html>
logined.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> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>logined</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="static/css/bootstrap.css"> </head> <body> <h1>logined...</h1> <p><%=request.getAttribute("username") %></p> <form action="http://192.168.0.199:8080/testSession1/test" method="post"> <input type="hidden" name="username" value=<%=request.getAttribute("username") %>> <input type="submit" value="test"> </form> <a href="http://192.168.0.199:8080/testSession1/writeToSession?username=<%=request.getAttribute("username") %>">write to Session</a> </body> </html>
fail.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> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>fail</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="static/css/bootstrap.css"> </head> <body> <h1>logining fail...</h1> </body> </html>
testSession.js
$.ajax({ url:"http://192.168.0.199:8080/testSession1/testSession", type:"post", error:function(){}, success:function(mess){ console.log(mess); } });
若是您看到了这篇文章,恰巧有更好的办法,不妨在下方留言👀