Struts2拦截器简单示例

一、定义拦截器

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来加入或者排除需要过滤的方法。

一般来说,拦截器的写法都差不多。看下面的示例:

 

  1. /** 
  2.  * 自定义拦截器 
  3.  * 功能:若用户已登录继续执行当前action, 
  4.  *      否则返回登录页面 
  5.  * @author zhezi 
  6.  * 
  7.  */ 
  8. @SuppressWarnings("serial"
  9. public class AuthInterceptor extends AbstractInterceptor { 
  10.      
  11.      
  12.     @Override 
  13.     public String intercept(ActionInvocation invocation) throws Exception { 
  14.         HttpServletRequest request = ServletActionContext.getRequest(); 
  15.         HttpSession session = request.getSession(); 
  16.         if(session.getAttribute(Const.user) == null){ 
  17.             return Action.LOGIN; 
  18.         } 
  19.         String result = invocation.invoke(); 
  20.         return result; 
  21.     } 

二、声明拦截器

在struts中拦截器实际上分为拦截器和拦截器栈,拦截器栈可以包含一到多个拦截器或者拦截器栈。需将自定义拦截器加上struts缺省拦截器形成新的缺省拦截器。

特别::需注意拦截器顺序,默认拦截器在上。


  1. <interceptors>  
  2.         <interceptor name="login" class="jp.struts.interceptor.AuthInterceptor"></interceptor>  
  3.         <interceptor-stack name="myDefault">  
  4.             <!-- 引用默认拦截器 -->   
  5.             <interceptor-ref name="defaultStack"></interceptor-ref>  
  6.             <!-- 引用自定义拦截器 -->   
  7.             <interceptor-ref name="login"></interceptor-ref> 
  8. <interceptor-ref name="myInterceptor3">               
  9.   <!--不拦截的方法-->                 
  10. <param name="excludeMethods">test,execute</param>                 <!--包含拦截的方法-->                 
  11. <param name="includeMethods">test</param>             
  12. </interceptor-ref>
  13.         </interceptor-stack>  
  14.     </interceptors>  
  15.     <default-interceptor-ref name="myDefault"></default-interceptor-ref>  

三、定义全局result

因为全局定义了拦截器,虽然拦截器在通过拦截的情况下会返回特定Action的result,但有时候比如权限验证失败等情况下,自定义拦截器会返回自定义的结果,不属于任何特定Action,所以我们也需要定义一个全局result用以响应这个拦截器的返回值。

 

  1. <global-results> 
  2.             <result name="Exception">/common/exception.jsp</result> 
  3.             <result name="RuntimeException">/common/runtime_exception.jsp</result> 
  4.             <result name="login" type="redirect">/login.jsp</result> 
  5.         </global-results> 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章