阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

HttpSession的监听器

82次阅读
没有评论

共计 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"%> <!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>

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-06-06发表,共计1616字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中