struts2的结构图:

代码实现:

组织结构:

主要代码:

package cn.itcast.config;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader; import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* Created by zhen on 2017-08-04.
* 读取struts.xml配置信息
*/
public class ConfigurationManager {
private static final Logger logger = Logger.getLogger(ConfigurationManager.class); //读取Interceptor
public static List<String> getInterceptors(){
List<String> interceptors = null;
SAXReader saxReader = new SAXReader();
InputStream inputStream = ConfigurationManager.class.getResourceAsStream("/struts.xml");
Document document = null;
try {
document = saxReader.read(inputStream);
} catch (DocumentException e) {
logger.error(e.getMessage());
throw new RuntimeException("配置文件解析异常" ,e);
}
String xpath = "//interceptor";
List<Element> list = document.selectNodes(xpath);
if(list != null && list.size() > 0){
interceptors = new ArrayList<String>();
for(Element ele: list){
String className = ele.attributeValue("class");
interceptors.add(className);
}
}
return interceptors;
} //读取Constant
public static String getConstant(String name){
String value = null;
SAXReader saxReader = new SAXReader();
InputStream is = ConfigurationManager.class.getResourceAsStream("/struts.xml");
Document document = null;
try {
document = saxReader.read(is);
} catch (DocumentException e) {
logger.error(e.getMessage());
throw new RuntimeException("配置文件解析异常" ,e);
}
String xPath = "//constant[@name='" + name + "']";
List<Element> ele = document.selectNodes(xPath);
if(ele != null && ele.size() > 0){
value = ele.get(0).attributeValue("value");
}
return value;
} //读取Action
public static Map<String, ActionConfig> getActions(){
Map<String, ActionConfig> actions = null;
SAXReader saxReader = new SAXReader();
InputStream is = ConfigurationManager.class.getResourceAsStream("/struts.xml");
Document document = null;
try {
document = saxReader.read(is);
} catch (DocumentException e) {
logger.error(e.getMessage());
throw new RuntimeException("配置文件解析异常" ,e);
}
String xPath = "//action";
List<Element> list = document.selectNodes(xPath);
if(list != null && list.size() > 0){
actions = new HashMap<String, ActionConfig>();
for(Element element : list){
ActionConfig actionConfig = new ActionConfig();
String name = element.attributeValue("name");
String method = element.attributeValue("method");
String className = element.attributeValue("class");
Map<String, String> results = null;
List<Element> resultElements = element.elements("result");
if(resultElements != null && resultElements.size() > 0){
results = new HashMap();
for(Element ele: resultElements){
String resultName = ele.attributeValue("name");
String resultValue = ele.getTextTrim();
results.put(resultName, resultValue);
}
}
actionConfig.setName(name);
actionConfig.setMethod(method == null || method.trim().equals("") ? "execute" : method.trim());
actionConfig.setClassName(className);
actionConfig.setResults(results);
actions.put(name, actionConfig);
}
}
return actions;
} }
package cn.itcast.invocation;

import cn.itcast.config.ActionConfig;
import cn.itcast.context.ActionContext;
import cn.itcast.interceptor.Interceptor;
import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; /**
* Created by zhen on 2017-08-06.
*/
public class ActionInvocation {
private static final Logger logger = Logger.getLogger(ActionInvocation.class);
private Iterator<Interceptor> interceptors;
private Object action;
private ActionConfig actionConfig;
private ActionContext actionContext;
private String resultUrl; public ActionContext getActionContext() {
return actionContext;
} public ActionInvocation(List<String> classNames, ActionConfig actionConfig, HttpServletRequest request, HttpServletResponse response){
//装载Interceptor链
if(classNames != null && classNames.size() > 0){
List<Interceptor> interceptorList = new ArrayList<Interceptor>();
for(String className : classNames){
try {
Interceptor interceptor = (Interceptor) Class.forName(className).newInstance();
interceptor.init();
interceptorList.add(interceptor);
} catch (Exception e) {
logger.error(e.getMessage());
throw new RuntimeException("创建Interceptor失败,Interceptor Name:" + className ,e);
}
}
interceptors = interceptorList.iterator();
} //准备action实例
this.actionConfig = actionConfig;
try {
action = Class.forName(actionConfig.getClassName()).newInstance();
} catch (Exception e) {
logger.error(e.getMessage());
throw new RuntimeException("创建Action实例失败!" + actionConfig.getClass(), e);
} //准备数据中心
actionContext = new ActionContext(request, response, action);
} public String invoke(){
if(interceptors != null && interceptors.hasNext() && resultUrl == null){
Interceptor interceptor = interceptors.next();
resultUrl = interceptor.invoke(this);
}else{
try{
Method executeMethod = Class.forName(actionConfig.getClassName()).getMethod(actionConfig.getMethod());
resultUrl = (String) executeMethod.invoke(action);
}catch(Exception ex){
logger.error(ex.getMessage());
throw new RuntimeException("您配置的action方法不存在" + actionConfig.getClassName());
}
}
return resultUrl;
}
}
package cn.itcast.filter;

import cn.itcast.config.ActionConfig;
import cn.itcast.config.ConfigurationManager;
import cn.itcast.context.ActionContext;
import cn.itcast.invocation.ActionInvocation;
import org.apache.log4j.Logger;
import org.junit.Test; import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map; /**
* Created by zhen on 2017-08-06.
*/
public class StrutsPrepareAndExecuteFilter implements Filter {
private static final Logger logger = Logger.getLogger(StrutsPrepareAndExecuteFilter.class);
private List<String> interceptorClassNames;
private String extension;
private Map<String, ActionConfig> actionConfigs; public void init(FilterConfig filterConfig) throws ServletException {
//装载配置信息
interceptorClassNames = ConfigurationManager.getInterceptors();
extension = ConfigurationManager.getConstant("struts.action.extension");
actionConfigs = ConfigurationManager.getActions();
} public static void main(String[] args){
Logger logger = Logger.getLogger(StrutsPrepareAndExecuteFilter.class);
} public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//执行
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse; String urlPath = request.getRequestURI();
if(!urlPath.endsWith(extension)){
filterChain.doFilter(request, response);
return;
}
String actionName = urlPath.substring(urlPath.lastIndexOf("/") + 1).replace("." + extension, "");
ActionConfig actionConfig = actionConfigs.get(actionName);
if(actionConfig == null){
throw new RuntimeException("找不到对应的action!" + actionName);
}
ActionInvocation actionInvocation = new ActionInvocation(interceptorClassNames, actionConfig, request, response);
String result = actionInvocation.invoke();
String dispatcherPath = actionConfig.getResults().get(result);
if(dispatcherPath == null || "".equals(dispatcherPath)){
throw new RuntimeException("找不到对应的返回路径!");
}
request.getRequestDispatcher(dispatcherPath).forward(request, response);
ActionContext.tl.remove();
} public void destroy() { }
}

写后感想:

struts2模拟

1、关注点分离思想。类似java中的解耦合,插拔。将功能拆分成各个拦截器实现。拦截器运行过程中拼接出想要的功能。
2、MVC思想。 filter-C Action-M jsp_url-V 需要掌握知识:
XML解析,Xpath表达式(dom4j)
Servlet技术
java内省(BeanUtils)
ThreadLocal线程本地化类
递归调用 需要补充的知识:
dom4j解析
xpath语法
获取资源文件路径 理解:
对于值栈的模拟不要拘泥于数组,也可以使用现有的类进行封装,比如使用ArrayList模拟。
经常递归调用使用的局部变量可以放在循环外或者说是方法外。

项目路径:

https://github.com/gzdx/MyStruts2.git

传智:自己简单实现一个struts2框架的demo的更多相关文章

  1. 08_传智播客iOS视频教程_Foundation框架

    比如产生随机数.这个功能要你写吗?不用,因为苹果已经写好了.后面想开发一个ios程序,往界面上放一个按钮,实际上这个按钮不用你写别人已经写好了,你就拿过来拖一下就可以了. 框架是1个功能集 苹果或者第 ...

  2. 第一个struts2框架

    编写步骤: 1.导入有关的包. 2.编写web.xml文件 3.写Action类 4.编写jsp 5.编写struts.xml web.xml <?xml version="1.0&q ...

  3. 利用jdbc简单封装一个小框架(类似DBUtils)

    利用jdbc写的一个类似DBUtils的框架 package com.jdbc.orm.dbutils; import java.io.IOException; import java.io.Inpu ...

  4. 简单创建一个完整的struts2框架小程序

    要完成一个struts2框架的搭建, 1.首先应该从官网上下载最新的jar包,网络连接:http://struts.apache.org/download.cgi#struts2514.1,选择下载F ...

  5. Struts2框架之类型转换 --Struts2框架

    Struts2框架实现了大多数常见的用于类型转换的转换器,开发人员不用自己编写类型转换代码,就可以实现数据类型的转换.下面一个Struts2框架类型转换的简单事例, 本例可在使用validate()方 ...

  6. struts2框架 转载 精华帖

    一.Struts2简介 参考<JavaEE 轻量级框架应用与开发—S2SH> Struts框架是流行广泛的一个MVC开源实现,而Struts2是Struts框架的新一代产品,是将Strut ...

  7. 搭建一个简单struts2框架的登陆

    第一步:下载struts2对应的jar包,可以到struts官网下载:http://struts.apache.org/download.cgi#struts252 出于学习的目的,可以把整个完整的压 ...

  8. 搭建一个简单的Struts2框架

    1  创建一个web项目. 2 导入必要的JAR文件. 放在WEB-INF下lib包里. 3 添加web.xml配置,添加启动配置. <?xml version="1.0" ...

  9. 关于在Struts2框架下实现文件的上传功能

    struts2的配置过程 (1)在项目中加入jar包 (2)web.xml中filter(过滤器)的配置 <?xml version="1.0" encoding=" ...

随机推荐

  1. python 面向对象· self 讲解

    self就是参数 以形参形式 5.self是什么鬼? self是一个python自动会给传值的参数 那个对象执行方法,self就是谁. obj1.fetch('selec...') self=obj1 ...

  2. 详解PHP实现定时任务的五种方法

    这几天需要用PHP写一个定时抓取网页的服务器应用. 在网上搜了一下解决办法, 找到几种解决办法,现总结如下. 定时运行任务对于一个网站来说,是一个比较重要的任务,比如定时发布文档,定时清理垃圾信息等, ...

  3. c primer plus(五版)编程练习-第七章编程练习

    1.编写一个程序.该程序读取输入直到遇到#字符,然后报告读取的空格数目.读取的换行符数目以及读取的所有其他字符数目. #include<stdio.h> #include<ctype ...

  4. Grid Search学习

    转自:https://www.cnblogs.com/ysugyl/p/8711205.html Grid Search:一种调参手段:穷举搜索:在所有候选的参数选择中,通过循环遍历,尝试每一种可能性 ...

  5. Selenium IDE的一些操作

    1.运行速度过快时,可能出现找不到元素的情况,影响运行结果,将速度调慢慢一些,就可以运行成功. 如果为其他情况找不到元素,则需要另外找原因,有可能元素定位有问题,有可能无该元素. 2.导出录制的脚本为 ...

  6. MySql数据库批量备份命令

    rd d:\mysql_data-BAK /s /qmd d:\mysql_data-BAKxcopy d:\mysql_data d:\mysql_data-BAK /e

  7. 史上最全的MonkeyRunner自动化测试从入门到精通(3)

    原文地址https://blog.csdn.net/liu_jing_hui/article/details/60956088 MonkeyRunner复杂的功能开始学习 (1)获取APK文件中ID的 ...

  8. Broken pipe错误原因

      这个异常是由于以下几个原因造成. 1.客户端再发起请求后没有等服务器端相应完,点击了stop按钮,导致服务器端接收到取消请求.  通常情况下是不会有这么无聊的用户,出现这种情况可能是由于用户提交了 ...

  9. smarty简单语法

    什么是smarty及其安装 Smarty是一个php模板引擎,它分开了逻辑程序和外在的内容,提供了一种易于管理的方法. Smarty要求web服务器运行php4.0.6和以上版本. smarty安装需 ...

  10. SpringBoot基础的使用

    springboot的基础使用 和 内部原理 高级使用整合 进行web开发 springboot 看下spring的所有项目:https://spring.io/projects 等等 就不一一介绍了 ...