前些天一直在寫這個架構,現在放出源碼!
主要功能:
1、自動將表單封裝成對象(類似Struts2)
2、自動根據對象產生增刪改查sql語句(類似hibernate)
3、支援Spring動態注入,可以把自訂的Action 交給Spring去進行管理
4、自訂的tab標籤庫
5、支援偽靜態功能
偽靜態實現,可以用Regex!~
這個架構,差不多就是一個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){//用Regex進行驗證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="";} //id String 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;}}