前言:

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

输出结果:

-
-
execute!

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

最新文章

  1. MySQL 显示命令
  2. 海边直播目标2017全国初中数学竞赛班课堂测试题解答-The Final
  3. 【转】利用optimize、存储过程和系统表对mysql数据库表进行批量碎片清理释放表空间
  4. reactjs入门到实战(一)---- hello world例子
  5. mysql中case用法
  6. java条件选择学习
  7. C#_delegate - 调用列表
  8. poj 2151
  9. 【Gzip】
  10. HDU_2553——n皇后问题,作弊
  11. npm ERR! Error: socket hang up
  12. Python -- OOP高级 -- 元类
  13. Angular(2+) 国际化方案(ngx-translate)
  14. 洛谷P3369 【模板】普通平衡树(Treap/SBT)
  15. HI258摄像头旋转配置问题
  16. windows快捷键十八式(win10)
  17. 【js课设】电子画板01
  18. ie8遇到的那些事
  19. JSP基础知识➣Cookie和Session(五)
  20. 【转载】webstorm-前端javascript开发神器中文教程和技巧分享

热门文章

  1. css3 @font-face设置嵌入字体
  2. 【WPF】TextBox样式重写注意事项
  3. left join 条件区别
  4. Python2.5-原理之模块
  5. WPFProgressBarAndSlider随位置显示Value
  6. 从零开始,将ASP.NET Core部署到Linux生产环境
  7. Android Stduio统计项目的代码行数
  8. (十七)迭代器模式详解(foreach的精髓)
  9. 个人觉得目前 最好用的Taobao API的NodeJS封装
  10. [BZOJ1061][Noi 2008]志愿者招募(网络流)