JavaWeb之实现账号强制下线功能
【摘要】 准备工具:IntelliJ IDEA 2019.2.3 x64 apache-tomcat-8.5.15实现账号踢出功能解释:账号踢出指一个账号在A处已登录,如果在B处再次登录该账号时,则使得A处的账号自动退出。login.jsp<%-- Created by IntelliJ IDEA. User: admin Date: 2020/11/11 Time: 15:11 To ch...
准备工具:
IntelliJ IDEA 2019.2.3 x64
apache-tomcat-8.5.15
实现账号踢出功能
解释:账号踢出指一个账号在A处已登录,如果在B处再次登录该账号时,则使得A处的账号自动退出。
login.jsp
<%-- Created by IntelliJ IDEA. User: admin Date: 2020/11/11 Time: 15:11 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录</title> </head> <body> <form action="login" method="post"> <input name="name"><br> <input type="password" name="password"><br> <input type="checkbox" name="check" value="1">7天免登录 <input type="submit" value="登录"> </form> </body> </html>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title></title> </head> <body> 欢迎你,${user} </body> </html>
LoginServlet.java
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet("/login") public class LoginServlet extends HttpServlet { private Map<String, HttpSession> sessions = new HashMap<>(); //存放所有登录成功的session对象 @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getParameter("name"); String password = req.getParameter("password"); String check = req.getParameter("check"); if ("root".equals(name) && "root".equals(password)) { //如果账号已登录,则让前一个账号的session过期 if (sessions.containsKey(name)) { HttpSession httpSession = sessions.get(name); httpSession.setMaxInactiveInterval(1); //让上一次登录的session失效 sessions.remove(httpSession); //从列表中移除 } sessions.put(name, req.getSession()); //将当前session加入集合中 req.getSession().setAttribute("user", name); resp.sendRedirect("index.jsp"); }else { req.setAttribute("msg", "用户名或密码错误"); req.getRequestDispatcher("login.jsp").forward(req, resp); } } }
代码都有注释的,简单实现一个账号剔除功能,就是让上一个session失效
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)