异地防止重复登录
将用户的登录信息保存在Application内置作用域中,利用session监听每一个登录用户的登录情况。
用户登录成功后将用户的登录信息已键值对的形式保存在Application中,由于Application是保存在服务器端,当用户在异地登录时,将登录信息与Application中的键值对进行比较如果相同则登录失败。
如图所示为目录结构:
核心代码片段:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取表单中的username和password
String username = req.getParameter("username");
String password = req.getParameter("password");
HttpSession session = req.getSession();//初始化session
UserBean user = null;
try {
System.out.println(username + "ceshi " + password);
user = userService.login(username, password);//
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (user != null) {
//初始化Context变量
ServletContext application = session.getServletContext();
//初始化map集合
Map<String, String> loginMap = (Map<String, String>) application.getAttribute("loginMap");
if (loginMap == null) {
loginMap = new HashMap<>();
}
//
for (String key : loginMap.keySet()) {
if (user.getUsername().equals(key)) {
if (session.getId().equals(loginMap.get(key))) {
System.out.println(username + "在同一地点多次登录!");
} else {
System.out.println(username + "异地登录被拒绝!");
session.setAttribute("tip", "该用户已经异地登录!");
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
}
}
loginMap.put(user.getUsername(), session.getId());
application.setAttribute("loginMap", loginMap);
session.setAttribute("username", user.getUsername());
System.out.println("登录成功!");
resp.sendRedirect("index.jsp");
}
else {
// 登录失败
System.out.println("user is null");
session.setAttribute("tip", "登录失败!");
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
}
session监听:
public void sessionDestroyed(HttpSessionEvent event) {
//在session销毁的时候 把loginMap中保存的键值对清除
String username = event.getSession().getAttribute("username").toString();
if(username!=null){
Map<String, String> loginMap = (Map<String, String>)event.getSession().getServletContext().getAttribute("loginMap");
loginMap.remove(username);
event.getSession().getServletContext().setAttribute("loginMap",loginMap);
System.out.println(username+"用户注销!");
}
}
效果如图所示:
异地登录