Session 内置对象的监听器
Demo: 监听 session 的状态
1.定义 session 内置对象的状态监听器
1 public class SessionListener implements HttpSessionListener { 2 @Override 3 public void sessionCreated(HttpSessionEvent event) { 4 System.out.println("创建 session 内置对象:" + event.getSession().getId()); 5 } 6 @Override 7 public void sessionDestroyed(HttpSessionEvent event) { 8 System.out.println("销毁了 session 内置对象:" + event.getSession().getId()); 9 } 10 }
2.配置 session 内置对象的状态监听器
<listener> <listener-class>com.sxt.mvcpro.listener.SessionListener</listener-class> </listener>
3.获取 session 内置对象
1 @SuppressWarnings("serial") 2 public class EmpServlet extends HttpServlet{ 3 @Override 4 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 5 req.getSession(); 6 System.out.println("访问了 servlet 方法"); 7 } 8 }
4.销毁 session 内置对象
1 @SuppressWarnings("serial") 2 public class EmpServlet extends HttpServlet{ 3 @Override 4 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 5 req.getSession().invalidate(); 6 } 7 }
Demo: 监听 session 的属性
1.定义 session 内置对象的属性监听器
1 1.定义 session 内置对象的属性监听器 2 public class SessionAttributeListener implements HttpSessionAttributeListener { 3 @Override 4 public void attributeAdded(HttpSessionBindingEvent event) { 5 System.out.println("增加属性时候触发: " + event.getName() + ":" + event.getValue()); 6 } 7 @Override 8 public void attributeRemoved(HttpSessionBindingEvent event) { 9 System.out.println("删除属性时候触发: " + event.getName() + ":" + event.getValue()); 10 } 11 @Override 12 public void attributeReplaced(HttpSessionBindingEvent event) { 13 System.out.println("替换属性时候触发: " + event.getName() + ":" + event.getValue()); 14 } 15 }
2.配置 session 内置对象的属性监听器
1 <listener> 2 <listener-class>com.sxt.mvcpro.listener.SessionAttributeListener</listener-class> 3 </listener>
3.测试监听器
1 @SuppressWarnings("serial") 2 public class EmpServlet extends HttpServlet{ 3 @Override 4 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 5 HttpSession session = req.getSession(); 6 //增加属性 7 session.setAttribute("name", "李四"); 8 //替换属性 9 session.setAttribute("name", "张三"); 10 //删除属性 11 session.removeAttribute("name"); 12 } 13 }
Demo: 访问 jsp 页面的时候为什么会触发 sessionCreated 方法?
访问 jsp 页面的时候容器会将 jsp 页面转换成一个特殊的 Servlet,
先将其转换为对应的*.java 源码(源码会调用sessionCreated ), 之后再将源码编译成对应的*.class,
之后发那会给浏览器之前会被解析为 html 代码给到浏览器解析时