Session 內置對象的監聽器
Demo: 監聽 session 的狀態
1.定義 session 內置對象的狀態監聽器html
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 內置對象的狀態監聽器java
<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 內置對象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 內置對象的屬性監聽器mvc
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 內置對象的屬性監聽器jsp
1 <listener> 2 <listener-class>com.sxt.mvcpro.listener.SessionAttributeListener</listener-class> 3 </listener>
3.測試監聽器ide
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 代碼給到瀏覽器解析時測試