struts2 拦截器学习笔记01

0.拦截器的作用

用于在Action执行之前或者执行之后,进行拦截,并加入我们自定义的代码,执行相关的操作,是实现AOP的一种策略。


1拦截器在Action之前还是之后执行

主要看invocation.invoke();的位置,在此函数之前的代码为Action代码执行前拦截器会做的,反之,之后的的代码即为Action之后拦截器做的。

后置拦截器示例

package ...interceptor;

import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class UserInterceptor extends AbstractInterceptor {

	public String intercept(ActionInvocation invocation) throws Exception {
		invocation.invoke();
		//
		Action执行之后执行的代码...
		//
	}

}

前置拦截器示例

package ...interceptor;

import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class UserInterceptor extends AbstractInterceptor {

	public String intercept(ActionInvocation invocation) throws Exception {
		//
		Action执行之前执行的代码...
		//
<pre name="code" class="java"><span style="white-space:pre">		</span>invocation.invoke();
}}
 


2拦截器的三种实现方式

2.1实现Interceptor接口

需要实现三个方法:init,destroy,intercept

2.2继承AbstractInterceptor类

实现intercept(ActionInvocation invocation)方法即可

2.3

继承MethodFilterInterceptor类

重写doIntercept()方法


3.基础知识

3.1默认拦截器是在每个Action都会执行拦截的

如:<default-interceptor-ref name="默认拦截器名称"/>

3.2要想只对某个Action拦截的话,可以将该拦截器设置为该Action的拦截器

如:

<action name="login" class="...Login">
<result name="success" type="redirect">patientList.action</result>
<result name="error">/login.jsp</result>
<interceptor-ref name="userInterceptorStack"/>

</action>

3.3上述拦截器可能带来的问题

struts2默认的拦截器功能丢失,因为这样配置之后,就只会执行用户配置的这个拦截器了,解决办法就是加入struts2的默认拦截器

如:

<action name="login" class="...Login">
<result name="success" type="redirect">patientList.action</result>
<result name="error">/login.jsp</result>
<interceptor-ref name="userInterceptorStack"/>

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

</action>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值