Struts2角色權限 filter(過濾器)和interceptor(攔截器)

jopen 10年前發布 | 29K 次閱讀 Struts2 Web框架

Struts2項目通過使用Struts的if標簽進行了session判斷,使得未登錄的用戶不能看到頁面,但是這 種現僅僅在view層進行,如果未登錄用戶直接在地址欄輸入登錄用戶才能訪問的地址,那么相應的action還是會執行,僅僅是不讓用戶看到罷了。這樣顯 然是不好的,所以研究了一下Struts2的權限驗證。

權限最核心的是業務邏輯,具體用什么技術來實現就簡單得多。 
通常:用戶與角色建立多對多關系,角色與業務模塊構成多對多關系,權限管理在后者關系中。 
對權限的攔截,如果系統請求量大,可以用Struts2攔截器來做,請求量小可以放在filter中。但一般單級攔截還不夠,要做到更細粒度的權限控制,還需要多級攔截。

    不大理解filter(過濾器)和interceptor(攔截器)的區別,遂google之。博文中有介紹:

1、攔截器是基于java的反射機制的,而過濾器是基于函數回調 。 
2、過濾器依賴與servlet容器,而攔截器不依賴與servlet容器 。 
3、攔截器只能對action請求起作用,而過濾器則可以對幾乎所有的請求 起作用 。 
4、攔截器可以訪問action上下文、值棧里的對象,而過濾器不能 。 
5、在action的生命周期中,攔截器可以多次被調用,而過濾器只能在容 器初始化時被調用一次 。

    為了學習決定把兩種實現方式都試一下,然后再決定使用哪個。

權限驗證的Filter實現:

web.xml代碼片段

  

[html] view plaincopy
  1. <!-- authority filter 最好加在Struts2的Filter前面-->  
  2.   <filter>  
  3.     <filter-name>SessionInvalidate</filter-name>  
  4.     <filter-class>filter.SessionCheckFilter</filter-class>  
  5.     <init-param>  
  6.       <param-name>checkSessionKey</param-name>  
  7.       <param-value>loginName</param-value>  
  8.     </init-param>  
  9.     <init-param>  
  10.       <param-name>redirectURL</param-name>  
  11.       <param-value>/entpLogin.jsp</param-value>  
  12.     </init-param>  
  13.     <init-param>  
  14.       <param-name>notCheckURLList</param-name>  
  15.       <param-value>/entpLogin.jsp,/rois/loginEntp.action,/entpRegister.jsp,/test.jsp,/rois/registerEntp.action</param-value>  
  16.     </init-param>  
  17.   </filter>  
  18.   <!--過濾/rois命名空間下所有action  -->  
  19.   <filter-mapping>  
  20.     <filter-name>SessionInvalidate</filter-name>  
  21.     <url-pattern>/rois/*</url-pattern>  
  22.   </filter-mapping>  
  23.   <!--過濾/jsp文件夾下所有jsp  -->  
  24.   <filter-mapping>  
  25.     <filter-name>SessionInvalidate</filter-name>  
  26.     <url-pattern>/jsp/*</url-pattern>  
  27.   </filter-mapping>  


SessionCheckFilter.java代碼
[java] view plaincopy
  1. package filter;  
  2. import java.io.IOException;  
  3. import java.util.HashSet;  
  4. import java.util.Set;  
  5. import javax.servlet.Filter;  
  6. import javax.servlet.FilterChain;  
  7. import javax.servlet.FilterConfig;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.ServletRequest;  
  10. import javax.servlet.ServletResponse;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13. import javax.servlet.http.HttpSession;  
  14. /** 
  15.  * 用于檢測用戶是否登陸的過濾器,如果未登錄,則重定向到指的登錄頁面 配置參數 checkSessionKey 需檢查的在 Session 中保存的關鍵字 
  16.  * redirectURL 如果用戶未登錄,則重定向到指定的頁面,URL不包括 ContextPath notCheckURLList 
  17.  * 不做檢查的URL列表,以分號分開,并且 URL 中不包括 ContextPath 
  18.  */  
  19. public class SessionCheckFilter implements Filter {  
  20.   protected FilterConfig filterConfig = null;  
  21.   private String redirectURL = null;  
  22.   private Set<String> notCheckURLList = new HashSet<String>();  
  23.   private String sessionKey = null;  
  24.   @Override  
  25.   public void destroy() {  
  26.     notCheckURLList.clear();  
  27.   }  
  28.   @Override  
  29.   public void doFilter(ServletRequest servletRequest,  
  30.       ServletResponse servletResponse, FilterChain filterChain)  
  31.       throws IOException, ServletException {  
  32.     HttpServletRequest request = (HttpServletRequest) servletRequest;  
  33.     HttpServletResponse response = (HttpServletResponse) servletResponse;  
  34.     HttpSession session = request.getSession();  
  35.     if (sessionKey == null) {  
  36.       filterChain.doFilter(request, response);  
  37.       return;  
  38.     }  
  39.     if ((!checkRequestURIIntNotFilterList(request))  
  40.         && session.getAttribute(sessionKey) == null) {  
  41.       response.sendRedirect(request.getContextPath() + redirectURL);  
  42.       return;  
  43.     }  
  44.     filterChain.doFilter(servletRequest, servletResponse);  
  45.   }  
  46.   private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {  
  47.     String uri = request.getServletPath()  
  48.         + (request.getPathInfo() == null ? "" : request.getPathInfo());  
  49.     String temp = request.getRequestURI();  
  50.     temp = temp.substring(request.getContextPath().length() + 1);  
  51.     // System.out.println("是否包括:"+uri+";"+notCheckURLList+"=="+notCheckURLList.contains(uri));  
  52.     return notCheckURLList.contains(uri);  
  53.   }  
  54.   @Override  
  55.   public void init(FilterConfig filterConfig) throws ServletException {  
  56.     this.filterConfig = filterConfig;  
  57.     redirectURL = filterConfig.getInitParameter("redirectURL");  
  58.     sessionKey = filterConfig.getInitParameter("checkSessionKey");  
  59.     String notCheckURLListStr = filterConfig  
  60.         .getInitParameter("notCheckURLList");  
  61.     if (notCheckURLListStr != null) {  
  62.       System.out.println(notCheckURLListStr);  
  63.       String[] params = notCheckURLListStr.split(",");  
  64.       for (int i = 0; i < params.length; i++) {  
  65.         notCheckURLList.add(params[i].trim());  
  66.       }  
  67.     }  
  68.   }  
  69. }  

權限驗證的Interceptor實現:

   使用Interceptor不需要更改web.xml,只需要對struts.xml進行配置

struts.xml片段
[html] view plaincopy
  1. <!-- 用戶攔截器定義在該元素下 -->  
  2.     <interceptors>  
  3.       <!-- 定義了一個名為authority的攔截器 -->  
  4.       <interceptor name="authenticationInterceptor" class="interceptor.AuthInterceptor" />  
  5.       <interceptor-stack name="defualtSecurityStackWithAuthentication">  
  6.         <interceptor-ref name="defaultStack" />  
  7.         <interceptor-ref name="authenticationInterceptor" />  
  8.       </interceptor-stack>  
  9.     </interceptors>  
  10.     <default-interceptor-ref name="defualtSecurityStackWithAuthentication" />  
  11.     <!-- 全局Result -->  
  12.     <global-results>  
  13.       <result name="error">/error.jsp</result>  
  14.       <result name="login">/Login.jsp</result>  
  15.     </global-results>  
  16.     <action name="login" class="action.LoginAction">  
  17.       <param name="withoutAuthentication">true</param>  
  18.       <result name="success">/WEB-INF/jsp/welcome.jsp</result>  
  19.       <result name="input">/Login.jsp</result>  
  20.     </action>  
  21.     <action name="viewBook" class="action.ViewBookAction">  
  22.         <result name="sucess">/WEB-INF/viewBook.jsp</result>  
  23.     </action>  

AuthInterceptor.java代碼
[java] view plaincopy
  1. package interceptor;  
  2. import java.util.Map;  
  3. import com.opensymphony.xwork2.Action;  
  4. import com.opensymphony.xwork2.ActionContext;  
  5. import com.opensymphony.xwork2.ActionInvocation;  
  6. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;  
  7. public class AuthInterceptor extends AbstractInterceptor {  
  8.   private static final long serialVersionUID = -5114658085937727056L;  
  9.   private String sessionKey="loginName";  
  10.   private String parmKey="withoutAuthentication";  
  11.   private boolean excluded;  
  12.   @Override  
  13.   public String intercept(ActionInvocation invocation) throws Exception {  
  14.       
  15.     ActionContext ac=invocation.getInvocationContext();  
  16.     Map<?, ?> session =ac.getSession();  
  17.     String parm=(String) ac.getParameters().get(parmKey);  
  18.       
  19.     if(parm!=null){  
  20.       excluded=parm.toUpperCase().equals("TRUE");  
  21.     }  
  22.       
  23.     String user=(String)session.get(sessionKey);  
  24.     if(excluded || user!=null){  
  25.       return invocation.invoke();  
  26.     }  
  27.     ac.put("tip""您還沒有登錄!");  
  28.     //直接返回 login 的邏輯視圖    
  29.         return Action.LOGIN;   
  30.   }  
  31. }  

使用自定義的default-interceptor的話有需要注意幾點:

1.一定要引用一下Sturts2自帶defaultStack。否則會用不了Struts2自帶的攔截器。

2.一旦在某個包下定義了上面的默認攔截器棧,在該包下的所有 Action 都會自動增加權限檢查功能。所以有可能會出現永遠登錄不了的情況。

解決方案:

1.像上面的代碼一樣,在action里面增加一個參數表明不需要驗證,然后在interceptor實現類里面檢查是否不需要驗證

2.將那些不需要使用權限控制的 Action 定義在另一個包中,這個新的包中依然使用 Struts 2 原有的默認攔截器棧,將不會有權限控制功能。

3.Interceptor是針對action的攔截,如果知道jsp地址的話在URL欄直接輸入JSP的地址,那么權限驗證是沒有效果滴!

解決方案:把所有page代碼(jsp)放到WEB-INF下面,這個目錄下的東西是“看不見”的

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!