Struts2教程:实现自已的拦截器

开发 后端
本文为Struts2教程,本部分教你如何实现自已的拦截器。Struts2虽然在大版本号上是第二个版本,但基本上在配置和使用上已经完全颠覆了Struts1.x的方式。

在上一篇中介绍了Struts2拦截器的原理,在这一篇中我们将学习一下如何编写自己的拦截器。

一、拦截器的实现

实现一个拦截器非常简单。实际上,一个拦截器就是一个普通的类,只是这个类必须实现com.opensymphony.xwork2.interceptor.Interceptor接口。Interceptor接口有如下三个方法:

  1. public interface Interceptor extends Serializable   
  2. {  
  3.     void destroy();  
  4.     void init();  
  5.     String intercept(ActionInvocation invocation) throws Exception;  

其中init和destroy方法只在拦截器加载和释放(都由Struts2自身处理)时执行一次。而intercept方法在每次访问动作时都会被调用。Struts2在调用拦截器时,每个拦截器类只有一个对象实例,而所有引用这个拦截器的动作都共享这一个拦截器类的对象实例,因此,在实现Interceptor接口的类中如果使用类变量,要注意同步问题。

下面我们来实现一个简单的拦截器,这个拦截器通过请求参数action指定一个拦截器类中的方法,并调用这个方法(我们可以使用这个拦截器对某一特定的动作进行预处理)。如果方法不存在,或是action参数不存在,则继续执行下面的代码。如下面的URL:

http://localhost:8080/struts2/test/interceptor.action?action=test

访问上面的url后,拦截器会就会调用拦截器中的test方法,如果这个方法不存在,则调用invocation.invoke方法,invoke方法和Servlet过滤器中调用FilterChain.doFilter方法类似,如果在当前拦截器后面还有其他的拦截器,则invoke方法就是调用后面拦截器的intercept方法,否则,invoke会调用Action类的execute方法(或其他的执行方法)。

下面我们先来实现一个拦截器的父类ActionInterceptor。这个类主要实现了根据action参数值来调用方法的功能,代码如下:

  1. package interceptor;  
  2.  
  3. import com.opensymphony.xwork2.ActionInvocation;  
  4. import com.opensymphony.xwork2.interceptor.Interceptor;  
  5. import javax.servlet.http.*;  
  6. import org.apache.struts2.*;  
  7.  
  8. public class ActionInterceptor implements Interceptor  
  9. {  
  10.     protected final String INVOKE = "##invoke";  
  11.      
  12.     public void destroy()  
  13.     {  
  14.         System.out.println("destroy");  
  15.     }  
  16.  
  17.     public void init()  
  18.     {  
  19.         System.out.println("init");  
  20.     }  
  21.  
  22.     public String intercept(ActionInvocation invocation) throws Exception  
  23.     {      
  24.         HttpServletRequest request = ServletActionContext.getRequest();  
  25.         String action = request.getParameter("action");  
  26.         System.out.println(this.hashCode());  
  27.         if (action != null)  
  28.         {  
  29.             try 
  30.             {  
  31.                 java.lang.reflect.Method method = this.getClass().getMethod(action);  
  32.                 String result = (String)method.invoke(this);  
  33.                 if(result != null)  
  34.                 {  
  35.                     if(!result.equals(INVOKE))  
  36.                         return result;  
  37.                 }  
  38.                 else 
  39.                     return null;  
  40.             }  
  41.             catch (Exception e)  
  42.             {  
  43.             }  
  44.         }  
  45.         return invocation.invoke();  
  46.     }  
  47. }  

从上面代码中的intercept方法可以看出,在调用action所指定的方法后,来判断返回值。可能发生的情况有三种:

1. 返回值为null,执行return null。

2. 返回值为INVOKE,执行return invockation.invoke()。

3. 其他情况,执行return result。 result表示指定方法的返回值,如上面代码所示。

在实现完上面的拦截器父类后,任何继承于ActionInterceptor类的拦截器都可以自动根据action的参数值调用自身的相应方法。下面我们来实现一个拥有两个动作方法test和print的拦截器类。代码如下:

  1. package interceptor;  
  2.  
  3. import javax.servlet.http.HttpServletResponse;  
  4. import org.apache.struts2.ServletActionContext;  
  5.  
  6. public class MultiMethodInterceptor extends ActionInterceptor  
  7. {  
  8.     public String test() throws Exception  
  9.     {  
  10.         HttpServletResponse response = ServletActionContext.getResponse();  
  11.         response.getWriter().println("invoke test");  
  12.         return this.INVOKE;  
  13.     }  
  14.  
  15.     public String print() throws Exception  
  16.     {  
  17.         HttpServletResponse response = ServletActionContext.getResponse();  
  18.         response.getWriter().println("invoke print");  
  19.  
  20.         return null;  
  21.     }  
  22. }  

test方法返回了INVOKE,因此,在执行完这个方法后,Struts2会接着调用其他拦截器的intercept方法或Action类的execute方法。而print方法在执行完后,只是返回了null,而不再调用其他的方法了,也就是访问如下的url时,动作的execute方法将不会执行:

http://localhost:8080/struts2/test/ddd.action?action=print

下面我们来实现一个Action类,代码如下:

  1. package action;  
  2.  
  3. import org.apache.struts2.*;  
  4. import com.opensymphony.xwork2.ActionSupport;  
  5.  
  6. public class InterceptorAction extends ActionSupport  
  7. {  
  8.     public String abcd() throws Exception  
  9.     {  
  10.         ServletActionContext.getResponse().getWriter()  
  11.                 .println("invoke abcd");  
  12.         return null;  
  13.     }  
  14. }  

在这个Action类中,只有一个abcd方法,实际上,这个方法相当于execute方法,在下面会设置动作的method属性为abcd。下面我们来在struts.xml中定义拦截器类和动作,代码如下:

  1. < ?xml version="1.0" encoding="UTF-8" ?> 
  2. < !DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd"> 
  5. < struts> 
  6.     < package name="demo" extends="struts-default" namespace="/test"> 
  7.         < interceptors> 
  8.             < interceptor name="method" class="interceptor.MultiMethodInterceptor" /> 
  9.                 < interceptor-stack name="methodStack"> 
  10.                     < interceptor-ref name="method" /> 
  11.                     < interceptor-ref name="defaultStack" /> 
  12.                 < /interceptor-stack> 
  13.         < /interceptors> 
  14.  
  15.         < action name="interceptor" class="action.InterceptorAction" method="abcd"> 
  16.             < interceptor-ref name="methodStack" /> 
  17.         < /action> 
  18.     < /package> 
  19. < /struts> 

在配置上面的methodStack拦截器时要注意,***在后面引用defaultStack,否则很多通过拦截器提供的功能将失去。

OK,现在访问如下的URL:

http://localhost:8080/struts2/test/ddd.action?action=test

在浏览器中将会出现如下的字符串:

invoke test

invoke abcd

而如果访问http://localhost:8080/struts2/test/ddd.action?action=print,将会只出现如下的字符串:

invoke print

大家可以看出,访问这个url时并没有调用abcd方法。如果随便指定的action值的话,则只调用abcd方法,如访问http://localhost:8080/struts2/test/ddd.action?action=aaa,就只会输出invoke abcd。

二、拦截器的参数

我们在使用很多Struts2内置的拦截器时会发现有很多拦截器都带参数,当然。我们自己做的拦截器也可以加上同样的参数。有两个参数比较常用,这两个参数是includeMethods和excludeMethods,其中includeMethods指定了拦截器要调用的Action类的执行方法(默认是execute),也就是说,只有在includeMethods中指定的方法才会被Struts2调用,而excludeMethods恰恰相反,在这个参数中指定的执行方法不会被Struts2调用。如果有多个方法,中间用逗号(,)分隔。在Struts2中提供了一个抽象类来处理这两个参数。这个类如下:

com.opensymphony.xwork2.interceptor.MethodFilterInterceptor

如有继承于这个类的拦截器类都会自动处理includeMethods和excludeMethods参数,如下面的拦截器类所示:

  1. package interceptor;  
  2.  
  3. import com.opensymphony.xwork2.ActionInvocation;  
  4. import com.opensymphony.xwork2.interceptor.*;  
  5.  
  6. public class MyFilterInterceptor extends MethodFilterInterceptor  
  7. {  
  8.     private String name;  
  9.     public String getName()  
  10.     {  
  11.         return name;  
  12.     }  
  13.     public void setName(String name)  
  14.     {  
  15.         this.name = name;  
  16.     }  
  17.     @Override 
  18.     protected String doIntercept(ActionInvocation invocation) throws Exception  
  19.     {  
  20.         System.out.println("doIntercept");  
  21.         System.out.println(name);  
  22.         return invocation.invoke();  
  23.     }  
  24. }  

MethodFilterInterceptor的子类需要实现doIntercept方法(相当于Interceptor的intercept方法),如上面代码所示。在上面的代码中还有一个name属性,是为了读取拦截器的name属性而设置的,如下面的配置代码所示:

  1. < ?xml version="1.0" encoding="UTF-8" ?> 
  2. < !DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd"> 
  5. < struts> 
  6.     < package name="demo" extends="struts-default" namespace="/test"> 
  7.         < interceptors> 
  8.             < interceptor name="method" class="interceptor.MultiMethodInterceptor" /> 
  9.                 < interceptor name="filter" 
  10.                     class="interceptor.MyFilterInterceptor"> 
  11.                     < param name="includeMethods">abcd< /param> 
  12.                     < param name="name">中国< /param> 
  13.                 < /interceptor> 
  14.                 < interceptor-stack name="methodStack"> 
  15.                     < interceptor-ref name="method" /> 
  16.                     < interceptor-ref name="filter" /> 
  17.                     < interceptor-ref name="defaultStack" /> 
  18.                 < /interceptor-stack> 
  19.         < /interceptors> 
  20.  
  21.         < action name="interceptor" class="action.InterceptorAction" method="abcd"> 
  22.             < interceptor-ref name="methodStack" /> 
  23.         < /action> 
  24.     < /package> 
  25. < /struts> 

再次访问http://localhost:8080/struts2/test/ddd.action?action=test, Struts2就会调用MyFilterInterceptor的doIntercept方法来输出name属性值。如果将上面的includeMethods参数值中的abcd去掉,则Action类的abcd方法不会被执行。

【编辑推荐】

  1. Struts2教程:拦截器概述
  2. Struts2教程:上传任意多个文件
  3. Struts2教程:在Action类中获得HttpServletResponse对象
  4. Struts2教程:使用Validation框架验证数据
  5. Struts2教程:使用validate方法验证数据
责任编辑:yangsai 来源: BlogJava
相关推荐

2009-02-04 14:45:06

2009-06-25 15:54:42

Struts2教程拦截器

2009-02-04 14:19:38

2009-06-04 08:01:25

Struts2拦截器原理

2009-06-25 15:11:28

Struts2教程Struts2程序

2009-02-04 10:51:07

2009-06-03 14:19:34

Struts2Guice

2009-06-25 16:04:30

2011-04-28 09:52:04

Struts2

2009-06-25 15:26:25

Struts2教程struts.xml常

2009-02-04 15:04:13

2009-06-25 15:50:03

Struts2教程上传任意多个文件

2010-01-06 14:36:04

JSON插件

2009-07-08 17:02:11

JDK实现调用拦截器

2009-02-04 11:37:15

2011-11-21 14:21:26

SpringMVCJava框架

2009-07-29 09:54:34

struts2和str

2012-04-25 10:14:40

JavaStruts

2009-06-25 15:33:12

Struts2教程使用validate验证数据

2009-06-25 15:37:12

Struts2教程Validation框
点赞
收藏

51CTO技术栈公众号