传智:自己简单实现一个struts2框架的demo
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的更多相关文章
- 08_传智播客iOS视频教程_Foundation框架
比如产生随机数.这个功能要你写吗?不用,因为苹果已经写好了.后面想开发一个ios程序,往界面上放一个按钮,实际上这个按钮不用你写别人已经写好了,你就拿过来拖一下就可以了. 框架是1个功能集 苹果或者第 ...
- 第一个struts2框架
编写步骤: 1.导入有关的包. 2.编写web.xml文件 3.写Action类 4.编写jsp 5.编写struts.xml web.xml <?xml version="1.0&q ...
- 利用jdbc简单封装一个小框架(类似DBUtils)
利用jdbc写的一个类似DBUtils的框架 package com.jdbc.orm.dbutils; import java.io.IOException; import java.io.Inpu ...
- 简单创建一个完整的struts2框架小程序
要完成一个struts2框架的搭建, 1.首先应该从官网上下载最新的jar包,网络连接:http://struts.apache.org/download.cgi#struts2514.1,选择下载F ...
- Struts2框架之类型转换 --Struts2框架
Struts2框架实现了大多数常见的用于类型转换的转换器,开发人员不用自己编写类型转换代码,就可以实现数据类型的转换.下面一个Struts2框架类型转换的简单事例, 本例可在使用validate()方 ...
- struts2框架 转载 精华帖
一.Struts2简介 参考<JavaEE 轻量级框架应用与开发—S2SH> Struts框架是流行广泛的一个MVC开源实现,而Struts2是Struts框架的新一代产品,是将Strut ...
- 搭建一个简单struts2框架的登陆
第一步:下载struts2对应的jar包,可以到struts官网下载:http://struts.apache.org/download.cgi#struts252 出于学习的目的,可以把整个完整的压 ...
- 搭建一个简单的Struts2框架
1 创建一个web项目. 2 导入必要的JAR文件. 放在WEB-INF下lib包里. 3 添加web.xml配置,添加启动配置. <?xml version="1.0" ...
- 关于在Struts2框架下实现文件的上传功能
struts2的配置过程 (1)在项目中加入jar包 (2)web.xml中filter(过滤器)的配置 <?xml version="1.0" encoding=" ...
随机推荐
- Git学习-->GitLab如何修改时区?
一.背景 今天有同事在GitLab上查看时间的时候,发现GitLab上显示的时间和提交的时间不一致. 本地时间现在为:2017-11-28 11:43 查看本地代码提交的时间为:2017-11-28 ...
- Java char 和 String 的区别: 字符编码及其存储
一. ASCII码 上个世纪60年代,美国制定了一套字符编码,对英语字符与二进制位之间的关系,做了统一规定.这被称为ASCII码,一直沿用至今.一个字节(8bit)一共 可以用来表示256种不同的状态 ...
- MVC模式:python案例
quotes = ('A man is not complete until he is married. Then he is finished.', 'As I said before, I ne ...
- PAT 1043 Is It a Binary Search Tree[二叉树][难]
1043 Is It a Binary Search Tree(25 分) A Binary Search Tree (BST) is recursively defined as a binary ...
- Hadoop 编写WordCount
本文发表于本人博客. 前面几次讲了关于Hadoop的环境搭建.HDFS操作,今天接着继续.本来Hadoop源码中就有一个例子WordCount,但是今天我们来自己实现一个加深对这个Mapper.Red ...
- SQL group by的使用
①定义 "group by" 从字面上理解是根据“by"指定的规则对数据进行分组 ②简单示例 ③group by 中的select字段是受限制的 select指定的字段要 ...
- 微信小程序:JS 交互逻辑
微信小程序:JS 交互逻辑 一.JS 交互逻辑 一个服务仅仅只有界面展示是不够的,还需要和用户做交互:响应用户的点击.获取用户的位置等等.在小程序里边,我们就通过编写 JS 脚本文件来处理用户的操作. ...
- OpenVAS安装过程
OpenVAS安装过程 安装过程 检查安装状况 命令行下输入opensav-check-setup,显示错误NO CA certificate file,并显示解决方法 创建证书 输入命令openva ...
- ubuntu14.04安装CUDA8.0
ubuntu安装CUDA 因为深度学习需要用到CUDA,所以写篇博客,记录下自己安装CUDA 的过程. 1 安装前的检查 安装CUDA之前,首先要做一些事情,检查你的机器是否可以安装CUDA. 1.1 ...
- Docker 安装&基本操作
Docker 安装 Docker 中的三个概念:镜像,容器,仓库 镜像(image):Docker 镜像就是一个只读的模板,镜像可以用来创建 Docker 容器.Docker 提供了一个很简单的机制来 ...