Java设置用户在一处登录,另一处就被挤掉
当用户登录时,将用户信息存入session中(前提先判断已经验证过是未登录用户,即session中无用户信息),然后通过ServletContext获取之前用户登录的信息,如果没有,就代表一个同用户登录,把新用户的信息存入servletContext中如果有,就代表在别处该用户已经登录,servletContext.removeAttribute删除用户信息,并销毁session中的信息。
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
UserLoginService service=new UserLoginServiceImpl();
String username = req.getParameter("username");
String password = req.getParameter("password");
try {
Users users = service.userLogin(username, password);
//建立客户端与服务端会话状态
HttpSession session= req.getSession();
session.setAttribute("users",users);
//控制用户只能在一处登录,获取全局共享数据
ServletContext servletContext = this.getServletContext();
HttpSession session1 = (HttpSession) servletContext.getAttribute(users.getUserid() + "");
if(session1!=null){
servletContext.removeAttribute(users.getUserid()+"");
session1.invalidate();
}
servletContext.setAttribute(users.getUserid()+"",session);
resp.sendRedirect("index.jsp");
}catch (UserNotFoundException e){
req.setAttribute("msg",e.getMessage());
req.getRequestDispatcher("login.jsp").forward(req,resp);
}catch (Exception e){
resp.sendRedirect("error.jsp");
}