Struts2自定义拦截器

2017-10-30  本文已影响0人  小山雀

概述

本文简单介绍如何自定义一个Struts拦截器,但不涉及拦截器基础、原理等其他知识,仅仅只是介绍自定义拦截器的步骤。本人目前的能力只能如此。我是学习Struts2时写的这段文字,请带着怀疑的态度阅读。

详细步骤

创建一个Struts2项目

创建一个HelloWorld项目,上一篇已经介绍过了,不赘述。

创建一个拦截器类

创建拦截器类必须要实现一个Interceptor 接口:

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

该接口中有3个方法:init(),intercept(),destroy()。init方法是初始化拦截器方法;destroy方法是拦截器清理方法;intercept 是拦截器方法,是实现拦截器功能的主要方法。

本例中拦截器继承AbstractInterceptor,使用AbstractInterceptor默认的init和destroy方法,创建MyInterceptor类:

package com.xxx.action;

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

public class MyInterceptor extends AbstractInterceptor{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
          /* let us do some pre-processing */
          String output = "Pre-Processing"; 
          System.out.println(output);

          /* let us call action or next interceptor */
          String result = invocation.invoke();

          /* let us do some post-processing */
          output = "Post-Processing"; 
          System.out.println(output);

          return result;
    }

}

简单的解释一下,String result = invocation.invoke();这行的作用是:如果还有其他拦截器,则调用其他拦截器,如果没有,那么就调用action方法。也就是说,在 invocation.invoke();之前是在调用action之前做的预处理,在 invocation.invoke();之后是对调用action后的结果的处理。

配置拦截器

在strtuts.xml中注册拦截器:

 <interceptors>
        <interceptor name="myinterceptor" class="com.xxx.action.MyInterceptor"/>   
</interceptors>

name是拦截器名,是引用拦截器的标志,class是拦截器的实现类的路径。

在<action>标签下为action配置拦截器:

 <action name="hello" 
            class="com.xxx.action.HelloWorldAction">
            
             <result name="success">/HelloWorld.jsp</result>
            <result name="error">/Erro.jsp</result>
            
            <interceptor-ref name="params"></interceptor-ref>
            <interceptor-ref name="myinterceptor"></interceptor-ref>
            
            
</action>

在<interceptor-ref name="myinterceptor"></interceptor-ref>中填写正确的拦截器名。

部署到服务器运行测试

在服务器中运行即可,最终的项目结构如下:

Paste_Image.png
上一篇 下一篇

猜你喜欢

热点阅读