设为首页 加入收藏

TOP

Struts2拦截器模拟
2015-08-31 21:25:28 来源: 作者: 【 】 浏览:168
Tags:Struts2 拦截 模拟

前言:


接触Struts2已经有一段时间,Student核心内容就是通过拦截器对接Action,实现View层的控制跳转。本文根据自身理解对Struts2进行一个Java实例的模拟,方便大家理解!


示意图


通过以上简单的示意图,我们可以看到Struts2将ServletAPI与业务处理分离,让开发者能够在用户向客户端发送请求的时候通过拦截机制更好的进行业务层处理,提高开发效率。下面我们就通过几个Java类模拟Struts2拦截器的实现。


拦截原理



代码设计:


?1ActionInvocation


package com.simulink;


import java.util.ArrayList;
import java.util.List;


public class AntionInvocation {


? ? Action a = new Action();
? ? int index = -1;
? ? List interceptors = new ArrayList();


? ? public AntionInvocation() {
? ? ? ? interceptors.add(new FirstInterceptor());
? ? ? ? interceptors.add(new SecondInterceptor());
? ? }


? ? public void invoke() {
? ? ? ? index++;
? ? ? ? // System.out.println("index:" + index);
? ? ? ? if (index >= this.interceptors.size()) {
? ? ? ? ? ? a.execute();
? ? ? ? } else {
? ? ? ? ? ? this.interceptors.get(index).intercept(this);
? ? ? ? }
? ? }


}


?FirstInterceptor类


package com.simulink;


public class FirstInterceptor implements Interceptor {


? ? @Override
? ? public void intercept(AntionInvocation invocation) {
? ? ? ? System.out.println(-1);
? ? ? ? invocation.invoke();
? ? ? ? System.out.println(1);
? ? }


}


?SecondInterceptor类


package com.simulink;


public class SecondInterceptor implements Interceptor {


? ? @Override
? ? public void intercept(AntionInvocation invocation) {
? ? ? ? System.out.println(-2);
? ? ? ? invocation.invoke();
? ? ? ? System.out.println(2);
? ? }


}


?Action类


package com.simulink;


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


?5测试类Main


package com.simulink;


public class Main {


/**
* @param args
*/
public static void main(String[] args) {
new AntionInvocation().invoke();
}


}


输出结果:


后记:接触过WebWork的朋友应该会发觉struts2跟其很相似,实际上Struts2就是Struts1和WebWork的结合体。其主要技术大部分来自WebWork!


以上内容纯属个人学习总结,不代表任何团体或单位。若有理解不到之处请见谅!


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java实现本地 fileCopy 下一篇Elixir: 编程语言的未来

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: