struts2拦截器

  • 什么是拦截器

拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行,同时也提供了一种可以提取action中可重用部分的方式。在AOP(Aspect-Oriented Programming)中拦截器用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。

Struts2拦截器的实现原理相对简单,当请求struts2的action时,Struts 2会查找配置文件,并根据其配置实例化相对的拦截器对象,然后串成一个列表,最后一个一个地调用列表中的拦截器。

 

  • 拦截器的实现方式

实现 Interceptor 接口,实现 intercept 方法

继承 AbstractInterceptor类( 推荐 ),重写 intercept 方法

 

  • 在struts.xml文件中配置拦截器

一、单个拦截器:name为拦截器的名称,class是编写的拦截器

<!-- 定义的拦截器 -->

<interceptors>

<interceptor name="test" class="com.Interceptor.MyInterceptor"></interceptor>

</interceptors>

二、拦截器栈

<interceptors>

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

        <interceptor-stack name="mystac">

        <interceptor-ref name="test1"></interceptor-ref>

        <interceptor-ref name="test2"></interceptor-ref>

        </interceptor-stack>

</interceptors>

 

  • 拦截器在action中的引用

https://images2015.cnblogs.com/blog/897287/201603/897287-20160311195240085-1552703081.png

index.jsp:登录成功之后的页面!

<global-results>:全局结果集,非法登录则调回原页面!

 

  • 登录测试:

https://images2015.cnblogs.com/blog/897287/201603/897287-20160311195639632-401371127.png

https://images2015.cnblogs.com/blog/897287/201603/897287-20160311195750772-94675419.png