最近有一个需求,不允许多个设备同时登陆一个账号,由于我还是一个初学者,对于这个需求我能想到的解决办法就是创建一个全局的map集合,用来存储用户的账号以及登陆成功时的session(这里存session是为了方便数据处理),在session中设置一个logined的属性来标识用户的登陆状态,为防止恶意篡改和用户退出后可以在其他地方登陆(从map集合中去掉登陆信息),logined属性的值设置用户的账号。
下面我添加一个用来学习的小项目:
项目采用ssm框架,maven工程,结构如下:
ssm框架的配置这里就不再赘述了,需要实现以上需求,我们需要自己写一个类继承HttpSessionListener,由于我们是要在session被销毁的同时在map集合中同样去除登陆信息,故这里需要重写HttpSessionListener的sessionDestroyed方法,在web.xml文件中对该监听进行配置。项目完整代码如下:
控制层
LoginController.java
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;@Controllerpublic 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 { ListaccountList = 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.java
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;@Controllerpublic 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"); } }
服务层:
LoginService.java
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;@Servicepublic class LoginService { @Autowired AccMapper am; public ListgetAccount(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包(工具类):
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 Mapmap=new HashMap<>(); public static Map 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中:
com.lzy.util.LoginSessionDestroyed
web.xml
ssm_lzy contextConfigLocation classpath:applicationContext.xml org.springframework.web.context.ContextLoaderListener dispatcherServlet org.springframework.web.servlet.DispatcherServlet 1 dispatcherServlet / com.lzy.util.LoginSessionDestroyed
到这里就完成了所有的编写以及配置。
结果:
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"%>login
register.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>register
success.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>">write to Sessionsuccess logining successful...
<%=request.getAttribute("username") %>
logined.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>">write to Sessionlogined logined...
<%=request.getAttribute("username") %>
fail.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>fail logining fail...
testSession.js
$.ajax({ url:"http://192.168.0.199:8080/testSession1/testSession", type:"post", error:function(){}, success:function(mess){ console.log(mess); }});
如果您看到了这篇文章,恰巧有更好的办法,不妨在下方留言?