HttpSessionListener的使用方式
session监听实现类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import org.springframework.stereotype.Component; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; @Component public class MySessionListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent se) { //设置session持续时间,单位为秒 se.getSession().setMaxInactiveInterval( 10 ); System.out.println( "-----------Session已创建------------------" ); } @Override public void sessionDestroyed(HttpSessionEvent se) { String name = (String)se.getSession().getAttribute( "name" ); System.out.println( "name= " + name); System.out.println( "-----------Session已销毁------------------" ); } } |
controller调用
1 2 3 4 5 6 7 |
@RequestMapping ( "/sessionTest" ) @ResponseBody public void sessionTest(HttpServletRequest request){ request.getSession().setAttribute( "name" , "zwq" ); //销毁session request.getSession().invalidate(); } |
注意点:
1、request.getSession(),获取即创建session,会触发session监听实现类中的sessionCreated方法;
2、session过了有效时间或主动使用invalidate方法销毁,会触发session监听实现类中的sessionDestroyed方法;
3、使用监听器一定要确保可以被springboot扫描到并打包成bean,一般来说在监听器实现类前加 @Component注解并保证该类在程序扫描范围内即可。
注册HttpSessionListener失效原因
问题描述
监听器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
@WebListener public class MyHttpSessionListener implements HttpSessionListener { /** * session创建 */ @Override public void sessionCreated(HttpSessionEvent e) { HttpSession session=e.getSession(); System.out.println( "session创建===ID====" +session.getId()); } /** * session销毁 */ @Override public void sessionDestroyed(HttpSessionEvent e) { HttpSession session=e.getSession(); System.out.println( "销毁的sessionID====" +session.getId()); } } |
启动类上已经加了注解@ServletComponentScan
访问接口:
1 2 3 4 5 6 7 |
@RestController public class HelloController { @RequestMapping ( "/hello" ) public String handle01(){ return "nihao你好" ; } } |
这样写之后,发现第一次访问时,控制台并不会打印:
1 |
System.out.println( "session创建===ID====" +session.getId()); |
原因
在访问接口时,形参要带上HttpSession session.
如下:
1 2 3 4 5 6 7 |
@RestController public class HelloController { @RequestMapping ( "/hello" ) public String handle01(HttpSession session){ return "nihao你好" ; } } |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/zhengyikuangge/article/details/106219550
查看更多关于SpringBoot中HttpSessionListener的简单使用方式的详细内容...