MySessionAttributeListener.java:
package com.demo.listener.attr;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
/**
* 监听 session 属性的变化:添加、修改、移除
*/
public class MySessionAttributeListener implements HttpSessionAttributeListener {
/**
* 添加属性
*/
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
System.out.println("属性添加");
// 获取 session 对象
HttpSession session = se.getSession();
// 获取添加的属性值
Object name = session.getAttribute("name");
System.out.println("name:" + name);
}
/**
* 移除属性
*/
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
System.out.println("属性移除");
}
/**
* 修改属性
*/
@Override
public void attributeReplaced(HttpSessionBindingEvent se) {
// 获取 session 对象
HttpSession session = se.getSession();
// 获取属性修改前的值
Object oldValue = se.getValue();
System.out.println("oldValue:" + oldValue);
// 获取属性修改后的值
Object newValue = session.getAttribute("name");
System.out.println("newValue:" + newValue);
}
}
Admin.java:
package com.demo.listener.attr;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
/**
* 监听对象 绑定/解除绑定 到 session 上的事件;
*/
public class Admin implements HttpSessionBindingListener {
private int id;
private String name;
public Admin() {
}
public Admin(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 对象绑定到 session 对象
*/
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("绑定到 session 对象");
}
/**
* 从 session 对象上解除绑定
*/
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("从 session 对象上解除绑定");
}
}
session.jsp:
<%@ page import="com.demo.listener.attr.Admin" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
/* 给 session 对象添加属性 */
session.setAttribute("name", "admin");
/* 修改属性的值 */
session.setAttribute("name", "jack");
/* 移除属性 */
session.removeAttribute("name");
/* 将 javabean 对象绑定到 session 对象 */
session.setAttribute("admin", new Admin(1, "lily"));
/* 将 javabean 对象从 session 对象上解除绑定 */
session.removeAttribute("admin");
%>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置监听器:监听 session 对象属性的变化 -->
<listener>
<listener-class>com.demo.listener.attr.MySessionAttributeListener</listener-class>
</listener>
</web-app>
浏览器输入:http://localhost:8080/07_Listener_war_exploded/session.jsp,访问结果: