Struts2 權限驗證 ---攔截器和過濾器
之前的Struts2項目通過再Sitemesh的母版頁中使用Struts的if標籤進行了session判斷,使得未登錄的用戶不能看到頁面,但是這種現僅僅在view層進行,如果未登錄用戶直接在地址欄輸入登錄用戶才能訪問的地址,那麼相應的action還是會執行,僅僅是不讓用戶看到罷了。這樣顯然是不好的,所以研究了一下Struts2的權限驗證。Here i quote
權限最核心的是業務邏輯,具體用什麼技術來實現就簡單得多。
通常:用戶與角色建立多對多關係,角色與業務模塊構成多對多關係,權限管理在後者關係中。
對權限的攔截,如果系統請求量大,可以用Struts2攔截器來做,請求量小可以放在filter中。但一般單級攔截還不夠,要做到更細粒度的權限控制,還需要多級攔截。
不大理解filter(過濾器)和interceptor(攔截器)的區別,遂google之。[2]博文中有介紹:
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下面,這個目錄下的東西是“看不見”的
權限最核心的是業務邏輯,具體用什麼技術來實現就簡單得多。
通常:用戶與角色建立多對多關係,角色與業務模塊構成多對多關係,權限管理在後者關係中。
對權限的攔截,如果系統請求量大,可以用Struts2攔截器來做,請求量小可以放在filter中。但一般單級攔截還不夠,要做到更細粒度的權限控制,還需要多級攔截。
不大理解filter(過濾器)和interceptor(攔截器)的區別,遂google之。[2]博文中有介紹:
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下面,這個目錄下的東西是“看不見”的
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.