感知Session绑定的事件监听器
- Servlet规范中定义了两个特殊的监听器接口来帮助JavaBean对象了解自己在Session域中的这些状态
HttpSessionBindingListener接口
public class Student implements HttpSessionBindingListener {
private String name;
private String mobile;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("绑定");
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("取消绑定");
}
}
index.jsp
<%@page import="com.dz.listerner.Student"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>监听器Listener</p>
<a href="./add.jsp">add</a>
<a href="./remove.jsp">remove</a>
</body>
</html>
add.jsp
<%@page import="com.dz.listerner.Student"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Student student = new Student();
session.setAttribute("student", student);
%>
</body>
</html>
remove.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
session.removeAttribute("student");
%>
</body>
</html>
- 点击add的a标签
- 执行了valueBound方法
点击remove标签
- 执行了valueUnbound方法
HttpSessionActivationListener接口
public class Student implements Serializable,HttpSessionActivationListener {
private String name;
private String mobile;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
@Override
public void sessionWillPassivate(HttpSessionEvent se) {
System.out.println("从内存保存到磁盘上");
}
@Override
public void sessionDidActivate(HttpSessionEvent se) {
System.out.println("从磁盘加载到内存中");
}
}
index.jsp
<%@page import="com.dz.listerner.Student"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>监听器Listener</p>
<%
Student student = new Student();
session.setAttribute("student", student);
%>
</body>
</html>
- 开启服务器访问项目
- 正常停止服务器(Stop),注意不要使用Terminate
- 执行了sessionWillPassivate方法
tomcat中work目录下在服务器正常停止后生成了SESSIONS.ser文件
- 再次开启服务器
- 项目目录下的SESSION.ser被删除,执行了sessionDidActivate方法
注意: 这里实现了Serializable,HttpSessionActivationListener这两个接口,如果不实现Serializable将无法看到预期效果。