衆所周知,Struts2的大部分功能都是通過攔截器實現的,就算是Struts2的啓動也是使用Servlet的攔截器啓動的,下
面我們來說一下自定義Struts2攔截器,其實只要是學過Servlet的攔截器,就應該明白大概原理,基本上是差不多的。
首先需要寫一個類,實現Struts2的指定接口,com.opensymphony.xwork2.interceptor.Interceptor;
- package com.bird.action;
- import com.opensymphony.xwork2.ActionContext;
- import com.opensymphony.xwork2.ActionInvocation;
- import com.opensymphony.xwork2.interceptor.Interceptor;
- public class PermissionInterceptor implements Interceptor {
- private static final long serialVersionUID = 1L;
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void init() {
- // TODO Auto-generated method stub
- }
- public String intercept(ActionInvocation action) throws Exception {
- Object value = ActionContext.getContext().getSession().get("user");
- if(value != null) return action.invoke();
- ActionContext.getContext().put("message", "您沒有權限登錄");
- return "message";
- }
- }
和Servlet攔截器類似,主要都是在intercept這個方法上了,這裏判斷session裏面是否有值,如果有值就調用攔截器後
面的Action的方法,這樣就完成了攔截器的任務,沒有servlet裏面的攔截器鏈。下面的工作就是註冊攔截器,在
struts.xml這個配置文件裏面這樣配置。
- <package name="niao" namespace="/t" extends="struts-default">
- <interceptors>
- <interceptor name="permission" class="com.bird.action.PermissionInterceptor"/>
- <interceptor-stack name="permissionStack">
- <interceptor-ref name="defaultStack"></interceptor-ref>
- <interceptor-ref name="permission"></interceptor-ref>
- </interceptor-stack>
- </interceptors>
- <global-results>
- <result name="message">/WEB-INF/jsp/hello.jsp</result>
- </global-results>
- <action name="login_*" class="com.bird.action.Login" method="{1}">
- <interceptor-ref name="permissionStack"/>
- <result name="success">/WEB-INF/jsp/hello.jsp</result>
- </action>
- </package>
這裏啓用了攔截器棧,這個意思是因爲一旦你定義了自己的攔截器就把struts默認的攔截器都給屏蔽掉了,這樣的話
很多struts的功能就不能使用了,所以使用了攔截器棧,這樣把struts默認的和你自定義的都放在了一個堆棧中,實現
了自定義和默認的攔截器的同時使用,默認堆棧的名稱爲defalutStack,這個名字可以在struts-default.xml文件裏面找
到,不能寫錯了。然後定義了一個全局信息處理頁面,最後在action定義裏面直接把攔截器堆棧放到裏面去就行了。
總體感覺還是挺簡單的,至少和servlet差不多