思路:使用session的监听器
参拷:http://xace.iteye.com/blog/424250
监听器类
package com.chinacache.utils; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import com.chinacache.entity.User; public class OnLineUtil implements HttpSessionListener, HttpSessionAttributeListener, ServletContextListener { private ServletContext application = null; private Map<String, User> allUser = null; @Override /** * session 创建时会调用这个方法 */ public void sessionCreated(HttpSessionEvent se) { allUser = (Map<String, User>) application.getAttribute("userMap"); String sessionId = se.getSession().getId(); if (allUser.get(sessionId) == null) { allUser.put(sessionId, null); } } @Override /** * 调用session.invalidate()时被调用 */ public void sessionDestroyed(HttpSessionEvent se) { String sessionId = se.getSession().getId(); if (allUser != null && allUser.get(sessionId) != null) { allUser.remove(sessionId); } } @Override /** * 应用启动时调用 */ public void contextInitialized(ServletContextEvent sce) { application = sce.getServletContext(); application.setAttribute("userMap", new HashMap<String, User>()); } @Override public void contextDestroyed(ServletContextEvent sce) { // TODO Auto-generated method stub } @Override /** * session 中属性被增回时 */ public void attributeAdded(HttpSessionBindingEvent se) { String sessionId = se.getSession().getId(); if (allUser != null) { User user = (User) se.getSession().getAttribute("currUser"); if (user.getUser_name() != null) { allUser.put(sessionId, user); } } } @Override public void attributeRemoved(HttpSessionBindingEvent se) { // TODO Auto-generated method stub } @Override /** * session 中属性更改时 */ public void attributeReplaced(HttpSessionBindingEvent se) { HttpSession session = se.getSession(); String id = session.getId(); if (allUser != null) { User user = (User) session.getAttribute("currUser"); if (user.getUser_name() != null) { allUser.put(id, user); } } } }
web.xml
<listener> <listener-class>com.chinacache.utils.OnLineUtil</listener-class> </listener>
jsp展示(使用了ztree)
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page import="java.util.*"%> <%@ page import="com.chinacache.entity.User"%> <%@ taglib prefix="s" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="${projectPath}/resources/ztree/zTreeStyle/zTreeStyle.css" type="text/css"> <script type="text/javascript" src="${projectPath}/resources/ztree/jquery.ztree.core-3.5.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Welcome to Starscream!</title> </head> <body> <div class="container"> <div class="zTreeDemoBackground left"> <ul id="treeDemo" class="ztree"></ul> </div> </div> </body> <SCRIPT type="text/javascript"> var zNodes =<% Map<String, User> l = (Map<String, User>)application.getAttribute("userMap"); Map<String,List<String>> users=new HashMap<String,List<String>>(); for(String id : l.keySet()){ String cgf=l.get(id).getCfg_value(); String username=l.get(id).getUser_name(); if(users.get(cgf)==null){ users.put(cgf, new ArrayList<String>()); } users.get(cgf).add(username); } StringBuilder node= new StringBuilder("[{ name:'在线人员(").append(l.size()).append("人)'"); if(users.size()>0){ node.append(", open:true"); node.append(", children: ["); for(String cgf:users.keySet()){ List<String> usernames= users.get(cgf); node.append(String.format("{ name:'%s(%s人)',",cgf,usernames.size())); if(usernames.size()>0){ node.append("children: ["); for(String name:usernames){ node.append("{ name:'").append(name).append("'},"); } node.deleteCharAt(node.length()-1); }else{ node.append(", isParent:true"); } node.append("]},"); } node.deleteCharAt(node.length() - 1); node.append("]"); } else { node.append(", isParent:true"); } node.append("}]"); out.println(node.toString()); %>; var setting = { }; $(document).ready(function(){ $.fn.zTree.init($("#treeDemo"), setting, zNodes); }); </SCRIPT> </html>
LoginController.java
package com.chinacache.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import com.chinacache.entity.User; @Controller @SessionAttributes({ "currUser", "projectPath", "funcMap" }) public class LoginController { private static Logger logger = Logger.getLogger(LoginController.class); @RequestMapping("/") public String showLoginPage(Model model) { logger.info("showLoginPage is call!"); return "login"; } @RequestMapping(value = "/user", method = RequestMethod.POST) public String userLogin(@RequestParam(value = "user", required = false) User user, HttpServletRequest request, Model model) { model.addAttribute("currUser", user); return "forward:/home"; } @RequestMapping(value = "/logout") public String LogOut(HttpServletRequest request,Model model){ HttpSession session = request.getSession(); if(session!=null){ model.addAttribute("currUser",new User()); session.removeAttribute("currUser"); session.invalidate(); } return "login"; } }
由于使用@SessionAttributes把model里的属性赋值给session中,在调用LogOut后跳到login页(此时model里还存放着user信息,会自动赋给新session),所以把model里的值User赋值空user,在判断当前session中的user中的属性(如username)是否为null,如果为null表示还没有登入即不会放到在线列表中
转的:http://xace.iteye.com/blog/424250
javax.servlet.http.HttpSession 这个类是很常用的,每当我们浏览网站,不论有没有登陆,都会产生1个session,它记录了和浏览者相关的数据;
下面介绍session的2个监听器接口:
1)javax.servlet.http.HttpSessionBindingListener;
实现这个接口的类,每当被存放到session或从session中移除都会出发接口中相应的方法,从而实现监听的效果;
2)javax.servlet.http.HttpSessionListener;
实现这个接口的类,本身就是1个监听器,每当有session生成或消亡时,都触发接口中相应的方法,从而实现监听器的效果;
HttpSessionListener 的实现类本身就是一个监听器,要使用它需要在 web.xml 中启动这个监听器,例如
- <listener>
- <listener-class>packname.classname</listener-class>
- </listener>
3)这2个监听器是有区别的
前者的触发取决于 session 中加入的属性;
后者的触发取决于 session 本身的产生和消亡;
与shangshu 之类似的还有
对ServletContext的监听和对Request监听
应用:当前在线人数列表
在线人数列表是对所有人起作用,数据应放到application中。即ServletContext对象
OnLineDemo.java
- package demo;
- import java.util.ArrayList;
- import java.util.List;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletContextEvent;
- import javax.servlet.ServletContextListener;
- import javax.servlet.http.HttpSessionAttributeListener;
- import javax.servlet.http.HttpSessionBindingEvent;
- import javax.servlet.http.HttpSessionEvent;
- import javax.servlet.http.HttpSessionListener;
- /*
- * <listener> <listener-class>demo.OnLineDemo</listener-class>
- * </listener>
- */
- public class OnlineDemo implements ServletContextListener, HttpSessionListener,
- HttpSessionAttributeListener {
- // 声明一个ServletContext对象
- private ServletContext application = null;
- public void contextInitialized(ServletContextEvent sce) {
- // 容器初始化时,向application中存放一个空的容器
- this.application = sce.getServletContext();
- this.application.setAttribute("alluser", new ArrayList());
- }
- public void contextDestroyed(ServletContextEvent sce) {
- }
- public void sessionCreated(HttpSessionEvent se) {
- }
- public void sessionDestroyed(HttpSessionEvent se) {
- // 将用户名称从列表中删除
- List l = (List) this.application.getAttribute("alluser");
- String value = (String) se.getSession().getAttribute("uname");
- l.remove(value);
- this.application.setAttribute("alluser", l);
- }
- public void attributeAdded(HttpSessionBindingEvent se) {
- // 如果登陆成功,则将用户名保存在列表之中
- List l = (List) this.application.getAttribute("alluser");
- l.add(se.getValue());
- this.application.setAttribute("alluser", l);
- }
- public void attributeRemoved(HttpSessionBindingEvent se) {
- }
- public void attributeReplaced(HttpSessionBindingEvent se) {
- }
- }
online.jsp
- <%@ page contentType="text/html;charset=gb2312"%>
- <%@ page import="java.util.*"%>
- <form action="online.jsp" method="post">
- 用户名:
- <input type="text" name="name">
- <input type="submit" value="登陆">
- <a href="logout.jsp">注销</a>
- </form>
- <!-- 向session接收输入的用户名 -->
- <%
- if(request.getParameter("name")!=null)
- session.setAttribute("uname",request.getParameter("name")) ;
- %>
- <h2>在线人员</h2>
- <hr>
- <%
- List l = (List)application.getAttribute("allUser");
- for(Object o : l)
- out.println(o);
- %>
logout.jsp
- <%
- session.invalidate() ;
- %>