Struts2-16 自定义拦截器

一、Struts2拦截器概述

  • 拦截器(Interceptor是 Struts2.0的核心组成部分;
  • Struts2拦截器在访问某个Action方法之前或之后实施拦截;
  • Struts2拦截器是可插拔的,其是拦截器是AOP(面向切面编程)思想的一种实现;
  • Struts2的很多功能都是构建在拦截器基础之上的,如类型转换、国际化、输入验证、文件的上传与下载等;
  • 拦截器栈(Interceptor Stack):将拦截器按一定的顺序联结成一条链,在访问被拦截的方法时, Struts2拦截器链中的拦截器会按其定义顺序被依次调用。

二、Struts2自带拦截器

这里写图片描述
这里写图片描述


三、Interceptor接口

public interface Interceptor extends Serializable {

    /**
     * 该方法将在拦截器被创建后立即被调用,在拦截器的生命周期内只被调用一次;
     * 功能:可以在该方法中对相关资源进行必要的初始化。
     */
    void init();

    /**
     * 每拦截一个请求,该方法就会被调用一次。
     */
    String intercept(ActionInvocation invocation) throws Exception;

    /**
     * 该方法将在拦截器被销毁之前调用,在拦截器的生命周期内也只被调用一次。
     */
    void destroy();
}

 具体说明如下:

  • 每个拦截器都是实现了com.opensymphony.xwork2.interceptor.Interceptor接口的Java类;
  • Struts会依次调用为某个Action而注册的每一个拦截器的interecept()方法;
  • 每次调用interecept()方法,Struts均会传递一个ActionInvocation接口的实例;
  • ActionInvocation接口代表一个给定Action的执行状态,拦截器可以从该类的对象中获得与该Action相关的Action对象和Result对象;
  • 在完成拦截器自己的任务之后,拦截器将调用ActionInvocation对象的invoke()方法前进到Action处理流程的下一个环节;
  • AbstractInterceptor类实现了Interceptor接口,并为init()方法和destroy()方法提供了空白实现。

四、自定义拦截器

4.1 自定义拦截器类

 可以直接实现Interceptor接口或选择继承于AbstractInterceptor抽象类。核心示例代码如下:

package com.qiaobc.struts.interceptors;

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 {

        System.out.println("before invocation.invoke() ...");

        String result = invocation.invoke();

        System.out.println("after invocation.invoke() ...");

        return result;
    }
}
4.2 配置自定义拦截器类

 可以在struts.xml文件中配置自定义的拦截器类,核心配置代码如下:

<interceptors>  
    <interceptor name="test" class="com.qiaobc.struts.interceptors.MyInterceptor"></interceptor>    
</interceptors>

<action name="testToken" class="com.qiaobc.struts.token.TokenAction">
    <interceptor-ref name="test"></interceptor-ref>
    <interceptor-ref name="defaultStack"></interceptor-ref>
    <result>/success.jsp</result>
    <result name="invalid.token">/token-error.jsp</result>
</action>

 注意:在自定义拦截器中可以选择不调用ActionInvocation的invoke()方法,则后续拦截器和Action方法将不会被调用;同时,Struts会渲染自定义拦截器intercept()方法返回值所对应的result。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值