struts2第十三讲学习笔记,拦截器interceptor的详细讲解

来源:互联网 发布:mpp 文件查看 mac 编辑:程序博客网 时间:2024/06/07 13:31
1.编写一个拦截器Interceptor类,实现Interceptor接口或者继承AbstractInterceptor
2.在struts.xml中配置拦截器
3.在action中引用拦截器,当请求hello.action时,拦截器就会执行


package Interceptor;


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


public class time extends AbstractInterceptor {

//或者public class time implements Interceptor{...}

private static final long serialVersionUID = 1L;


@Override
public String intercept(ActionInvocation interceptor) throws Exception {
long start = System.currentTimeMillis();
String result = interceptor.invoke();//继续执行下去
long end = System.currentTimeMillis();
System.out.println("执行时间为:"+(end-start)+"ms");
return result;
}


}


<struts>

<package name="hello" extends="struts-default" namespace="/">

<!--配置我们的interceptors多个拦截器-->

<interceptors>
<interceptor name="time" class="Interceptor.time"></interceptor>
</interceptors>

<action name="hello" class="action.hello" >

<result>/index.jsp</result>

<!--在action中引用我们的拦截器,带ref的都是引用-->

<interceptor-ref name="time"/>
</action>
</package>


</struts>


拦截器配置详解
1.当引用了自定义拦截器的时候,默认拦截器就不起作用了
2.什么是默认拦截器?默认拦截器在core包中的struts-default.xml中,配置了拦截器栈,里面有非常多的拦截器。如果不引用拦截器,则它即默认拦截器就生效
        在strut-default.xml中  <default-interceptor-ref name="defaultStack"/>

3.当自定义拦截器后,又想使用struts2的默认拦截器,那么需要手动在aciton中引用
<action name="hello" class="action.hello">
<result>/index.jsp</result>
<interceptor-ref name="time">
<interceptor-ref name="defaultStack"/>

</action>
4.当action中的拦截器较多的时候,可以将多个拦截器放入一个拦截器栈,拦截器栈的引用和拦截器一致,在interceptors中写
<interceptor-stack name="myStack">
<interceptor-ref name="time">
<interceptor-ref name="defaultStack">

</interceptor-stack>

    在action中可以引用这个interceptor栈,<interceptor-ref name="myStack"/>

5.当自定义拦截器栈在这个包下所有aciono中都可以使用的时候,可以定义默认拦截器栈,写法顺序interceptors, default-interceptor-ref
<default-interceptor-ref name="myStack">





<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">


<struts>
<package name="hello" extends="struts-default" namespace="/">
<interceptors>
<!-- 拦截器栈的引用和拦截器一致,ref就是引用,不加class -->
<interceptor name="time" class="Interceptor.time"></interceptor>
<interceptor-stack name="myStack">里面有两个引用
<interceptor-ref name="time"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack"/>设计默认的拦截器
<action name="hello" class="action.hello" >
<result>/index.jsp</result>
</action>
</package>


</struts>

原创粉丝点击