DAO层和Service层访问session

  多情况下,我们需要在DAO或者Service层拿到Session中的值,比如下面这个应用,session中存放了当前用户的账号,在DAO层中需要insert一条record,这条record需要记录当前用户(该记录是由谁创建的),对于这样的应用,我们一般可以在Action层中通过request拿到session里的用户账号,然后传入service,再传入DAO层,就可以解决了。

    今天,我在这里记录一种方式,利用ThreadLocal来存入sesion,然后可以在任何业务层,DAO层获取Session的方式,首先建立一个CSession来存放session的值,只放了2个属性,用户的账号和姓名

Java代码 复制代码
  1. public class CSession { 
  2.     private String username; 
  3.     private String userId; 
  4.          
  5.     public String getUsername() { 
  6.         return username; 
  7.     } 
  8.     public void setUsername(String username) { 
  9.         this.username = username; 
  10.     } 
  11.      
  12.     public String getUserId() { 
  13.         return userId; 
  14.     } 
  15.     public void setUserId(String userId) { 
  16.         this.userId = userId; 
  17.     } 

建立SessionUser类,用来存放在整个运行期CSession的存在

Java代码 复制代码
  1. public class SessionUser { 
  2.  
  3.  
  4.     @SuppressWarnings("unchecked"
  5.     static ThreadLocal sessionUser = new ThreadLocal(); 
  6.      
  7.     @SuppressWarnings("unchecked"
  8.     public static void setSessionUser(CSession cSession) { 
  9.         sessionUser.set(cSession); 
  10.     } 
  11.      
  12.     public static CSession getSessionUser(){ 
  13.         return (CSession )sessionUser.get(); 
  14.     } 
  15.      
  16.     public static String getSessionUserId(){ 
  17.         return getSessionUser().getUserId(); 
  18.     } 
  19.      
  20.     public static String getSessionUserName(){ 
  21.         return getSessionUser().getUsername(); 
  22.     } 

在登录的Action里,登录成功后,加Session里的用户信息,放入CSession中,

Java代码 复制代码
  1. HttpSession session = request.getSession(true); 
  2. CSession cs = new CSession(); 
  3. cs.setUserId(userId); 
  4. cs.setUsername(userName); 
  5. session.setAttribute("C_SESSION",cs); 

最后,在session check的Filter中,把CSession注入到SessionUser中,

Java代码 复制代码
  1. public void doFilter(ServletRequest request, ServletResponse response, 
  2.             FilterChain chain) throws IOException, ServletException { 
  3.          
  4.         HttpServletRequest hrequest = (HttpServletRequest) request; 
  5.         HttpServletResponse hresponse = (HttpServletResponse) response; 
  6.          
  7.                ....... 
  8.          
  9.         CSession cs = (CSession) hrequest.getSession(true).getAttribute("C_SESSION"); 
  10.          
  11.         SessionUser.setSessionUser(cs); 
  12.                          
  13.                 ....... 
  14.     } 

下面我们就可以再DAO层中直接从SessionUser中获取 userid 和 username,

Java代码 复制代码
  1. xxxTO.setUserId(SessionUser.getSessionUserId()); 
  2. xxxTO.setUserName(SessionUser.getSessionUserName()); 

页面上,

Java代码 复制代码
  1. <bean:write name="C_SESSION" property="username"/> 
  2. <bean:write name="C_SESSION" property="userId"/> 
原文地址:https://www.cnblogs.com/dandre/p/4507078.html