session

web中每次登录或退出,session是怎么处理的?

一、首先,写一个监听器,监听用户请求和session的操作动作

 1 public class AppRequestListener implements ServletRequestListener,
 2         HttpSessionAttributeListener {
 3 
 4     private final Log log = LogFactory.getLog(AppRequestListener.class);
 5 
 6     @Override
 7     public void attributeAdded(HttpSessionBindingEvent event) {//在session中添加对象时触发
 8         dealSessionErr(event, "add");
 9 
10     }
11 
12     @Override
13     public void attributeRemoved(HttpSessionBindingEvent event) {//移除session时触发
14         dealSessionErr(event, "remove");
15
16     }
17 
18     @Override
19     public void attributeReplaced(HttpSessionBindingEvent event) {//替换session中对象时触发
20         dealSessionErr(event, "replace");
21 
22     }
23 
24     @Override
25     public void requestDestroyed(ServletRequestEvent event) {//用户请求结束时,触发该方法
26         CtxSessionBag.clear();
27 
28     }
29 
30     @Override
31     public void requestInitialized(ServletRequestEvent requestEvent) {//用户请求到达初始化时,触发该方法
32         HttpServletRequest request = (HttpServletRequest) requestEvent
33                 .getServletRequest();
34         String pin = LoginUtils.getPin(request);
35         try {
36             request.setCharacterEncoding("UTF-8");
37         } catch (UnsupportedEncodingException e) {
38             e.printStackTrace();
39         }
40         SessionBagImpl sessionBag = null;
41         if (pin == null) {
42             return;
43         }
44 
45         if (sessionBag == null) {
46             sessionBag = new SessionBagImpl();
47         }
48 
49         sessionBag.setIp(request.getRemoteAddr());
50         sessionBag.setSessionNbr(request.getSession().getId());
51 
52         BackOperator bo = sessionBag.getBackOperator();
53         if (bo == null) {
54             bo = new BackOperator();
55         }
56         bo.setUserName(pin);
57         sessionBag.setBackOperator(bo);
58         CtxSessionBag.setSessionBag(sessionBag);
59 
60     }
61 
62 }

 

二、在web.xml中添加监听器

<listener>
  <listener-class>com.***.web.listener.AppRequestListener</listener-class>
</listener>

 

三、AppRequestListener 是监听器,每次请求的时候或session操作的时候,都会执行,所以在这个类里,

requestInitialized方法里,每次用户请求时,把用户信息封装到CtxSessionBag里
 1 public class CtxSessionBag {
 2     private static final ThreadLocal<SessionBagImpl> sessionBagThread = new ThreadLocal<SessionBagImpl>();
 3     
 4     public static SessionBagImpl getSessionBag() {
 5         return sessionBagThread.get();
 6     }
 7 
 8     public static void setSessionBag(SessionBagImpl s){
 9         sessionBagThread.set(s);
10     }
11     
12     public static void clear(){
13         sessionBagThread.set(null);
14     }
15 }
CtxSessionBag 把session信息存到ThreadLocal里,可以共享,每次从CtxSessionBag 类静态方法取
posted @ 2018-05-09 20:33  点点积累  阅读(170)  评论(0编辑  收藏  举报