權限最核心的是業務邏輯,具體用什麼技術來實現就簡單得多。 一般:用戶與角色創建多對多關係,角色與業務模塊構成多對多關係,權限管理在後者關係中。 對權限的攔截,若是系統請求量大,能夠用Struts2攔截器來作,請求量小能夠放在filter中。但通常單級攔截還不夠,要作到更細粒度的權限控制,還須要多級攔截。 不大理解filter(過濾器)和interceptor(攔截器)的區別,遂google之。 1、攔截器是基於java的反射機制的,而過濾器是基於函數回調 。 2、過濾器依賴與servlet容器,而攔截器不依賴與servlet容器 。 3、攔截器只能對action請求起做用,而過濾器則能夠對幾乎全部的請求 起做用 。 4、攔截器能夠訪問action上下文、值棧裏的對象,而過濾器不能 。 5、在action的生命週期中,攔截器能夠屢次被調用,而過濾器只能在容 器初始化時被調用一次 。 爲了學習決定把兩種實現方式都試一下,而後再決定使用哪一個。 權限驗證的Filter實現: web.xml代碼片斷 <!-- authority filter 最好加在Struts2的Filter前面--> <filter> <filter-name>SessionInvalidate</filter-name> <filter-class>filter.SessionCheckFilter</filter-class> <init-param> <param-name>checkSessionKey</param-name> <param-value>loginName</param-value> </init-param> <init-param> <param-name>redirectURL</param-name> <param-value>/entpLogin.jsp</param-value> </init-param> <init-param> <param-name>notCheckURLList</param-name> <param-value>/entpLogin.jsp,/rois/loginEntp.action,/entpRegister.jsp,/test.jsp,/rois/registerEntp.action</param-value> </init-param> </filter> <!--過濾/rois命名空間下全部action --> <filter-mapping> <filter-name>SessionInvalidate</filter-name> <url-pattern>/rois/*</url-pattern> </filter-mapping> <!--過濾/jsp文件夾下全部jsp --> <filter-mapping> <filter-name>SessionInvalidate</filter-name> <url-pattern>/jsp/*</url-pattern> </filter-mapping> SessionCheckFilter.java代碼 package filter; import java.io.IOException; import java.util.HashSet; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * 用於檢測用戶是否登錄的過濾器,若是未登陸,則重定向到指的登陸頁面 配置參數 checkSessionKey 需檢查的在 Session 中保存的關鍵字 * redirectURL 若是用戶未登陸,則重定向到指定的頁面,URL不包括 ContextPath notCheckURLList * 不作檢查的URL列表,以分號分開,而且 URL 中不包括 ContextPath */ public class SessionCheckFilter implements Filter { protected FilterConfig filterConfig = null; private String redirectURL = null; private Set<String> notCheckURLList = new HashSet<String>(); private String sessionKey = null; @Override public void destroy() { notCheckURLList.clear(); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(); if (sessionKey == null) { filterChain.doFilter(request, response); return; } if ((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null) { response.sendRedirect(request.getContextPath() + redirectURL); return; } filterChain.doFilter(servletRequest, servletResponse); } private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) { String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo()); String temp = request.getRequestURI(); temp = temp.substring(request.getContextPath().length() + 1); // System.out.println("是否包括:"+uri+";"+notCheckURLList+"=="+notCheckURLList.contains(uri)); return notCheckURLList.contains(uri); } @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; redirectURL = filterConfig.getInitParameter("redirectURL"); sessionKey = filterConfig.getInitParameter("checkSessionKey"); String notCheckURLListStr = filterConfig .getInitParameter("notCheckURLList"); if (notCheckURLListStr != null) { System.out.println(notCheckURLListStr); String[] params = notCheckURLListStr.split(","); for (int i = 0; i < params.length; i++) { notCheckURLList.add(params[i].trim()); } } } } 權限驗證的Interceptor實現: 使用Interceptor不須要更改web.xml,只須要對struts.xml進行配置 struts.xml片斷 <!-- 用戶攔截器定義在該元素下 --> <interceptors> <!-- 定義了一個名爲authority的攔截器 --> <interceptor name="authenticationInterceptor" class="interceptor.AuthInterceptor" /> <interceptor-stack name="defualtSecurityStackWithAuthentication"> <interceptor-ref name="defaultStack" /> <interceptor-ref name="authenticationInterceptor" /> </interceptor-stack> </interceptors> <default-interceptor-ref name="defualtSecurityStackWithAuthentication" /> <!-- 全局Result --> <global-results> <result name="error">/error.jsp</result> <result name="login">/Login.jsp</result> </global-results> <action name="login" class="action.LoginAction"> <param name="withoutAuthentication">true</param> <result name="success">/WEB-INF/jsp/welcome.jsp</result> <result name="input">/Login.jsp</result> </action> <action name="viewBook" class="action.ViewBookAction"> <result name="sucess">/WEB-INF/viewBook.jsp</result> </action> AuthInterceptor.java代碼 package interceptor; import java.util.Map; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class AuthInterceptor extends AbstractInterceptor { private static final long serialVersionUID = -5114658085937727056L; private String sessionKey="loginName"; private String parmKey="withoutAuthentication"; private boolean excluded; @Override public String intercept(ActionInvocation invocation) throws Exception { ActionContext ac=invocation.getInvocationContext(); Map<?, ?> session =ac.getSession(); String parm=(String) ac.getParameters().get(parmKey); if(parm!=null){ excluded=parm.toUpperCase().equals("TRUE"); } String user=(String)session.get(sessionKey); if(excluded || user!=null){ return invocation.invoke(); } ac.put("tip", "您尚未登陸!"); //直接返回 login 的邏輯視圖 return Action.LOGIN; } } 使用自定義的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下面,這個目錄下的東西是「看不見」的 最後我項目裏仍是使用的filter實現方式,項目變更的少嘛~^_^