Struts2应用开发详解-15、自定义拦截器

Struts2应用开发详解--15、自定义拦截器

    拦截器在实际开发中经常用到,典型的应用如对全局环境的权限验证。拦截器实现可以体现非常好的封装性,代码也容易维护。

拦截器实现需要如下步骤。

一、实现一个拦截器类

Struts2的拦截器必须实现com.opensymphony.xwork2.interceptor.Interceptor接口和对于方法,如下所示:

1、拦截器实现类

package filter;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class TestInterceptor implements Interceptor {

 public void destroy() {
    // TODO Auto-generated method stub

 }

 public void init() {
    // TODO Auto-generated method stub

 }

 public String intercept(ActionInvocation invocation) throws Exception {
  // TODO Auto-generated method stub

    return invocation.invoke();
 }

}

2、 拦截器栈设置

a、创建拦截器堆栈

     <interceptors>
      <interceptor name="testInter" class="filter.TestInterceptor"></interceptor>
      <interceptor-stack name="testStack">  //新建堆栈名
       <interceptor-ref name="defaultStack"></interceptor-ref> //设置拦截器堆栈,先加载Struts框架栈
       <interceptor-ref name="testInter"></interceptor-ref> //加载自定义拦截器
      </interceptor-stack>      
     </interceptors>

 

b、设置拦截器拦截的Action

<action name="helloworld" class="test.HelloWorldAction">
      <interceptor-ref name="testInter"></interceptor-ref>

      <result name="success">/page/hello.jsp</result>
</action>

c、设置拦截所有包中的action

<default-interceptor-ref name="testStack"></default-interceptor-ref>

 

拦截器的生命周期类似于Servlet的Filter。init()负责创建实例,destroy()负责销毁,而intercept()则类似于doFilter()所有逻辑在该方法中执行。Struts拦截器的内部实现并非基于Servlet的Filter。所以运行机制跟Filter并不相同。

return invocation.invoke();返回一个字符串,该字符串默认返回action方法返回的字符,随后跳转到对应字符串的页面视图。