一、定義攔截器
Struts2規定用戶自定義攔截器必須實現com.opensymphony.xwork2.interceptor.Interceptor接口
其中,init和destroy方法會在程序開始和結束時各執行一遍,不管使用了該攔截器與否,只要在struts.xml中聲明瞭該攔截器就會被執行。
intercept方法就是攔截的主體了,每次攔截器生效時都會執行其中的邏輯。
不過,struts中又提供了幾個抽象類來簡化這一步驟。
public abstract class AbstractInterceptor implements Interceptor;
public abstract class MethodFilterInterceptor extends AbstractInterceptor;
都是模板方法實現的。
其中AbstractInterceptor提供了init()和destroy()的空實現,使用時只需要覆蓋intercept()方法;
而MethodFilterInterceptor則提供了includeMethods和excludeMethods兩個屬性,用來過濾執行該過濾器的action的方法。可以通過param來加入或者排除需要過濾的方法。
一般來說,攔截器的寫法都差不多。看下面的示例:
- /**
- * 自定義攔截器
- * 功能:若用戶已登錄繼續執行當前action,
- * 否則返回登錄頁面
- * @author zhezi
- *
- */
- @SuppressWarnings("serial")
- public class AuthInterceptor extends AbstractInterceptor {
- @Override
- public String intercept(ActionInvocation invocation) throws Exception {
- HttpServletRequest request = ServletActionContext.getRequest();
- HttpSession session = request.getSession();
- if(session.getAttribute(Const.user) == null){
- return Action.LOGIN;
- }
- String result = invocation.invoke();
- return result;
- }
- }
二、聲明攔截器
在struts中攔截器實際上分爲攔截器和攔截器棧,攔截器棧可以包含一到多個攔截器或者攔截器棧。需將自定義攔截器加上struts缺省攔截器形成新的缺省攔截器。
特別::需注意攔截器順序,默認攔截器在上。
- <interceptors>
- <interceptor name="login" class="jp.struts.interceptor.AuthInterceptor"></interceptor>
- <interceptor-stack name="myDefault">
- <!-- 引用默認攔截器 -->
- <interceptor-ref name="defaultStack"></interceptor-ref>
- <!-- 引用自定義攔截器 -->
- <interceptor-ref name="login"></interceptor-ref>
- <interceptor-ref name="myInterceptor3">
- <!--不攔截的方法-->
- <param name="excludeMethods">test,execute</param> <!--包含攔截的方法-->
- <param name="includeMethods">test</param>
- </interceptor-ref>
- </interceptor-stack>
- </interceptors>
- <default-interceptor-ref name="myDefault"></default-interceptor-ref>
三、定義全局result
因爲全局定義了攔截器,雖然攔截器在通過攔截的情況下會返回特定Action的result,但有時候比如權限驗證失敗等情況下,自定義攔截器會返回自定義的結果,不屬於任何特定Action,所以我們也需要定義一個全局result用以響應這個攔截器的返回值。
- <global-results>
- <result name="Exception">/common/exception.jsp</result>
- <result name="RuntimeException">/common/runtime_exception.jsp</result>
- <result name="login" type="redirect">/login.jsp</result>
- </global-results>