很多情況下,我們需要在DAO或者Service層拿到Session中的值,比如下面這個(gè)應用,session中存放了當前用戶(hù)的賬號,在DAO層中需要insert一條record,這條record需要記錄當前用戶(hù)(該記錄是由誰(shuí)創(chuàng )建的),對于這樣的應用,我們一般可以在A(yíng)ction層中通過(guò)request拿到session里的用戶(hù)賬號,然后傳入service,再傳入DAO層,就可以解決了。
今天,我在這里記錄一種方式,利用ThreadLocal來(lái)存入sesion,然后可以在任何業(yè)務(wù)層,DAO層獲取Session的方式,首先建立一個(gè)CSession來(lái)存放session的值,只放了2個(gè)屬性,用戶(hù)的賬號和姓名
- public class CSession {
- private String username;
- private String userId;
-
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getUserId() {
- return userId;
- }
- public void setUserId(String userId) {
- this.userId = userId;
- }
- }
建立SessionUser類(lèi),用來(lái)存放在整個(gè)運行期CSession的存在
- public class SessionUser {
-
-
- @SuppressWarnings("unchecked")
- static ThreadLocal sessionUser = new ThreadLocal();
-
- @SuppressWarnings("unchecked")
- public static void setSessionUser(CSession cSession) {
- sessionUser.set(cSession);
- }
-
- public static CSession getSessionUser(){
- return (CSession )sessionUser.get();
- }
-
- public static String getSessionUserId(){
- return getSessionUser().getUserId();
- }
-
- public static String getSessionUserName(){
- return getSessionUser().getUsername();
- }
- }
在登錄的Action里,登錄成功后,加Session里的用戶(hù)信息,放入CSession中,
- HttpSession session = request.getSession(true);
- CSession cs = new CSession();
- cs.setUserId(userId);
- cs.setUsername(userName);
- session.setAttribute("C_SESSION",cs);
最后,在session check的Filter中,把CSession注入到SessionUser中,
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
-
- HttpServletRequest hrequest = (HttpServletRequest) request;
- HttpServletResponse hresponse = (HttpServletResponse) response;
-
- .......
-
- CSession cs = (CSession) hrequest.getSession(true).getAttribute("C_SESSION");
-
- SessionUser.setSessionUser(cs);
-
- .......
- }
下面我們就可以再DAO層中直接從SessionUser中獲取 userid 和 username,
- xxxTO.setUserId(SessionUser.getSessionUserId());
- xxxTO.setUserName(SessionUser.getSessionUserName());
頁(yè)面上,
- <bean:write name="C_SESSION" property="username"/>
- <bean:write name="C_SESSION" property="userId"/>
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。