Struts2拦截指定方法的拦截器

时间:2023-03-10 07:07:19
Struts2拦截指定方法的拦截器

作者:禅楼望月

默认情况下,我们为一个Action配置一个拦截器,该拦截器会拦截该Action中的所有方法,但是有时候我们只想拦截指定的方法。为此,需要使用struts2拦截器的方法过滤特性。

要使用struts2拦截器的方法过滤特性其实也很简单,只需让拦截器的实现类继承com.opensymphony.xwork2.interceptor.MethodFilterInterceptor类。该类是AbstractInterceptor的子类。它重写了AbstractInterceptor类的intercept(ActionInvocation invocation)方法,并提供了protected abstract String doIntercept(ActionInvocation invocation) throws Exception方法。拦截器的实现类只需重写该方法即可。

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.stbc.web.Action.LoginAction;

public class InterceptorHello extends MethodFilterInterceptor {
    private static final long serialVersionUID = -5407269431454126006L;

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        HttpServletRequest request=ServletActionContext.getRequest();
        if(request.getParameter("username").equals("毛爷爷")){
            return "error";
        }else {
            request.setAttribute("datetime", new Date());
            LoginAction action=(LoginAction) invocation.getAction();
            return action.execute();
        }
    }
}

从上面的代码可以看出,我们自定义的拦截指定方法的拦截器和普通的拦截器没有太大的区别,只不过是继承的类和重写的方法不同而已。

那么我们怎么来实现一些方法不拦截而另一些方法拦截呢?

查看MethodFilterInterceptor类的API可知:

Struts2拦截指定方法的拦截器

在Action中配置也很简单,它也是通过反射的技术来实现的。

<package name="loginPackage" extends="struts-default"  namespace="/login">
    <interceptors>
        <interceptor name="interceptormaoyeye" class="test.InterceptorHello">
            <param name="name">你好!</param>
        </interceptor>
    </interceptors>
    <action name="login" class="com.stbc.web.Action.LoginAction">
        <result name="success">welcome.jsp</result>
        <result name="error">welcome.jsp</result>
        <interceptor-ref name="interceptormaoyeye">
            <!-- 这里使用了反射的方法,实际上调用的是拦截器类的setName方法 -->
            <param name="name">覆盖了默认值</param>
            <!-- 有多个方法需要(不)被拦截器拦截,则多个方法名之间用逗号分隔即可。 -->
            <param name="excludeMethods">method1,method2</param>
            <param name="includeMethods">method2,method3</param>
        </interceptor-ref>
    </action>
</package>

上述代码将method2配置为既不给拦截也被拦截,这是struts2以<param name="includeMethods">的为准。

struts2内置的支持方法过滤的拦截器有:

欢迎转载,请注明出处