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

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

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

一、拦截器的实现

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

public interface Interceptor extends Serializable   
{  
    void destroy();  
    void init();  
    String intercept(ActionInvocation invocation) throws Exception;  

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

其中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参数值来调用方法的功能,代码如下:

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

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

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

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

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

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

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

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

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

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

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

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

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

在配置上面的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参数,如下面的拦截器类所示:

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

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

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

再次访问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

2009-06-25 15:26:25

Struts2教程struts.xml常

2011-04-28 09:52:04

Struts2

2009-02-04 15:04:13

2009-06-25 15:50:03

Struts2教程上传任意多个文件

2009-02-04 11:37:15

2010-01-06 14:36:04

JSON插件

2009-07-29 09:54:34

struts2和str

2009-02-04 14:00:59

2009-06-25 15:37:12

Struts2教程Validation框

2009-06-25 15:33:12

Struts2教程使用validate验证数据

2012-04-25 10:14:40

JavaStruts

2011-11-21 14:21:26

SpringMVCJava框架
点赞
收藏

51CTO技术栈公众号