关于监听器的类型其实有很多,有HttpSessionListener
、servletContext
、servletRequest
等,这些都是tomcat封装的接口,所以都可以自定义这些接口来定义符合我们业务需求的监听器。
这里以HttpSessionListener
为例
1
、打开源码HttpSessionListener
可以发现接口中有两个方法,一个是session创建的方法,一个是session销毁的方法
sessionCreated
是创建会话是调用,源码注释是“Notification that a session was created.The default implementation is a NO-OP.”
sessionDestoyed
是会话销毁时调用
源码中的方法都是没有任何内容的,所以意味着咱们可以完完全全的自定义自己的session监听器
2
、自定义监听器类
public class MyListener implements HttpSessionListener {
public static int online=0;
@Override
public void sessionCreated(HttpSessionEvent se) {//创建一次session会话,online+1
System.out.println("创建session");
online++;
System.out.println(online);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
online--;
System.out.println("销毁session");
}
}
3
、启动类中添加监听器启动方法
@Bean
public ServletListenerRegistrationBean listenerRegist(){
//servlet监听器对象
ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean();
/**
* setListener():传入的值若为空,会报“Listener must not be null”
* 若为非法值,会报“Listener is not of a supported type”
*/
srb.setListener(new MyListener());
System.out.println("listener");
return srb;
}
4
、测试类Controller
@Controller
@ResponseBody
public class ThymeleafController {
@RequestMapping("/login")
public String login(HttpServletRequest request){
HttpSession session = request.getSession(true);
return "login";
}
@RequestMapping("online")
public String online(){
return "当前在线人数:"+ MyListener.online +"人";
}
}