文章目录 SessionAttListenerDemo.java SessionListenerDemo.java ProductController.java
SessionAttListenerDemo.java
package com. aistart. listener ; import javax. servlet. ServletContext ;
import javax. servlet. annotation. WebListener ;
import javax. servlet. http. HttpSessionAttributeListener ;
import javax. servlet. http. HttpSessionBindingEvent ;
import javax. servlet. http. HttpSessionEvent ;
import javax. servlet. http. HttpSessionListener ;
@WebListener
public class SessionAttListenerDemo implements HttpSessionAttributeListener { @Override public void attributeAdded ( HttpSessionBindingEvent httpSessionBindingEvent) { System . out. println ( "增加值" ) ; } @Override public void attributeRemoved ( HttpSessionBindingEvent httpSessionBindingEvent) { System . out. println ( "删除值" ) ; } @Override public void attributeReplaced ( HttpSessionBindingEvent httpSessionBindingEvent) { System . out. println ( "修改值" ) ; }
}
SessionListenerDemo.java
package com. aistart. listener ; import javax. servlet. ServletContext ;
import javax. servlet. annotation. WebListener ;
import javax. servlet. http. HttpSessionEvent ;
import javax. servlet. http. HttpSessionListener ;
@WebListener
public class SessionListenerDemo implements HttpSessionListener { private int OnlineUserNumber = 0 ; @Override public void sessionCreated ( HttpSessionEvent httpSessionEvent) { System . out. println ( "seesion创建并调用监听" ) ; ServletContext servletContext = httpSessionEvent. getSession ( ) . getServletContext ( ) ; this. OnlineUserNumber++ ; servletContext. setAttribute ( "userNumber" , this. OnlineUserNumber) ; } @Override public void sessionDestroyed ( HttpSessionEvent httpSessionEvent) { System . out. println ( "seesion销毁并调用监听" ) ; ServletContext servletContext = httpSessionEvent. getSession ( ) . getServletContext ( ) ; this. OnlineUserNumber-- ; servletContext. setAttribute ( "userNumber" , this. OnlineUserNumber) ; }
}
ProductController.java
package com. aistart. controller ; import javax. servlet. ServletException ;
import javax. servlet. annotation. WebServlet ;
import javax. servlet. http. HttpServlet ;
import javax. servlet. http. HttpServletRequest ;
import javax. servlet. http. HttpServletResponse ;
import javax. servlet. http. HttpSession ;
import java. io. IOException ; @WebServlet ( { "/product/init" , "/product/add" , "/product/del" } )
public class ProductController extends HttpServlet { @Override protected void service ( HttpServletRequest req, HttpServletResponse resp) throws ServletException , IOException { System . out. println ( "我开始操作了" ) ; Object userNumber = req. getServletContext ( ) . getAttribute ( "userNumber" ) ; System . out. println ( "当前在线人数" + userNumber) ; }
}