java web项目中管理session的时候,除了在web.xml文件中设置过时时间
<session-config>
<session-timeout>2</session-timeout>
</session-config>
xxx分钟,还可以通过
HttpSessionListener
接口或HttpSessionBindingListener接口来实现对session的监控,通过监听session的新建和销毁来控制
实现HttpSessionListener接口:
package listener; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class OnlineListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent event) { System.out.println("新建session:" + event.getSession().getId()); } public void sessionDestroyed(HttpSessionEvent event) { HttpSession session = event.getSession(); ServletContext application = session.getServletContext(); // 取得登录的用户名 String username = (String) session.getAttribute("username"); // 从在线列表中删除用户名 List onlineUserList = (List) application.getAttribute("onlineUserList"); onlineUserList.remove(username); System.out.println(username+"已经退出!"); } }
后要在web.xml中配置监听接口配置:
<listener> <listener-class>listener.OnlineListener</listener-class> </listener>
当用户首次访问网站页面的时候,框架就会生成一个sessionID这时执行listener.OnlineListener.sessionCreated()方法,执行操作,不是对单个session与用户的是对整个全局的session的操作
项目其他文件代码:
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <form action="httpSessionLogin.jsp" method="get"> HttpSessionListener方式监听Session:<br/> 登陆:<input id="username" name="username"/> <input type="submit"/> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@page import="listener.OnlineListener"%> <% request.setCharacterEncoding("UTF-8"); // 取得登录的用户名 String username = request.getParameter("username"); // 把用户名保存进session System.out.println("jspsession:" + session.getId()); session.setAttribute("username", username); session.setAttribute("onlineUserList", new OnlineListener(username)); System.out.println("用户:"+username+" 登陆成功"); // 把用户名放入在线列表 List onlineUserList = (List) application.getAttribute("onlineUserList"); // 第一次使用前,需要初始化 if (onlineUserList == null) { onlineUserList = new ArrayList(); application.setAttribute("onlineUserList", onlineUserList); } onlineUserList.add(username); // 成功 response.sendRedirect("result.jsp"); %>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> 登陆成功 <h3>您好:${username} [<a href="logout.jsp">注销</a>]</h3> 当前在线用户: <table> <% List onlineUserList = (List) application.getAttribute("onlineUserList"); for (int i = 0; i < onlineUserList.size(); i++) { String onlineUsername = (String) onlineUserList.get(i); %> <tr> <td><%=onlineUsername%></td> <td><a href="deleteUser.jsp?username=<%=onlineUsername%>">删除</a></td> </tr> <% } %> </table> </body> </html>
而HttpSessionBindingListener运用时不用在web.xml中配置,HttpSessionBindingListener虽然叫做监听器,但使用方法与HttpSessionListener完全不同。我们实际看一下它是如何使用的。新建类OnlineUserBindingListener,实现HttpSessionBindingListener接口,构造方法传入username参数,HttpSessionBindingListener内有两个方法valueBound(HttpSessionBindingEvent event)和valueUnbound(HttpSessionBindingEvent event),前者为数据绑定,后者为取消绑定所谓对session进行数据绑定,就是调用session.setAttribute()把HttpSessionBindingListener保存进session中
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <form action="sessionBindingLogin.jsp" method="get"> HttpSessionBindingListener方式监听Session:<br/> 登陆:<input id="username" name="username"/> <input type="submit"/> </form> </body> </html>
sessionBindingLogin.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@page import="listener.OnlineBindingListener"%> <% request.setCharacterEncoding("UTF-8"); // 取得登录的用户名 String username = request.getParameter("username"); // 把用户名放入在线列表 session.setAttribute("onlineUserBindingListener", new OnlineBindingListener(username)); // 成功 response.sendRedirect("result.jsp"); %>
package listener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; public class OnlineBindingListener implements HttpSessionBindingListener { String username; public OnlineBindingListener(String username){ this.username=username; } public void valueBound(HttpSessionBindingEvent event) { HttpSession session = event.getSession(); System.out.println("创建Session:"+session.getId()); System.out.println("username:"+username); session.setAttribute("username", username); ServletContext application = session.getServletContext(); // 把用户名放入在线列表 List onlineUserList = (List) application.getAttribute("onlineUserList"); Map<String, HttpSession> sessionMap = (Map<String, HttpSession>)application.getAttribute("sessionMap"); // 第一次使用前,需要初始化 if (onlineUserList == null) { onlineUserList = new ArrayList(); application.setAttribute("onlineUserList", onlineUserList); } if (sessionMap == null) { sessionMap = new HashMap<String, HttpSession>(); application.setAttribute("sessionMap", sessionMap); } onlineUserList.add(this.username); sessionMap.put(username, session); } public void valueUnbound(HttpSessionBindingEvent event) { HttpSession session = event.getSession(); ServletContext application = session.getServletContext(); // 从在线列表中删除用户名 List onlineUserList = (List) application.getAttribute("onlineUserList"); onlineUserList.remove(this.username); System.out.println("Session实效:"+session.getId()); System.out.println(this.username + "退出。"); } }
deleteUser.jsp
<%@ page language="java" import="java.util.*,javax.servlet.*" pageEncoding="UTF-8"%> <% request.setCharacterEncoding("UTF-8"); // 取得登录的用户名 String username = request.getParameter("username"); System.out.println(username); Map<String, HttpSession> sessionMap = (Map<String, HttpSession>)application.getAttribute("sessionMap"); HttpSession otherSession = (HttpSession)sessionMap.get(username); //otherSession.removeAttribute("username"); otherSession.invalidate(); sessionMap.remove(username); // 成功 response.sendRedirect("result.jsp"); %>