Web-Listener

事件源、事件、监听器
  • 事件源:发生事件的对象
  • 事件:事件封装了事件源,方便监听器的某个方法获取到事件源对象
  • 监听器:监听事件源的行为和动作
    注:监听器一般都是接口,谁用谁实现。
Servlet规范中提供的8个监听器

监听ServletContext、HttpSession、ServletRequest对象的初始化和销毁的监听器

  1. ServletContextListener
  • void contextInitialized(ServletContextEvent sce) :ServletContext初始化
  • void contextDestroyed(ServletContextEvent sce) :ServletContext销毁
    使用场景:
    应用启动时执行,可将整个应用的初始化代码写到该监听器里
  1. HttpSessionListener
  • void sessionCreated(HttpSessionEvent sce):第一次执行request.getSession()执行
  • void sessionDestroyed(HttpSessionEvent sce):HttpSession销毁时调用
    注:关闭浏览器不会导致HttpSession销毁;HttpSession销毁时机(超时或者手动调用invalidate()方法)
    使用场景:
                    统计网站在线用户量
    
  1. ServletRequestListener
  • void requestInitialized(ServletRequestEvent arg0):用户请求时执行
  • void requestDestroyed(ServletRequestEvent arg0):请求结束后执行
    使用场景:根据用户访问的url资源id进行页面访问量统计
    

监听ServletContext、HttpSession、ServletRequest域对象数据变化(增删改)的监听器

  1. ServletContextAttributeListener
  • void attributeAdded(ServletContextAttributeEvent arg0):当向应用范围内添加属性时执行
  • void attributeRemoved(ServletContextAttributeEvent arg0):当从应用范围内移除属性时执行
  • void attributeReplaced(ServletContextAttributeEvent arg0):当应用范围内当属性值替换时执行
  1. HttpSessionAttributeListener
  • void attributeAdded(HttpSessionBindingEvent arg0):当向会话范围内添加属性时执行
  • void attributeRemoved(HttpSessionBindingEvent arg0):当从会话范围内移除属性时执行
  • void attributeReplaced(HttpSessionBindingEvent arg0):当会话范围内当属性值替换时执行
    使用场景:统计在线用户,踢人
  1. ServletRequestAttributeListener
  • void attributeAdded(ServletRequestAttributeEvent arg0):当向请求范围内添加属性时执行
  • void attributeRemoved(ServletRequestAttributeEvent arg0):当从请求范围内移除属性时执行
  • void attributeReplaced(ServletRequestAttributeEvent arg0):当请求范围内当属性值替换时执行

感知型监听器(无需注册监听器)

  1. HttpSessionBindingListener:监听自身是否被添加到量session中去
  • void valueBound(HttpSessionBindingEvent arg0):绑定时执行
  • void valueUnbound(HttpSessionBindingEvent arg0):解绑时执行
  1. HttpSessionActivationListener:监听自身合适被钝化和激活
  • void sessionWillPassivate(HttpSessionEvent arg0):钝化时执行
  • void sessionDidActivate(HttpSessionEvent arg0):被激活时执行
HttpSession的钝化和激活

当用户第一次调用request.getSession()时,则会创建session对象,session对象会存储在缓存当中。

  • session销毁:只有在session超时和手动调用invalidata()方法时,session对象才会销毁。
  • session钝化:将session对象持久化到本地硬盘上(tomcat/work/catalina/localhost/应用名/下的*.ser文件)
    1、服务器内存告急
    2、HttpSession对象长时间没有使用
    3、服务器正常停止或应用被卸载
    
    注:在编写javabean时,最好实现java.io.Serializable接口,若没有实现该接口,则会导致session的激活会失败
在线用户统计及踢人案例

流程分析:

1. 创建HttpSessionAttributeListener
2. 当用户登录成功后,则在session中设置当前用户信息
3. 在HttpSessionAttributeListener的attributeAdded方法中判断并创建Map<String,HttpSession>是否有当前用户信息,没有则添加,并将该map集合设置到全局属性中
4. 展示页面中通过获取ServletContext中的attribute的map集合进行遍历展示在线用户信息
5. 踢下线处理则将目标用户的username作为参数传递给Servlet,在踢下线Servlet中获取全局map,删除对应的session中的目标用户信息,再从map中移除目标元素

示例代码:
index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:if test="${sessionScope.user == null }">
<c:redirect url="/login.jsp"></c:redirect>
</c:if>
欢迎您,${sessionScope.user.username}
<c:if test="${sessionScope.user.username eq 'admin' }">
<a href="${ pageContext.request.contextPath }/online.jsp">查看在线用户</a>
</c:if>
</body>
</html>

login.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/servlet/LoginServlet"
method="post">
<table align="center" border="1" cellpadding="4px">
<tr>
<td align="right">用户名</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td align="right">密码</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="登录" /></td>
</tr>
</table>
</form>
</body>
</html>

LoginServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.gaoshiyi.web.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import com.gaoshiyi.web.domain.User;
import com.gaoshiyi.web.service.BusinessSevice;
import com.gaoshiyi.web.service.impl.BusinessServiceImpl;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;chartset=utf-8");
Map<String, String[]> map = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user, map);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BusinessSevice sevice = new BusinessServiceImpl();
User exitUser = sevice.login(user);
if (exitUser == null) {
response.getWriter().write("用户或密码错误,请重新登录!");
response.setHeader("Refresh", "1;url=" + request.getContextPath() + "/login.jsp");
return;
}
//进行session的存储
HttpSession session = request.getSession();
session.setAttribute("user", user);
response.sendRedirect(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

LoginInfoListener.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.gaoshiyi.web.listener;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import com.gaoshiyi.web.domain.User;
/**
* 用户登录信息监听器
*
*/
@WebListener
public class LoginInfoListener implements HttpSessionAttributeListener {
public LoginInfoListener() {
}
public void attributeAdded(HttpSessionBindingEvent arg0) {
HttpSession session = arg0.getSession();
ServletContext servletContext = session.getServletContext();
Object obj = session.getAttribute("user");
if (obj != null && obj instanceof User) {
//建立Map集合存储用户信息
Map<String, HttpSession> usersMap = (Map<String, HttpSession>) servletContext.getAttribute("users");
if (usersMap == null) {
//同步处理否则会创建多个Map
usersMap = Collections.synchronizedMap(new HashMap<>());
servletContext.setAttribute("users", usersMap);
}
User user = (User) obj;
if (!usersMap.containsKey(user.getUsername())) {
//若集合中没有该用户则添加
usersMap.put(user.getUsername(), session);
System.out.println("新用户:" + user.getUsername() + "登录...");
}
System.out.println(usersMap);
}
}
public void attributeRemoved(HttpSessionBindingEvent arg0) {
}
public void attributeReplaced(HttpSessionBindingEvent arg0) {
}
}

online.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>在线用户</title>
</head>
<body>
<c:if test="${sessionScope.user.username != 'admin' }">
<c:redirect url="/index.jsp"></c:redirect>
</c:if>
<h3 align="center">当前在线用户列表</h3>
<table align="center" border="1" width="50%" height="auto">
<tr>
<th>用户名</th>
<th>操作</th>
</tr>
<c:forEach items="${applicationScope.users }" var="um">
<tr align="center">
<c:url var="url" value="servlet/KickServlet">
<c:param name="username" value="${ um.key}"></c:param>
</c:url>
<td>${ um.key }</td>
<td><a href="${ url }">踢下线</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>

KickServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.gaoshiyi.web.servlet;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 踢下线处理
* @author gaopengfei
*
*/
public class KickServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public KickServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
// username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
System.out.println("被踢用户:" + username);
//获取全局用户登录信息集合
Map<String, HttpSession> usersMap = (Map<String, HttpSession>) getServletContext().getAttribute("users");
if (usersMap.containsKey(username)) {
//先从session中移除
usersMap.get(username).removeAttribute("user");
//再从map中移除元素
usersMap.remove(username);
System.out.println("用户:" + username + "已被踢下线...");
}
response.getWriter().write("操作成功^_^");
response.setHeader("Refresh", "1;url=" + request.getContextPath()+"/online.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

演示:

在线踢下线

如果帮到了你,想打赏支持,喏~