HttpSession的监听器
阅读 (838353)
分享
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"%>
<!DOCTYPE html>
<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"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
session.removeAttribute("user");
%>
</body>
</html>
需要
登录
才可以提问哦
: