Struts 处理流程及拦截器原理模拟

首先送上官网高清无码架构图:


论述下用户从请求到到达,struts大概的处理过程:

1。首先用户request到达filterDispatcher(web.xml已配置该拦截器),

2。f.ilterDispatcher帮我们创建一个ActionProxy,ActionProxy通过Configuraion Manager读出struts.xml中相应配置信息返回给ActionProxy.

3。ActionProxy拥有一个ActionInvocation实例,接下来通过ActionInvocation调用invoke()方法。

4.在invoke()方法中,先处理interceptor1,再处理interceptor2,3,4,,,最后处理Action

5.然后返回result,再经过Interceptor3,2,1..倒着处理,,,(看出来,拦截器两次拦截的时候,是通过栈实现的)。

6.最后形成HttpServletReponse返回给用户页面。

(ActionMapper主要用于访问struts静态资源,一般用不上,忽略)。


最后模拟一下,ActionInvocation的invoke()方法如何实现拦截过程:

首先写一个Main表示ActionProxy 的一个实例ActionInvocation开始调用invoke()方法了。

public class Main {
	public static void main(String[] args) {
		new ActionInvocation().invoke();
	}
}

接着写Invocation类,并实现invoke方法处理Interceptor:

此处假设此前读到的配置信息中有2个拦截器interceptor需要处理

public class ActionInvocation {
	List<Interceptor> interceptors = new ArrayList<Interceptor>();
	int index = -1;
	Action a = new Action();
	
	public ActionInvocation() {
		this.interceptors.add(new FirstInterceptor());
		this.interceptors.add(new SecondInterceptor());
		
	}
	
	public void invoke() {
		index ++;
		if(index >= this.interceptors.size()) {
			a.execute();
		}else {
			this.interceptors.get(index).intercept(this);
		}
	}
}

实现Interceptor拦截器内部:

public interface Interceptor {
	public void intercept(ActionInvocation invocation) ;
}

public class FirstInterceptor implements Interceptor {
	public void intercept(ActionInvocation invocation) {
		System.out.println(1);
		invocation.invoke();
		System.out.println(-1);
	}

}
public class SecondInterceptor implements Interceptor {

	public void intercept(ActionInvocation invocation) {
		System.out.println(2);
		invocation.invoke();
		System.out.println(-2);
	}

}

模拟一个用户自己创建的Action:

public class Action {
	public void execute() {
		System.out.println("execute!");
	}
}

最后的执行结果如下:


struts中的大多数功能都是用拦截器实现的。。。。拦截器的应用:权限控制。可以控制到类,方法级别,URL地址级别。。。






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值