你好,游客 登录 注册 搜索
背景:
阅读新闻

Struts2拦截器模拟

[日期:2015-08-01] 来源:Linux社区  作者:SeaSky0606 [字体:大 中 小]

前言:

接触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<Interceptor> interceptors = new ArrayList<Interceptor>();

    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();
}

}

输出结果:

  • -1
  • -2
  • execute!
  • 2
  • 1

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

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

Struts2学习笔记-Value Stack(值栈)和OGNL表达式  http://www.linuxidc.com/Linux/2015-07/120529.htm 

struts2文件上传(保存为BLOB格式) http://www.linuxidc.com/Linux/2014-06/102905.htm

Struts2的入门实例 http://www.linuxidc.com/Linux/2013-05/84618.htm

Struts2实现ModelDriven接口 http://www.linuxidc.com/Linux/2014-04/99466.htm

遇到的Struts2文件下载乱码问题 http://www.linuxidc.com/Linux/2014-03/98990.htm

Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm

Struts2 注解模式的几个知识点 http://www.linuxidc.com/Linux/2013-06/85830.htm

Struts 的详细介绍:请点这里
Struts 的下载地址:请点这里

本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-08/120890.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款