Struts2自定义拦截器

来源:互联网 发布:js中srcelement是什么 编辑:程序博客网 时间:2024/06/05 07:03

拦截器接口

com.opensymphony.xwork2.interceptor.Interceptor,为拦截器的接口,用户的自定义拦截器需要实现此接口。

接口方法(Interceptor)

  • void init();
    • 用于拦截器的初始化。这个方法会在拦截器实例创建完成后自动被调用。因为拦截器是单例的,所以这个方法只会被调用一次。
  • void destroy();
    • 在拦截器要被销毁时被调用。

String intercept(ActionInvocation invocation);

- 每拦截一个请求动作,都会被调用一次。- invocation      代表一个给定Action的执行状态, 拦截器可以从该类的对象里获得与该Action相关联的 Action 对象和 Result 对象。      在完成拦截器自己的任务之后, 拦截器将调用 ActionInvocation 对象的 invoke 方法前进到 Action 处理流程的下一个环节。- return    返回值和Action的返回值作用相同。- 通过ActionInvocation获取Action相关对象
        //ActionProxy中封装了有关Action的对象。        ActionProxy proxy = invocation.getProxy();        //获取Action的名字。        String actionName = proxy.getActionName();        //获取执行Action的方法名。        String actionRunMethodName = proxy.getMethod();        //获取Action的名称空间        String namespace = proxy.getNamespace();

配置拦截器

struts.xml配置:

<struts>    <!-- 包声明 -->    <package name="test" extends="struts-default" namespace="/test">        <interceptors>            <!-- 声明拦截器 -->            <interceptor name="testInterceptor" class="fszaxt.log.user.interceptor.UserIsLoginInterceptor" />            <!-- 定义一个新栈 -->            <interceptor-stack name="testStack">                <!-- 引入默认栈 -->                <interceptor-ref name="defaultStack" />                <!-- 加入自定义拦截器 !!!自定义的拦截器的引用一定要在默认拦截器的下面! -->                <interceptor-ref name="testInterceptor" />            </interceptor-stack>        </interceptors>        <!-- 将拦截器设置为包的默认执行拦截器 -->        <default-interceptor-ref name="testStack" />        <action name="testAction">            <!-- 设置Action执行的拦截器 -->            <interceptor-ref name="defaultStack" />        </action>    </package></struts>

一些struts的自带拦截器

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

0 0