共计 1616 个字符,预计需要花费 5 分钟才能阅读完成。
1、HttpSession 的监听器
还有一个与 HttpSession 相关的特殊的监听器,这个监听器的特点如下:
-
不用在 web.xml 文件中部署;
-
这两个监听器不是给 session 添加,而是给 Bean 添加。即让 Bean 类实现监听器接口,然后再把 Bean 对象添加到 session 域中。
下面对这个监听器介绍一下 :
HttpSessionBindingListener:当某个类实现了该接口后,可以感知本类对象添加到 session 中,以及感知从 session 中移除。例如让 Person 类实现 HttpSessionBindingListener 接口,那么当把 Person 对象添加到 session 中,或者把 Person 对象从 session 中移除时会调用下面两个方法:
public void valueBound(HttpSessionBindingEvent event):当把监听器对象添加到 session 中会调用监听器对象的本方法;
public void valueUnbound(HttpSessionBindingEvent event):当把监听器对象从 session 中移除时会调用监听器对象的本方法;
这里要注意,HttpSessionBindingListener 监听器的使用与前面介绍的都不相同,当该监听器对象添加到 session 中,或把该监听器对象从 session 移除时会调用监听器中的方法。并且无需在 web.xml 文件中部署这个监听器。
2、案例
public class User implements HttpSessionBindingListener {private String username; | |
private String password; | |
public String getUsername() {return username; | |
} | |
public void setUsername(String username) {this.username = username; | |
} | |
public String getPassword() {return password; | |
} | |
public void setPassword(String password) {this.password = password; | |
} | |
public void valueBound(HttpSessionBindingEvent event) {System.out.println("我添加到 session 域中去了"); | |
} | |
public void valueUnbound(HttpSessionBindingEvent event) {System.out.println("我从 session 域中被移除了"); | |
} | |
} | |
add.jsp
<%@page import="com.javaweb.listener.demo.User"%> | |
<%@ page language="java" contentType="text/html; charset=UTF-8" | |
pageEncoding="UTF-8"%> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Insert title here</title> | |
</head> | |
<body> | |
<% | |
session.setAttribute("user", new User()); | |
%> | |
</body> | |
</html> |
remove.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" | |
pageEncoding="UTF-8"%> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Insert title here</title> | |
</head> | |
<body> | |
<% | |
session.removeAttribute("user"); | |
%> | |
</body> | |
</html> |
正文完
星哥玩云-微信公众号
