winter framework 源码 SSH最精简的实现

2024-05-13 20:08

本文主要是介绍winter framework 源码 SSH最精简的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前些天一直在写这个框架,现在放出源码!

主要功能:

1、自动将表单封装成对象(类似Struts2)

2、自动根据对象产生增删改查sql语句(类似hibernate)

3、支持Spring动态注入,可以把自定义的Action 交给Spring去进行管理

4、自定义的tab标签库 

5、支持伪静态功能

伪静态实现,可以用正则表达式!~

这个框架,差不多就是一个SSH最精简的实现。

配置非常灵活简单,比起三大框架来说,容易多了,而且包就一个而已,非常的小!

包和类:

org.pan.code 这是核心类的包

主要的类:

过滤器-转发控制器-Action管理器-字段类型转换器-Spring支持类-JDBC支持类-SQL创建类

主要的配置文件是:request.xml


百度网盘下载地址:http://pan.baidu.com/share/link?shareid=467157&uk=470382596

Q:599194993

有兴趣的联系我,一起完善!~

附上部分源代码:

最核心的代码,Action管理器:


package org.pan.code;import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.pan.convetor.FieldConvertor;
import org.pan.exception.InitializeActionException;
import org.pan.support.ServletActionContent;
import org.pan.util.MethodsUitl;
import org.pan.util.StringUitl;/*** 请求request请求数据 调用对应的类去进行处理* @author Pan**/
public class ActionManage {private HttpServletRequest request;		//请求对象private HttpServletResponse response;	//响应对象private Map<String, Object> map=new HashMap<String, Object>();		//map对象private String result;		//返回类型private String classPath;	//类的路径private String methodName;		//需要操作的方法private Object bean;			//对象的实例 可以是从Spring中获取到的public void setMethodName(String methodName) {this.methodName = methodName;}public String getMethodName() {return methodName;}public String getResult() {return result;}private Map<String, Object> getMap() {return map;}public ActionManage(Object bean,HttpServletRequest request,HttpServletResponse response,String classPath,String methodName){this.request=request;this.response=response;this.classPath=classPath;this.methodName=methodName;this.bean=bean;invokeMap();	//将请求的值放入maptry {init();	//初始化} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}		}/*** 将请求的值放入map*/private void invokeMap(){Iterator it=request.getParameterMap().entrySet().iterator();while (it.hasNext()) {Map.Entry entry=(Map.Entry)it.next();String key=entry.getKey().toString();String value=StringUitl.getStringArray((String[])entry.getValue());map.put(key, value);}}/*** 将相关对象设置到用户的Action中* @throws InitializeActionException * @throws NoSuchMethodException * @throws SecurityException * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */private void init() throws Exception{//获取类对象Class class1=null;Object object=null;try{
//			if(this.bean!=null){object=bean;class1=bean.getClass();}else{class1=Class.forName(classPath);//初始化对象object=class1.newInstance();System.out.println("初始化对象");}}catch (Exception e) {System.err.println(e);throw new InitializeActionException();}//给对象设置字段参数initField(class1,object);//调用方法this.result=invokeMethod(class1, object);}/*** 初始化字段*/private void initField(Class class1,Object object) throws Exception{//获取字段集合Field[] fields=class1.getDeclaredFields();//获取方法集合Method [] methods=class1.getDeclaredMethods();for (Field field : fields) {String name=(String)map.get(field.getName());//给指定赋值String MethodName="set"+StringUitl.capitalize(field.getName());if(MethodsUitl.exist(methods,MethodName)){field.setAccessible(true);//field.set(object, map.get(field.getName()));Object value=map.get(field.getName());if(value!=null){FieldConvertor.convertor(object, field, value.toString());}}}}/*** 调用方法*/private String invokeMethod(Class class1,Object object) throws Exception{//创建ServletActionContent实例对象ServletActionContent servlet=new ServletActionContent();servlet.setRequest(request);servlet.setResponse(response);servlet.setSession(request.getSession());//创建参数类型Class parameter[]=new Class[]{ServletActionContent.class};Method method=class1.getMethod("setServletActionContent", parameter);//参数值Object obj[]=new Object[]{servlet};method.invoke(object, obj);	//操作方法//调用execute 方法//Method execute=class1.getMethod("execute", new Class[0]);Method execute=class1.getMethod(this.methodName, new Class[0]);Object type=execute.invoke(object, new Class[0]);return type.toString();	//设置返回类型}}

请求管理器:

package org.pan.controller;import java.util.List;import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.pan.bean.Request;
import org.pan.bean.Result;
import org.pan.bean.SpringBean;
import org.pan.code.ActionManage;
import org.pan.code.Configuration;
import org.pan.spring.SpringBeanFactory;
import org.pan.support.ActionSupport;
import org.pan.util.ResultUitl;/*** 请求控制器* @author Pan**/
public class RequestController {private HttpServletRequest request;private HttpServletResponse response;private FilterChain chain;public RequestController(ServletRequest request,ServletResponse response,FilterChain chain){this.request=(HttpServletRequest)request;this.response=(HttpServletResponse)response;this.chain=chain;}/*** 处理请求*/public void doFilter() throws Exception{String filepath=request.getServletPath().substring(1);	//当前这个文件的名称//通过配置文件得到跳转对象和一些操作的方法Configuration configuration=new Configuration(request);System.out.println("filepath:"+filepath);//伪静态Request rt=configuration.findByLike(filepath);if(rt==null){System.out.println(rt);System.out.println("error:"+configuration.find(filepath));rt=configuration.find(filepath);			}//如果rt还是null 就直接跳过不处理if(rt==null){chain.doFilter(request, response);return ;}//如果没有配置类路径,就当作转发器使用直接转发到结果页if(rt.getClassPath()==null||rt.getClassPath()==""){Result rs=ResultUitl.findResult(rt.getResults(), ActionSupport.SUCCESS);if(rs==null){chain.doFilter(request, response);}else{request.getRequestDispatcher(rs.getPath()).forward(request, response);}return;}//Spring supportSpringBeanFactory factory=new SpringBeanFactory(request);Object object=null;if(rt.getId()!=null||rt.getId()!=""){//xml配置中需要开启支持if(SpringBean.getSupport()){object=factory.getBean(rt.getId());}}//用户Action管理器ActionManage actionManage=new ActionManage(object,request,response,rt.getClassPath(),rt.getMethod());String result=actionManage.getResult();//寻找放返回值对应的页面List<Result> results= rt.getResults();String path="";for (Result result2 : results) {if(result2.getName().equals(result)){//得到对应的路径path=result2.getPath();}}//转发到对应的页面if(!path.equals("")){request.getRequestDispatcher(path).forward(request, response);}//上面没有进行处理那就是配置不争取或者面页不存在else{chain.doFilter(request, response);}}}

配置管理器和xml读取:

package org.pan.code;import java.util.List;import javax.servlet.http.HttpServletRequest;import org.pan.bean.Request;
import org.pan.bean.Result;
import org.pan.exception.ReadRequestXmlException;/*** 配置管理器* @author Pan**/
public class Configuration {private List<Request> requests;public Configuration(HttpServletRequest request){XmlRead xmlRead=new XmlRead(request);try {requests=xmlRead.read();} catch (ReadRequestXmlException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** 寻找配置文件中的request节点对象* @param name* @return*/public Request find(String name){for (Request request : requests) {System.out.println("name:"+name+" - "+request.getPage());if(request.getPage().equals(name)){return request;}}return null;}/*** 模糊检索* @param name* @return*/public Request findByLike(String name){//用正则表达式进行验证for (Request request:requests) {System.out.println("findByLike:"+request.getPage()+" - "+name);String reg=request.getPage();String page=name;if(page.matches(reg)){return request;}}return null;}/*** 通过id寻找对象,主要用于url伪静态* @param id* @return*/public Request findById(String id){for (Request request:requests) {System.out.println(request.getPage()+" - "+id);if(request.getId().equals(id)){return request;}}return null;}
}

xml读取:

package org.pan.code;import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;import org.pan.bean.JdbcConnectConfig;
import org.pan.bean.Request;
import org.pan.bean.Result;
import org.pan.bean.SpringBean;
import org.pan.exception.ReadRequestXmlException;
import org.pan.util.ServerUrl;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;/*** 读取xml* @author Pan**/
public class XmlRead {private HttpServletRequest request;//从xml读取出来的请求对象private List<Request> requests=new ArrayList<Request>();public XmlRead(HttpServletRequest request){this.request=request;}public List<Request> read() throws ReadRequestXmlException{//判断文件是否存在String strpath=ServerUrl.getDiskPath(request)+"WEB-INF/request.xml";File file=new File(strpath);if(!file.exists()){throw new ReadRequestXmlException();}DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  try {  DocumentBuilder db = dbf.newDocumentBuilder();  Document doc = db.parse(new FileInputStream(strpath));  Element root = doc.getDocumentElement();  //Action是否由Spring去管理String spring="false";try{spring=doc.getElementsByTagName("spring").item(0).getTextContent();if(spring==null){spring="false";}}catch (Exception e) {spring="false";}finally{SpringBean.setSupport(Boolean.parseBoolean(spring));}//jdbc配置String url="";String driverClass="";String userName="";String password="";NodeList serverslist = doc.getElementsByTagName("request"); for(int i=0;i<serverslist.getLength();i++){Node node=serverslist.item(i);System.out.println(serverslist.getLength());String page=null;try{page=node.getAttributes().getNamedItem("page").getNodeValue();}catch (Exception e) {page="";}//idString id="";try{id=node.getAttributes().getNamedItem("id").getNodeValue();id=id==null?"":id;}catch (Exception e) {id="";}String classPath=null;try{	classPath=node.getAttributes().getNamedItem("class").getNodeValue();if(classPath==null){classPath="";}}catch (Exception e) {classPath="";}String method = null;try{method=node.getAttributes().getNamedItem("method").getNodeValue();if(method==null||method=="null"){method="execute";}}catch (Exception e) {method="execute";}String pretend=null;try{pretend=node.getAttributes().getNamedItem("pretend").getNodeValue();}catch (Exception e) {pretend="false";}Request request=new Request();request.setId(id);request.setPage(page);request.setClassPath(classPath);request.setMethod(method);	//方法名称request.setPretend(Boolean.parseBoolean(pretend));	//伪静态for (int j = 0; j < node.getChildNodes().getLength(); j++) {Node book1 = node.getChildNodes().item(j);if(book1.getNodeType()==Node.ELEMENT_NODE){Result result=new Result();String name=book1.getAttributes().getNamedItem("name").getNodeValue();String path=book1.getTextContent();result.setName(name);result.setPath(path);request.add(result);}}requests.add(request);}} catch (Exception e) {  System.err.println(e);//throw new ReadRequestXmlException();}  return this.requests;}}

Spring 支持模块:

package org.pan.spring;import javax.servlet.http.HttpServletRequest;import org.pan.util.ServerUrl;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;/*** Spring 框架支持类* * @author Pan* */
public class SpringSupport extends ApplicationObjectSupport {private AbstractApplicationContext aac;public SpringSupport(HttpServletRequest request) { // 可以将ApplicationContent.xml文件放在src或者WEB-INF中try {aac = new ClassPathXmlApplicationContext("applicationContext.xml");} catch (Exception e) {}if (aac == null) {aac = new FileSystemXmlApplicationContext(ServerUrl.getDiskPath(request)+ "/WEB-INF/applicationContext.xml");}}public Object getBean(String bean) {try {return aac.getBean(bean);} catch (Exception e) {System.err.println(e);return null;}}}

Spring bean 工厂:

package org.pan.spring;import javax.servlet.http.HttpServletRequest;/*** Spring Bean Factory* * @author Pan* */
public class SpringBeanFactory extends SpringSupport {public SpringBeanFactory(HttpServletRequest request) {super(request);// TODO Auto-generated constructor stub}public Object findBean(String id) {Object object = null;try {object = getBean(id);} catch (Exception e) {//Do not display error}return object;}}

SQL语句创建:

package org.pan.sql.create;import java.lang.reflect.Field;
import java.lang.reflect.Method;import org.pan.exception.FieldNullException;
import org.pan.util.StringUitl;
/*** this the create sql code util* @author Pan**/
public class SqlCodeCreate {private Object object;public SqlCodeCreate(Object object) {this.object = object;}/*** create update sql code* * @return* @throws Exception*/public String updateSql() throws Exception {Class cl = object.getClass();String table = cl.getSimpleName(); // 类名=表名String sql = "update [" + table + "] set ";// 获得字段名// 生成字段Field[] fields = cl.getDeclaredFields();Field id = cl.getDeclaredField("id");Method idMethod = cl.getMethod("getId", new Class[0]);Object ivalue = idMethod.invoke(object, new Class[0]);if (ivalue == null) {throw new FieldNullException("Field :id ,not null!");}for (Field field : fields) {if (field.getName().equals("id"))continue;String m = "get" + StringUitl.capitalize(field.getName());Method method = cl.getMethod(m, new Class[0]);Object o = method.invoke(object, new Class[0]);if (o != null)sql += "[" + field.getName() + "] = '" + o + "',";}sql = StringUitl.removeEndChar(sql);Method method = cl.getMethod("getId", new Class[0]);sql += " where id = '" + method.invoke(object, new Class[0]) + "'";return sql;}/*** 创建sql语句* * @return* @throws NoSuchMethodException* @throws SecurityException*/public String insertSql(boolean sign) throws Exception {Class cl = object.getClass();String table = cl.getSimpleName(); // 类名=表名String sql = "insert into [" + table + "] ";// 获得字段名String strFileds = "("; // 字段String strValues = ")values("; // 值// 生成字段Field[] fields = cl.getDeclaredFields();// 输出值for (Field field : fields) {String m = "get" + StringUitl.capitalize(field.getName());Method method = cl.getMethod(m, new Class[0]);Object value = method.invoke(object, new Class[0]);// 插入idif (field.getName().equals("id"))continue;if (sign) {if (value == null) {continue;}}strFileds += "[" + field.getName() + "],";strValues += "'" + value + "',";}strFileds = StringUitl.removeEndChar(strFileds);strValues = StringUitl.removeEndChar(strValues) + ");";sql += strFileds + strValues;return sql;}/*** 创建查询语句* * @return* @throws Exception*/public String selectSql() throws Exception {Class cl = object.getClass();String table = cl.getSimpleName();String sql = "select * from [" + table+"]";return sql;}/*** 按条件查询字段,查询所有不为null的字段 传入bool 参数,指定是否用like进行查询* * @return* @throws NoSuchMethodException* @throws SecurityException*/public String seleteFieldSql(boolean like) throws Exception {Class cl = object.getClass();String table = cl.getSimpleName();String sql = "select * from [" + table + "] where 1=1 ";Field[] fields = cl.getDeclaredFields();for (Field field : fields) {String fname = field.getName();Method method = cl.getMethod("get" + StringUitl.capitalize(fname),new Class[0]);Object o = method.invoke(object, new Class[0]);if (o != null) {if (!like) {sql += "and [" + fname + "] = '" + o + "' ";} else {sql += "and [" + fname + "] like '%" + o + "%' ";}}}return sql;}/*** 创建删除语句* @return* @throws Exception*/public String deleteSql() throws Exception{Class cl=object.getClass();String table=cl.getSimpleName();Method method=cl.getMethod("getId", new Class[0]);Object ob=method.invoke(object,new Class[0]);if(ob==null){throw new FieldNullException("Field is null from:id");}String sql="delete ["+table+"] where id='"+ob+"'";return sql;}}


这篇关于winter framework 源码 SSH最精简的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/986697

相关文章

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

OpenCV实现实时颜色检测的示例

《OpenCV实现实时颜色检测的示例》本文主要介绍了OpenCV实现实时颜色检测的示例,通过HSV色彩空间转换和色调范围判断实现红黄绿蓝颜色检测,包含视频捕捉、区域标记、颜色分析等功能,具有一定的参考... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

Nexus安装和启动的实现教程

《Nexus安装和启动的实现教程》:本文主要介绍Nexus安装和启动的实现教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、Nexus下载二、Nexus安装和启动三、关闭Nexus总结一、Nexus下载官方下载链接:DownloadWindows系统根

SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程

《SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程》LiteFlow是一款专注于逻辑驱动流程编排的轻量级框架,它以组件化方式快速构建和执行业务流程,有效解耦复杂业务逻辑,下面给大... 目录一、基础概念1.1 组件(Component)1.2 规则(Rule)1.3 上下文(Conte

MySQL 横向衍生表(Lateral Derived Tables)的实现

《MySQL横向衍生表(LateralDerivedTables)的实现》横向衍生表适用于在需要通过子查询获取中间结果集的场景,相对于普通衍生表,横向衍生表可以引用在其之前出现过的表名,本文就来... 目录一、横向衍生表用法示例1.1 用法示例1.2 使用建议前面我们介绍过mysql中的衍生表(From子句