通过此代码自动生成框架来自动生成Dao层、Service层、Action、JSP以及相关的xml配置文件。
一、准备工作
1.准备测试用的hbm.xml
Users.hbm.xml

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.arimadisp.model"> <class name="Users" table="TUSERS"> <id name="id" column="id_" type="java.lang.Long"> <generator class="native"></generator> </id> <property name="name" type="java.lang.String"> <column name="name_"></column> </property> <property name="password" type="java.lang.String"> <column name="password_"></column> </property> <property name="age" type="java.lang.Integer"> <column name="age_"></column> </property> </class> </hibernate-mapping>
2.准备HibernateTool需要的hibernate.cfg.xml

1 <?xml version='1.0' encoding='utf-8'?> 2 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 3 <hibernate-configuration> 4 <session-factory> 5 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:HIBERBATETOOL</property> 6 <property name="connection.username">scott</property> 7 <property name="connection.password">tiger</property> 8 <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 9 <property name="myeclipse.connection.profile">OracleDriver</property> 10 <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> 11 <property name="show_sql">true</property> 12 <property name="format_sql">true</property> 13 14 <!-- 15 <mapping resource="DocumentCatalog.hbm.xml" /> 16 <mapping resource="DocumentItem.hbm.xml" /> 17 --> 18 <mapping resource="Users.hbm.xml" /> 19 </session-factory> 20 </hibernate-configuration>
3.准备空的Struts.xml

1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> 3 4 <struts> 5 </struts>
4.准备固定格式的applicationContext.xml

1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:p="http://www.springframework.org/schema/p" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-2.5.xsd 10 http://www.springframework.org/schema/tx 11 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 12 http://www.springframework.org/schema/aop 13 http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> 14 15 <import resource="applicationContext-basic.xml"/> 16 <import resource="applicationContext-dao.xml"/> 17 <import resource="applicationContext-action.xml"/> 18 19 </beans>
5.准备Dao层的模版
IDao.java

1 package code.automatic.generation.framework.util; 2 3 import java.sql.SQLException; 4 import java.util.List; 5 6 import org.hibernate.HibernateException; 7 import org.hibernate.Query; 8 import org.hibernate.Session; 9 import org.springframework.orm.hibernate3.HibernateCallback; 10 import org.springframework.orm.hibernate3.HibernateTemplate; 11 12 @SuppressWarnings("unchecked") 13 public abstract class IDao<T> 14 { 15 protected HibernateTemplate hibernateTemplate; 16 17 protected void removeObject(Class<T> clazz, Long id) 18 { 19 T t = (T) this.hibernateTemplate.load(clazz, id); 20 this.hibernateTemplate.delete(t); 21 } 22 23 protected void removeObject(T entity) 24 { 25 this.hibernateTemplate.delete(entity); 26 } 27 28 protected void removeObject(List<T> entities) 29 { 30 this.hibernateTemplate.delete(entities); 31 } 32 33 protected void updateObject(T entity) 34 { 35 this.hibernateTemplate.update(entity); 36 } 37 38 protected void updateObject(Class<T> clazz, Long id) 39 { 40 T t = (T) this.hibernateTemplate.load(clazz, id); 41 this.updateObject(t); 42 } 43 44 protected void updateObjects(List<T> entities) 45 { 46 this.hibernateTemplate.saveOrUpdateAll(entities); 47 } 48 49 protected T findObject(Class<T> clazz, Long id) 50 { 51 T t = (T) this.hibernateTemplate.load(clazz, id); 52 return t; 53 } 54 55 protected T findObjectByHQL(String queryString, String... param) 56 { 57 List<T> t = (List<T>) this.hibernateTemplate.find(queryString, param); 58 if (t != null) 59 { 60 return t.get(0); 61 } 62 return null; 63 } 64 65 protected T findObjectByHQL(String queryString) 66 { 67 List<T> t = (List<T>) this.hibernateTemplate.find(queryString); 68 if (t != null) 69 { 70 return t.get(0); 71 } 72 return null; 73 } 74 75 protected List<T> findObjects(String queryString) 76 { 77 return this.hibernateTemplate.find(queryString); 78 } 79 80 protected List<T> findObjectsByParameters(String queryString, 81 String... param) 82 { 83 return this.hibernateTemplate.find(queryString, param); 84 } 85 86 protected List<T> findObjectsByPages(final String queryString, 87 final String[] params, final int from, final int to) 88 { 89 return this.hibernateTemplate.executeFind(new HibernateCallback() 90 { 91 @Override 92 public Object doInHibernate(Session arg0) 93 throws HibernateException, SQLException 94 { 95 Query query = arg0.createQuery(queryString); 96 for (int i = 0; i < params.length; i++) 97 { 98 query.setString(i, params[i]); 99 } 100 query.setFirstResult(from); 101 query.setMaxResults(to); 102 return query.list(); 103 } 104 105 }); 106 } 107 108 protected List<T> findObjectsByPages(final String queryString, 109 final String param, final int from, final int to) 110 { 111 return this.hibernateTemplate.executeFind(new HibernateCallback() 112 { 113 @Override 114 public Object doInHibernate(Session arg0) 115 throws HibernateException, SQLException 116 { 117 String[] params = { param }; 118 Query query = arg0.createQuery(queryString); 119 for (int i = 0; i < params.length; i++) 120 { 121 query.setString(i, params[i]); 122 } 123 query.setFirstResult(from); 124 query.setMaxResults(to); 125 return query.list(); 126 } 127 128 }); 129 } 130 131 protected void saveObject(T entity) 132 { 133 this.hibernateTemplate.save(entity); 134 } 135 136 protected void saveObjects(List<T> entities) 137 { 138 this.hibernateTemplate.saveOrUpdateAll(entities); 139 } 140 141 protected Long getCount(final String queryString, final String... params) 142 { 143 Object obj = this.hibernateTemplate.execute(new HibernateCallback() 144 { 145 @Override 146 public Object doInHibernate(Session arg0) 147 throws HibernateException, SQLException 148 { 149 Query query = arg0.createQuery("select count(*)" + queryString); 150 for (int i = 0; i < params.length; i++) 151 { 152 query.setString(i, params[i]); 153 } 154 return query.uniqueResult(); 155 } 156 157 }); 158 System.out.println(obj); 159 return (Long) obj; 160 } 161 162 protected Long getCount(final String queryString) 163 { 164 String[] params = new String[0]; 165 return this.getCount(queryString, params); 166 } 167 168 }
dao_template.java

1 package @PACKAGENAME@ 2 3 import java.util.*; 4 import @IMPORTMODELS@ 5 6 public interface @CLASSNAME@Dao 7 { 8 public void save@CLASSNAME@(@CLASSNAME@ bean); 9 10 11 public void save@CLASSNAME@s(List<@CLASSNAME@> beans); 12 13 14 public @CLASSNAME@ get@CLASSNAME@(long id); 15 16 17 public void remove@CLASSNAME@ById(long id); 18 19 20 public void remove@CLASSNAME@(@CLASSNAME@ bean); 21 22 23 public void remove@CLASSNAME@s(List<@CLASSNAME@> beans); 24 25 26 public long get@CLASSNAME@Count(String queryString); 27 28 29 public long get@CLASSNAME@Count(String queryString,String param); 30 31 32 public long get@CLASSNAME@Count(String queryString,String[] params); 33 34 35 public @CLASSNAME@ find@CLASSNAME@ById(Long id); 36 37 38 public List<@CLASSNAME@> find@CLASSNAME@s(String queryString); 39 40 41 public List<@CLASSNAME@> find@CLASSNAME@s(String queryString,String param); 42 43 44 public List<@CLASSNAME@> find@CLASSNAME@s(String queryString,String[] params); 45 46 47 public @CLASSNAME@ find@CLASSNAME@(String queryString); 48 49 50 public @CLASSNAME@ find@CLASSNAME@(String queryString,String param); 51 52 53 public @CLASSNAME@ find@CLASSNAME@(String queryString,String[] params); 54 55 56 public List<@CLASSNAME@> find@CLASSNAME@sByPages(String queryString,String param,int from ,int to); 57 58 59 public List<@CLASSNAME@> find@CLASSNAME@sByPages(String queryString,String[] params,int from ,int to); 60 61 62 public void update@CLASSNAME@ById(Long id); 63 64 65 public void update@CLASSNAME@(@CLASSNAME@ bean); 66 67 68 public void update@CLASSNAME@s(List<@CLASSNAME@> beans); 69 70 }
dao_impl_template.java

1 package @PACKAGENAME@ 2 3 import java.util.*; 4 5 import org.springframework.orm.hibernate3.HibernateTemplate; 6 7 import @IMPORTMODELS@ 8 import @IMPORTINTERFACES@ 9 10 import code.automatic.generation.framework.util.IDao; 11 12 public class @CLASSNAME@DaoImpl extends IDao<@CLASSNAME@> implements @CLASSNAME@Dao 13 { 14 15 public HibernateTemplate getHibernateTemplate() 16 { 17 return this.hibernateTemplate; 18 } 19 20 public void setHibernateTemplate(HibernateTemplate hibernateTemplate) 21 { 22 this.hibernateTemplate = hibernateTemplate; 23 } 24 25 public void save@CLASSNAME@(@CLASSNAME@ bean) 26 { 27 this.saveObject(bean); 28 } 29 30 public void save@CLASSNAME@s(List<@CLASSNAME@> beans) 31 { 32 this.saveObjects(beans); 33 } 34 35 public @CLASSNAME@ get@CLASSNAME@(long id) 36 { 37 return this.findObject(@CLASSNAME@.class,id); 38 } 39 40 public void remove@CLASSNAME@ById(long id) 41 { 42 this.removeObject(@CLASSNAME@.class,id); 43 } 44 45 public void remove@CLASSNAME@(@CLASSNAME@ bean) 46 { 47 this.removeObject(bean); 48 } 49 50 public void remove@CLASSNAME@s(List<@CLASSNAME@> beans) 51 { 52 this.removeObject(beans); 53 } 54 55 public long get@CLASSNAME@Count(String queryString) 56 { 57 return this.getCount(queryString); 58 } 59 60 public long get@CLASSNAME@Count(String queryString,String param) 61 { 62 return this.getCount(queryString,param); 63 } 64 65 public long get@CLASSNAME@Count(String queryString,String[] params) 66 { 67 return this.getCount(queryString,params); 68 } 69 70 public @CLASSNAME@ find@CLASSNAME@ById(Long id) 71 { 72 return this.findObject(@CLASSNAME@.class,id); 73 } 74 75 public List<@CLASSNAME@> find@CLASSNAME@s(String queryString) 76 { 77 return this.findObjects(queryString); 78 } 79 80 public List<@CLASSNAME@> find@CLASSNAME@s(String queryString,String param) 81 { 82 return this.findObjectsByParameters(queryString,param); 83 } 84 85 public List<@CLASSNAME@> find@CLASSNAME@s(String queryString,String[] params) 86 { 87 return this.findObjectsByParameters(queryString,params); 88 } 89 90 public @CLASSNAME@ find@CLASSNAME@(String queryString) 91 { 92 return this.findObjectByHQL(queryString); 93 } 94 95 public @CLASSNAME@ find@CLASSNAME@(String queryString,String param) 96 { 97 return this.findObjectByHQL(queryString,param); 98 } 99 100 public @CLASSNAME@ find@CLASSNAME@(String queryString,String[] params) 101 { 102 return this.findObjectByHQL(queryString,params); 103 } 104 105 public List<@CLASSNAME@> find@CLASSNAME@sByPages(String queryString,String param,int from ,int to) 106 { 107 return this.findObjectsByPages(queryString,param,from,to); 108 } 109 110 public List<@CLASSNAME@> find@CLASSNAME@sByPages(String queryString,String[] params,int from ,int to) 111 { 112 return this.findObjectsByPages(queryString,params,from,to); 113 } 114 115 public void update@CLASSNAME@ById(Long id) 116 { 117 this.updateObject(@CLASSNAME@.class,id); 118 } 119 120 public void update@CLASSNAME@(@CLASSNAME@ bean) 121 { 122 this.updateObject(bean); 123 } 124 125 public void update@CLASSNAME@s(List<@CLASSNAME@> beans) 126 { 127 this.updateObjects(beans); 128 } 129 }
6.准备Service层的模版
service_template.java

1 package @PACKAGENAME@ 2 3 import java.util.*; 4 import @IMPORTMODELS@ 5 6 public interface @CLASSNAME@Service 7 { 8 public void save@CLASSNAME@(@CLASSNAME@ bean); 9 10 public void remove@CLASSNAME@ById(long id); 11 12 public void update@CLASSNAME@(@CLASSNAME@ bean); 13 14 public long get@CLASSNAME@Count(); 15 16 public @CLASSNAME@ get@CLASSNAME@ById(Long id); 17 18 public List<@CLASSNAME@> get@CLASSNAME@sPages(int from,int to); 19 20 public List<@CLASSNAME@> get@CLASSNAME@sPagesByAsc(int from,int to); 21 22 public List<@CLASSNAME@> get@CLASSNAME@sPagesByDesc(int from,int to); 23 24 }
service_impl_template.java

1 package @PACKAGENAME@ 2 3 import java.util.*; 4 import @IMPORTMODELS@ 5 import @IMPORTINTERFACES@ 6 import @IMPORTSERVICEINTERFACE@ 7 8 public class @CLASSNAME@ServiceImpl implements @CLASSNAME@Service 9 { 10 private String list_all_desc="from @CLASSNAME@ bean order by bean.id desc"; 11 private String list_all_asc="from @CLASSNAME@ bean order by bean.id asc"; 12 13 private @CLASSNAME@Dao @classname@Dao; 14 15 public @CLASSNAME@Dao get@CLASSNAME@Dao() 16 { 17 return @classname@Dao; 18 } 19 20 public void set@CLASSNAME@Dao(@CLASSNAME@Dao @classname@Dao) 21 { 22 this.@classname@Dao = @classname@Dao; 23 } 24 25 public void save@CLASSNAME@(@CLASSNAME@ bean) 26 { 27 this.@classname@Dao.save@CLASSNAME@(bean); 28 } 29 30 public void remove@CLASSNAME@ById(long id) 31 { 32 this.@classname@Dao.remove@CLASSNAME@ById(id); 33 } 34 35 public void update@CLASSNAME@(@CLASSNAME@ bean) 36 { 37 this.@classname@Dao.update@CLASSNAME@(bean); 38 } 39 40 public long get@CLASSNAME@Count() 41 { 42 return this.@classname@Dao.get@CLASSNAME@Count(list_all_desc); 43 } 44 45 public @CLASSNAME@ get@CLASSNAME@ById(Long id) 46 { 47 return this.@classname@Dao.find@CLASSNAME@ById(id); 48 } 49 50 public List<@CLASSNAME@> get@CLASSNAME@sPages(int from,int to) 51 { 52 return this.@classname@Dao.find@CLASSNAME@sByPages(list_all_desc,new String[]{},from,to); 53 } 54 55 public List<@CLASSNAME@> get@CLASSNAME@sPagesByAsc(int from,int to) 56 { 57 return this.@classname@Dao.find@CLASSNAME@sByPages(list_all_asc,new String[]{},from,to); 58 } 59 60 public List<@CLASSNAME@> get@CLASSNAME@sPagesByDesc(int from,int to) 61 { 62 return this.@classname@Dao.find@CLASSNAME@sByPages(list_all_desc,new String[]{},from,to); 63 } 64 65 }
7.准备Action模版
add_action_template.java

1 package @ACTIONPACKAGENAME@ 2 3 import java.util.*; 4 5 import @IMPORTMODELS@ 6 import @IMPORTSERVICEINTERFACE@ 7 8 import com.opensymphony.xwork2.ActionSupport; 9 10 11 public class Add@CLASSNAME@Action extends ActionSupport 12 { 13 private @CLASSNAME@Service service; 14 15 @ADDATTRIBUTES@ 16 17 public void setService(@CLASSNAME@Service service) 18 { 19 this.service=service; 20 } 21 22 public @CLASSNAME@Service getService() 23 { 24 return this.service; 25 } 26 27 @ADDGETTERANDSETTER@ 28 29 @Override 30 public void validate() 31 { 32 33 } 34 35 @Override 36 public String execute() throws Exception 37 { 38 @CLASSNAME@ bean=new @CLASSNAME@(); 39 40 @SETPROPERTY@ 41 42 this.service.save@CLASSNAME@(bean); 43 return SUCCESS; 44 } 45 46 47 }
update_pre_action_template.java

1 package @ACTIONPACKAGENAME@ 2 3 import java.util.*; 4 5 import @IMPORTMODELS@ 6 import @IMPORTSERVICEINTERFACE@ 7 8 import com.opensymphony.xwork2.ActionSupport; 9 10 11 public class UpdatePre@CLASSNAME@Action extends ActionSupport 12 { 13 private @CLASSNAME@Service service; 14 15 private @CLASSNAME@ bean; 16 17 private Long id; 18 19 private int start; 20 21 private int maxLineSize; 22 23 public void setService(@CLASSNAME@Service service) 24 { 25 this.service=service; 26 } 27 28 public @CLASSNAME@Service getService() 29 { 30 return this.service; 31 } 32 33 public @CLASSNAME@ getBean() 34 { 35 return this.bean; 36 } 37 38 public void setBean(@CLASSNAME@ bean) 39 { 40 this.bean=bean; 41 } 42 43 public Long getId() 44 { 45 return id; 46 } 47 48 public void setId(Long id) 49 { 50 this.id = id; 51 } 52 53 public int getStart() 54 { 55 return start; 56 } 57 58 public void setStart(int start) 59 { 60 this.start = start; 61 } 62 63 public int getMaxLineSize() 64 { 65 return maxLineSize; 66 } 67 68 public void setMaxLineSize(int maxLineSize) 69 { 70 this.maxLineSize = maxLineSize; 71 } 72 73 @Override 74 public void validate() 75 { 76 77 } 78 79 @Override 80 public String execute() throws Exception 81 { 82 @CLASSNAME@ result=this.service.get@CLASSNAME@ById(this.id); 83 if(result == null) 84 { 85 return INPUT; 86 } 87 this.setBean(result); 88 return SUCCESS; 89 } 90 91 }
update_action_template.java

1 package @ACTIONPACKAGENAME@ 2 3 import java.util.*; 4 5 import @IMPORTMODELS@ 6 import @IMPORTSERVICEINTERFACE@ 7 8 import com.opensymphony.xwork2.ActionSupport; 9 10 11 public class Update@CLASSNAME@Action extends ActionSupport 12 { 13 private @CLASSNAME@Service service; 14 15 private int start; 16 17 private int maxLineSize; 18 19 @ADDATTRIBUTES@ 20 21 public void setService(@CLASSNAME@Service service) 22 { 23 this.service=service; 24 } 25 26 public @CLASSNAME@Service getService() 27 { 28 return this.service; 29 } 30 31 public int getStart() 32 { 33 return start; 34 } 35 36 public void setStart(int start) 37 { 38 this.start = start; 39 } 40 41 public int getMaxLineSize() 42 { 43 return maxLineSize; 44 } 45 46 public void setMaxLineSize(int maxLineSize) 47 { 48 this.maxLineSize = maxLineSize; 49 } 50 51 @ADDGETTERANDSETTER@ 52 53 @Override 54 public String execute() throws Exception 55 { 56 if (null != this.service.get@CLASSNAME@ById(Long.valueOf(this.getId()))) 57 { 58 @CLASSNAME@ bean=new @CLASSNAME@(); 59 60 @SETPROPERTY@ 61 62 this.service.update@CLASSNAME@(bean); 63 return SUCCESS; 64 } 65 return INPUT; 66 } 67 68 }
list_action_template.java

1 package @ACTIONPACKAGENAME@ 2 3 import java.util.*; 4 5 import org.apache.struts2.ServletActionContext; 6 7 import code.automatic.generation.framework.util.PagingComponent; 8 9 import @IMPORTMODELS@ 10 import @IMPORTSERVICEINTERFACE@ 11 12 import com.opensymphony.xwork2.ActionSupport; 13 14 15 public class List@CLASSNAME@Action extends ActionSupport 16 { 17 private @CLASSNAME@Service service; 18 19 private List<@CLASSNAME@> queryList; 20 21 private int start; 22 23 private int maxLineSize; 24 25 private String pagingInfo; 26 27 public void setService(@CLASSNAME@Service service) 28 { 29 this.service=service; 30 } 31 32 public @CLASSNAME@Service getService() 33 { 34 return this.service; 35 } 36 37 public List<@CLASSNAME@> getQueryList() 38 { 39 return queryList; 40 } 41 42 public void setQueryList(List<@CLASSNAME@> queryList) 43 { 44 this.queryList = queryList; 45 } 46 47 public int getStart() 48 { 49 return start; 50 } 51 52 public void setStart(int start) 53 { 54 this.start = start; 55 } 56 57 public int getMaxLineSize() 58 { 59 return maxLineSize; 60 } 61 62 public void setMaxLineSize(int maxLineSize) 63 { 64 this.maxLineSize = maxLineSize; 65 } 66 67 public String getPagingInfo() 68 { 69 return pagingInfo; 70 } 71 72 public void setPagingInfo(String pagingInfo) 73 { 74 this.pagingInfo = pagingInfo; 75 } 76 77 @Override 78 public void validate() 79 { 80 81 } 82 83 @Override 84 public String execute() throws Exception 85 { 86 if (maxLineSize == 0) 87 { 88 maxLineSize = 10; 89 } 90 long allCount = this.service.get@CLASSNAME@Count(); 91 92 this.pagingInfo = PagingComponent.getPaging( 93 ServletActionContext.getRequest(), "", start, maxLineSize, 94 allCount); 95 this.setQueryList(this.service.get@CLASSNAME@sPages(start, maxLineSize)); 96 97 if(this.queryList.size() == 0) 98 { 99 return INPUT; 100 } 101 102 return SUCCESS; 103 } 104 105 }
delete_action_template.java

1 package @ACTIONPACKAGENAME@ 2 3 import java.util.*; 4 5 import @IMPORTMODELS@ 6 import @IMPORTSERVICEINTERFACE@ 7 8 import com.opensymphony.xwork2.ActionSupport; 9 10 11 public class Delete@CLASSNAME@Action extends ActionSupport 12 { 13 private @CLASSNAME@Service service; 14 15 private Long id; 16 17 private int start; 18 19 private int maxLineSize; 20 21 public void setService(@CLASSNAME@Service service) 22 { 23 this.service=service; 24 } 25 26 public @CLASSNAME@Service getService() 27 { 28 return this.service; 29 } 30 31 public Long getId() 32 { 33 return id; 34 } 35 36 public void setId(Long id) 37 { 38 this.id = id; 39 } 40 41 public int getStart() 42 { 43 return start; 44 } 45 46 public void setStart(int start) 47 { 48 this.start = start; 49 } 50 51 public int getMaxLineSize() 52 { 53 return maxLineSize; 54 } 55 56 public void setMaxLineSize(int maxLineSize) 57 { 58 this.maxLineSize = maxLineSize; 59 } 60 61 @Override 62 public void validate() 63 { 64 65 } 66 67 @Override 68 public String execute() throws Exception 69 { 70 @CLASSNAME@ bean=this.service.get@CLASSNAME@ById(id); 71 if(bean!=null) 72 { 73 this.service.remove@CLASSNAME@ById(bean.getId()); 74 return SUCCESS; 75 } 76 return INPUT; 77 } 78 79 80 }
8.准备Jsp模版
add_template.jsp

1 <%@page language="java" contentType="text/html; charset=utf-8"%> 2 3 <%@ include file="../documentTabSideBar.jsp"%> 4 5 <%@ include file="../title.jsp"%> 6 7 <script type="text/javascript" src="../Js/submitInfo.js" charset="utf-8"></script> 8 9 <form name="submitInfo" method="post" action="Add@CLASSNAME@Action.action" > 10 <table cellpadding="3" cellspacing="1" border="0" align="center" class="table" width="90%"> 11 12 @MORETRS@ 13 <tr class="tr"> 14 <td><input type="submit" value="提交"> 15 </td> 16 <td><input type="reset" value="重置"> 17 </td> 18 </tr> 19 </table> 20 </form> 21 22 <%@ include file="../footer.jsp"%>
list_template.jsp

1 <%@page language="java" contentType="text/html; charset=utf-8"%> 2 <%@taglib prefix="s" uri="/struts-tags"%> 3 4 <%@ include file="../documentTabSideBar.jsp"%> 5 <%@ include file="../title.jsp"%> 6 <script type="text/javascript"> 7 <!-- 8 function add() 9 { 10 window.location.href="Add@CLASSNAME@.jsp"; 11 } 12 function del() 13 { 14 if(!window.confirm("确定删除此条记录吗?")) 15 { 16 return false; 17 } 18 return true; 19 } 20 function setLineSize() 21 { 22 var temp=document.getElementById("lineSize").value; 23 window.location.href="List@CLASSNAME@Action.action?start=0&maxLineSize="+temp; 24 } 25 //--> 26 </script> 27 <table width="97%" align="center"> 28 <tr> 29 <td> 30 <input type="button" value="增加目录" onclick="add()"> 31 </td> 32 <td align="right"> 33 <% 34 out.print(request.getAttribute("pagingInfo")); 35 %> 36 每页显示 37 <select id="lineSize" onchange="setLineSize()"> 38 <option value="5" <s:if test="maxLineSize==5">selected="selected"</s:if>>5</option> 39 <option value="10" <s:if test="maxLineSize==10">selected="selected"</s:if>>10</option> 40 <option value="15" <s:if test="maxLineSize==15">selected="selected"</s:if>>15</option> 41 <option value="20" <s:if test="maxLineSize==20">selected="selected"</s:if>>20</option> 42 <option value="25" <s:if test="maxLineSize==25">selected="selected"</s:if>>25</option> 43 </select> 44 条记录 45 </td> 46 </tr> 47 48 </table> 49 50 <table cellpadding="3" cellspacing="1" border="0" align="center" class="table" width="97%"> 51 <tr class="tr"> 52 @MORETDSHEADER@ 53 54 <td width="" align="center" bgcolor="#78A1E6" nowrap="nowrap">操作</td> 55 </tr> 56 57 <s:iterator id="dc" value="queryList"> 58 <tr class="tr"> 59 @MORETRSRECORD@ 60 61 <td align="center" bgcolor="#E6ECF9"> 62 <a href="UpdatePre@CLASSNAME@Action.action?id=<s:property value='#dc.id'/>&start=<s:property value='start'/>&maxLineSize=<s:property value='maxLineSize'/>" >更新</a> 63 | 64 <a href="Delete@CLASSNAME@Action.action?id=<s:property value='#dc.id'/>&start=<s:property value='start'/>&maxLineSize=<s:property value='maxLineSize'/>" onclick=" return del()">删除</a> 65 </td> 66 </tr> 67 </s:iterator> 68 </table> 69 70 <table width="97%" align="center"> 71 <tr> 72 <td align="right"></td> 73 </tr> 74 75 </table> 76 77 <%@ include file="../footer.jsp"%>
update_template.jsp

1 <%@page language="java" contentType="text/html; charset=utf-8"%> 2 <%@taglib prefix="s" uri="/struts-tags"%> 3 <%@ include file="../documentTabSideBar.jsp"%> 4 <script type="text/javascript" charset="utf-8"> 5 6 function validateTitle(title) { 7 if (title == "") { 8 document.getElementById("title_msg").innerHTML = "<font color=\"red\">* 目录名称不能为空!</font>"; 9 return false; 10 } else { 11 document.getElementById("title_msg").innerHTML = "<font color=\"green\">* 目录名称填写正确!</font>"; 12 return true; 13 } 14 15 } 16 <s:if test="documentCatalog.flag == false"> 17 function validateDescription(description) { 18 if (description == "") { 19 document.getElementById("description_msg").innerHTML = "<font color=\"red\">* 描述不能为空!</font>"; 20 return false; 21 } else { 22 document.getElementById("description_msg").innerHTML = "<font color=\"green\">* 描述填写正确!</font>"; 23 return true; 24 } 25 26 } 27 function validateUrl(url) { 28 var strRegex = "^((https|http|ftp|rtsp|mms)?://)" 29 + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" 30 + "(([0-9]{1,3}\.){3}[0-9]{1,3}" 31 + "|" 32 + "([0-9a-z_!~*'()-]+\.)*" 33 + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." 34 + "[a-z]{2,6})" 35 + "(:[0-9]{1,4})?" 36 + "((/?)|" 37 + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; 38 39 if (!new RegExp(strRegex).test(url)) { 40 document.getElementById("url_msg").innerHTML = "<font color=\"red\">* 网址格式不正确!</font>"; 41 return false; 42 } else { 43 document.getElementById("url_msg").innerHTML = "<font color=\"green\">* 网址填写正确!</font>"; 44 return true; 45 } 46 return false; 47 } 48 </s:if> 49 function validate() { 50 return (validateTitle(document.submitInfo.title.value) 51 && validateDescription(document.submitInfo.description.value) && validateUrl(document.submitInfo.url.value)); 52 } 53 </script> 54 <%@ include file="../title.jsp"%> 55 56 <s:form name="submitInfo" method="post" action="Update@CLASSNAME@Action" theme="simple" namespace="/@CLASSNAME@" onsubmit="return validate()"> 57 <input type="hidden" name="id" value="<s:property value='bean.id'/>"/> 58 <input type="hidden" name="start" value="<s:property value='start'/>"/> 59 <input type="hidden" name="maxLineSize" value="<s:property value='maxLineSize'/>"/> 60 <table cellpadding="3" cellspacing="1" border="0" align="center" class="table" width="90%"> 61 @MORETRITEMS@ 62 63 <tr class="tr"> 64 <td><input type="submit" value="修改"></td> 65 <td><input type="reset" value="重置"></td> 66 </tr> 67 </table> 68 </s:form> 69 70 71 72 <%@ include file="../footer.jsp"%>
9.准备Ant编译环境
build.properties

1 src.dir=src 2 hbm.directory=config 3 template.directory=D\:\\cagf\\template 4 rootpath=WebRoot 5 classes.directory=${rootpath}\\WEB-INF\\classes 6 libs=D\:\\cagf\\libs 7 8 spring.config.output.dir=${rootpath}\\WEB-INF\\ 9 spring.file.name.basic=applicationContext-basic.xml 10 spring.file.name.dao=applicationContext-dao.xml 11 spring.file.name.action=applicationContext-action.xml 12 spring.dbproperty=dbconfig.properties 13 spring.hibernate.property=hibernateProperty.properties 14 project.directory=E\:\\webstudy\\CodeAutomaticGenerationFramework
dbconfig.properties

1 driverClassName=oracle.jdbc.driver.OracleDriver 2 url=jdbc:oracle:thin:@localhost:1521:HIBERBATETOOL 3 username=scott 4 password=tiger 5 maxActive=100 6 maxIdle=30 7 maxWait=10000
hibernateProperty.properties

1 hibernate.dialect=org.hibernate.dialect.Oracle10gDialect 2 hibernate.show_sql=true 3 hibernate.format_sql=true 4 hibernate.hbm2ddl.auto=update 5 javax.persistence.validation.mode=none
10.编写build.xml

1 <?xml version="1.0" encoding="UTF-8"?> 2 <project basedir="." default="run"> 3 <property file="build.properties"> 4 </property> 5 6 <target name="init"> 7 <path id="run.environment"> 8 <pathelement path="${classes.directory}" /> 9 <fileset dir="${libs}"> 10 <include name="**/*.jar" /> 11 </fileset> 12 </path> 13 </target> 14 15 <target name="set.hibernate.mappingfiles" depends="init"> 16 <fileset id="hbm.directory" dir="${hbm.directory}"> 17 <include name="**/*.hbm.xml" /> 18 </fileset> 19 <pathconvert property="hibernate.mappings" refid="hbm.directory" pathsep=" "> 20 </pathconvert> 21 </target> 22 23 <target name="createModel" depends="set.hibernate.mappingfiles"> 24 <taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpathref="run.environment" /> 25 <hibernatetool destdir="${src.dir}"> 26 <configuration configurationfile="config/hibernate.cfg.xml" /> 27 <hbm2java jdk5="true" /> 28 <hbm2ddl export="false" outputfilename="ddl.sql" drop="true" create="true" format="true" /> 29 <classpath refid="run.environment"> 30 </classpath> 31 </hibernatetool> 32 </target> 33 34 <target name="run" depends="createModel"> 35 <mkdir dir="${classes.directory}" /> 36 37 <echo>---生成Dao层---</echo> 38 <java classname="code.automatic.generation.framework.hbm2dao.CodeGenerater" fork="true" failonerror="true"> 39 <sysproperty key="file.encoding" value="UTF-8" /> 40 <classpath refid="run.environment"> 41 </classpath> 42 <arg line="--templateDirectory=${template.directory}" /> 43 <arg line="--outputDirectory=${src.dir}" /> 44 <arg line="${hibernate.mappings}" /> 45 </java> 46 47 <java classname="code.automatic.generation.framework.hbm2daoimpl.CodeGenerater" fork="true" failonerror="true"> 48 <sysproperty key="file.encoding" value="UTF-8" /> 49 <classpath refid="run.environment"> 50 </classpath> 51 <arg line="--templateDirectory=${template.directory}" /> 52 <arg line="--outputDirectory=${src.dir}" /> 53 <arg line="${hibernate.mappings}" /> 54 </java> 55 56 <echo>---生成applicationContext-basic.xml---</echo> 57 <java classname="code.automatic.generation.framework.hbm2xml.CodeGenerater" fork="true" failonerror="true"> 58 <sysproperty key="file.encoding" value="UTF-8" /> 59 <classpath refid="run.environment"></classpath> 60 61 <arg line="--outputDirectory=${spring.config.output.dir}" /> 62 <arg line="--springxmlFilename=${spring.file.name.basic}" /> 63 <arg line="--dbproperty=${spring.dbproperty}" /> 64 <arg line="--hibernateProperty=${spring.hibernate.property}" /> 65 <arg line="--projectDirectory=${project.directory}" /> 66 <arg line="--hbmDirectory=${hbm.directory}" /> 67 68 <arg line="${hibernate.mappings}" /> 69 </java> 70 71 <echo>---生成applicationContext-dao.xml---</echo> 72 <java classname="code.automatic.generation.framework.hbm2xml.daoconfig.CodeGenerater" fork="true" failonerror="true"> 73 <sysproperty key="file.encoding" value="UTF-8" /> 74 <classpath refid="run.environment"></classpath> 75 76 <arg line="--outputDirectory=${spring.config.output.dir}" /> 77 <arg line="--springDaoConfigFileName=${spring.file.name.dao}" /> 78 <arg line="--projectDirectory=${project.directory}" /> 79 <arg line="${hibernate.mappings}" /> 80 </java> 81 82 <echo>---生成services层---</echo> 83 <java classname="code.automatic.generation.framework.hbm2service.CodeGenerater" fork="true" failonerror="true"> 84 <sysproperty key="file.encoding" value="UTF-8" /> 85 <classpath refid="run.environment"> 86 </classpath> 87 <arg line="--templateDirectory=${template.directory}" /> 88 <arg line="--outputDirectory=${src.dir}" /> 89 <arg line="${hibernate.mappings}" /> 90 </java> 91 92 <java classname="code.automatic.generation.framework.hbm2serviceimpl.CodeGenerater" fork="true" failonerror="true"> 93 <sysproperty key="file.encoding" value="UTF-8" /> 94 <classpath refid="run.environment"> 95 </classpath> 96 <arg line="--templateDirectory=${template.directory}" /> 97 <arg line="--outputDirectory=${src.dir}" /> 98 <arg line="${hibernate.mappings}" /> 99 </java> 100 101 <echo>---编译源文件---</echo> 102 <javac srcdir="${src.dir}" destdir="${classes.directory}" classpathref="run.environment" includeantruntime="true"></javac> 103 104 <echo>---生成Action---</echo> 105 <java classname="code.automatic.generation.framework.hbm2action.CodeGenerater" fork="true" failonerror="true"> 106 <sysproperty key="file.encoding" value="UTF-8" /> 107 <classpath refid="run.environment"></classpath> 108 <arg line="--outputDirectory=${src.dir}" /> 109 <arg line="--templateDirectory=${template.directory}" /> 110 <arg line="${hibernate.mappings}" /> 111 </java> 112 113 <echo>---编译源文件---</echo> 114 <javac srcdir="${src.dir}" destdir="${classes.directory}" classpathref="run.environment" includeantruntime="true"></javac> 115 116 <echo>---生成Spring Action Config---</echo> 117 <java classname="code.automatic.generation.framework.hbm2xml.actionconfig.CodeGenerater" fork="true" failonerror="true"> 118 <sysproperty key="file.encoding" value="UTF-8" /> 119 <classpath refid="run.environment"></classpath> 120 <arg line="--outputDirectory=${spring.config.output.dir}" /> 121 <arg line="--springActionConfigFileName=${spring.file.name.action}" /> 122 <arg line="--projectDirectory=${project.directory}" /> 123 <arg line="${hibernate.mappings}" /> 124 </java> 125 126 <echo>---生成Struts.xml---</echo> 127 <java classname="code.automatic.generation.framework.hbm2strutsxml.CodeGenerater" fork="true" failonerror="true"> 128 <sysproperty key="file.encoding" value="UTF-8" /> 129 <classpath refid="run.environment"></classpath> 130 <arg line="--outputDirectory=${src.dir}" /> 131 <arg line="${hibernate.mappings}" /> 132 </java> 133 134 <echo>---生成Jsp---</echo> 135 <java classname="code.automatic.generation.framework.hbm2jsp.CodeGenerater" fork="true" failonerror="true"> 136 <sysproperty key="file.encoding" value="UTF-8" /> 137 <classpath refid="run.environment"> 138 </classpath> 139 <arg line="--templateDirectory=${template.directory}" /> 140 <arg line="--outputDirectory=${rootpath}" /> 141 <arg line="${hibernate.mappings}" /> 142 </java> 143 </target> 144 </project>
二、生成
11.生成Dao---hbm2dao
CodeGenerater.java

1 package code.automatic.generation.framework.hbm2dao; 2 3 public class CodeGenerater 4 { 5 private static String outputDirectory; 6 7 public static void main(String[] args) 8 { 9 10 System.out.println("DAO开始生成!"); 11 12 for (String temp : args) 13 { 14 15 if (temp.startsWith("--outputDirectory")) 16 { 17 outputDirectory = temp 18 .substring("--outputDirectory".length() + 1); 19 } 20 else if (temp.startsWith("--templateDirectory")) 21 { 22 Configer.getConfigerInstance().setDaoTemplatePath( 23 temp.substring("--templateDirectory".length() + 1)); 24 } 25 else 26 { 27 CodeUtil.getCodeUtilInstance().generateDao(temp, 28 outputDirectory); 29 } 30 31 } 32 System.out.println("DAO 生成完毕!"); 33 } 34 }
CodeUtil.java

1 package code.automatic.generation.framework.hbm2dao; 2 3 import java.io.File; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 7 import code.automatic.generation.framework.util.AuxiliaryStringProcessingUtil; 8 import code.automatic.generation.framework.util.FileData; 9 10 public class CodeUtil 11 { 12 private String DAO_EXT = "Dao.java"; 13 private static CodeUtil codeUtil = new CodeUtil(); 14 15 private CodeUtil() 16 { 17 18 } 19 20 public static CodeUtil getCodeUtilInstance() 21 { 22 return codeUtil; 23 } 24 25 private void replaceKeyWordAndGenerateDao(String templateContent, 26 String outputFileCompletePath, String packageName, 27 String importModelNames, String className) 28 { 29 String temp = null; 30 String packageNameTemplate = "@PACKAGENAME@"; 31 String importModelTemplate = "@IMPORTMODELS@"; 32 String classNameTemplate = "@CLASSNAME@"; 33 temp = templateContent.replaceAll(packageNameTemplate, packageName) 34 .replaceAll(importModelTemplate, importModelNames) 35 .replaceAll(classNameTemplate, className); 36 FileWriter writer = null; 37 try 38 { 39 File file = new File(outputFileCompletePath); 40 writer = new FileWriter(file); 41 writer.write(temp); 42 43 } 44 catch (Exception e) 45 { 46 e.printStackTrace(); 47 } 48 finally 49 { 50 try 51 { 52 writer.close(); 53 } 54 catch (IOException e) 55 { 56 e.printStackTrace(); 57 } 58 } 59 60 } 61 62 public void generateDao(String hbmCompletePath, String outputCompletePath) 63 { 64 String hbmContent = FileData.getHbmContent(hbmCompletePath); 65 String templateContent = FileData.getTemplateContent(Configer 66 .getConfigerInstance().getDaoTemplatePath()); 67 68 String packageName = AuxiliaryStringProcessingUtil 69 .getDaoPackageName(hbmContent); 70 String importModelNames = AuxiliaryStringProcessingUtil 71 .getImportModelNames(hbmContent); 72 String className = AuxiliaryStringProcessingUtil 73 .getClassName(hbmContent); 74 75 String outputFileCompleteDirectory = FileData 76 .getOutputFileCompletePath(outputCompletePath, hbmContent, 77 packageName); 78 79 String outputFileCompletePath = outputFileCompleteDirectory 80 + File.separator + className + DAO_EXT; 81 82 this.replaceKeyWordAndGenerateDao(templateContent, 83 outputFileCompletePath, packageName, importModelNames, 84 className); 85 } 86 }
Configer.java

1 package code.automatic.generation.framework.hbm2dao; 2 3 public class Configer 4 { 5 private static Configer configer = new Configer(); 6 private String extName = "\\dao_template.java"; 7 private String daoTemplatePath; 8 9 private Configer() 10 { 11 12 } 13 14 public static Configer getConfigerInstance() 15 { 16 return configer; 17 } 18 19 public String getDaoTemplatePath() 20 { 21 return daoTemplatePath; 22 } 23 24 public void setDaoTemplatePath(String daoTemplatePath) 25 { 26 this.daoTemplatePath = daoTemplatePath + this.extName; 27 } 28 29 }
12.生成DaoImpl---hbm2daoimpl
CodeGenerater.java

1 package code.automatic.generation.framework.hbm2daoimpl; 2 3 public class CodeGenerater 4 { 5 private static String outputDirectory; 6 7 public static void main(String[] args) 8 { 9 10 System.out.println("DAOImpl开始生成...!"); 11 12 for (String temp : args) 13 { 14 15 if (temp.startsWith("--outputDirectory")) 16 { 17 outputDirectory = temp 18 .substring("--outputDirectory".length() + 1); 19 } 20 else if (temp.startsWith("--templateDirectory")) 21 { 22 Configer.getConfigerInstance().setDaoTemplatePath( 23 temp.substring("--templateDirectory".length() + 1)); 24 } 25 else 26 { 27 CodeUtil.getCodeUtilInstance().generateDaoImpl(temp, 28 outputDirectory); 29 } 30 31 } 32 System.out.println("DAOImpl生成完毕...!"); 33 } 34 }
CodeUtil.java

1 package code.automatic.generation.framework.hbm2daoimpl; 2 3 import java.io.File; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 7 import code.automatic.generation.framework.util.AuxiliaryStringProcessingUtil; 8 import code.automatic.generation.framework.util.FileData; 9 10 public class CodeUtil 11 { 12 13 private String DAOIMPL_EXT = "DaoImpl.java"; 14 15 private static CodeUtil codeUtil = new CodeUtil(); 16 17 private CodeUtil() 18 { 19 20 } 21 22 public static CodeUtil getCodeUtilInstance() 23 { 24 return codeUtil; 25 } 26 27 private void replaceKeyWordAndGenerateDaoImpl(String templateContent, 28 String outputFileCompletePath, String packageName, 29 String importModelNames, String className, String hbmContent) 30 { 31 String temp = null; 32 String packageNameTemplate = "@PACKAGENAME@"; 33 String importModelTemplate = "@IMPORTMODELS@"; 34 String classNameTemplate = "@CLASSNAME@"; 35 String importInterfacesTemplate = "@IMPORTINTERFACES@"; 36 37 temp = templateContent 38 .replaceAll(packageNameTemplate, packageName) 39 .replaceAll(importModelTemplate, importModelNames) 40 .replaceAll(classNameTemplate, className) 41 .replaceAll( 42 importInterfacesTemplate, 43 AuxiliaryStringProcessingUtil.getDaoPackageName( 44 hbmContent).replace(";", ".*;")); 45 FileWriter writer = null; 46 try 47 { 48 File file = new File(outputFileCompletePath); 49 writer = new FileWriter(file); 50 writer.write(temp); 51 52 } 53 catch (Exception e) 54 { 55 e.printStackTrace(); 56 } 57 finally 58 { 59 try 60 { 61 writer.close(); 62 } 63 catch (IOException e) 64 { 65 e.printStackTrace(); 66 } 67 } 68 69 } 70 71 public void generateDaoImpl(String hbmCompletePath, 72 String outputCompletePath) 73 { 74 String hbmContent = FileData.getHbmContent(hbmCompletePath); 75 String templateContent = FileData.getTemplateContent(Configer 76 .getConfigerInstance().getDaoTemplatePath()); 77 String packageName = AuxiliaryStringProcessingUtil 78 .getDaoImplPackageName(hbmContent); 79 String importModelNames = AuxiliaryStringProcessingUtil 80 .getImportModelNames(hbmContent); 81 String className = AuxiliaryStringProcessingUtil 82 .getClassName(hbmContent); 83 84 String outputFileCompleteDirectory = FileData 85 .getOutputFileCompletePath(outputCompletePath, hbmContent, 86 packageName); 87 88 String outputFileCompletePath = outputFileCompleteDirectory 89 + File.separator + className + DAOIMPL_EXT; 90 this.replaceKeyWordAndGenerateDaoImpl(templateContent, 91 outputFileCompletePath, packageName, importModelNames, 92 className, hbmContent); 93 } 94 }
Configer.java

1 package code.automatic.generation.framework.hbm2daoimpl; 2 3 public class Configer 4 { 5 private static Configer configer = new Configer(); 6 private String extName = "\\dao_impl_template.java"; 7 private String daoTemplatePath; 8 9 private Configer() 10 { 11 12 } 13 14 public static Configer getConfigerInstance() 15 { 16 return configer; 17 } 18 19 public String getDaoTemplatePath() 20 { 21 return daoTemplatePath; 22 } 23 24 public void setDaoTemplatePath(String daoTemplatePath) 25 { 26 this.daoTemplatePath = daoTemplatePath + this.extName; 27 } 28 29 }
13.生成Service---hbm2service
CodeGenerater.java

1 package code.automatic.generation.framework.hbm2service; 2 3 public class CodeGenerater 4 { 5 private static String outputDirectory; 6 7 public static void main(String[] args) 8 { 9 10 System.out.println("Service开始生成!"); 11 12 for (String temp : args) 13 { 14 15 if (temp.startsWith("--outputDirectory")) 16 { 17 outputDirectory = temp 18 .substring("--outputDirectory".length() + 1); 19 } 20 else if (temp.startsWith("--templateDirectory")) 21 { 22 Configer.getConfigerInstance().setDaoTemplatePath( 23 temp.substring("--templateDirectory".length() + 1)); 24 } 25 else 26 { 27 CodeUtil.getCodeUtilInstance().generateService(temp, outputDirectory); 28 } 29 30 } 31 System.out.println("Service 生成完毕!"); 32 } 33 }
CodeUtil.java

1 package code.automatic.generation.framework.hbm2service; 2 3 import java.io.File; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 7 import code.automatic.generation.framework.util.AuxiliaryStringProcessingUtil; 8 import code.automatic.generation.framework.util.FileData; 9 10 public class CodeUtil 11 { 12 private String SERVICE_EXT = "Service.java"; 13 14 private static CodeUtil codeUtil = new CodeUtil(); 15 16 private CodeUtil() 17 { 18 19 } 20 21 public static CodeUtil getCodeUtilInstance() 22 { 23 return codeUtil; 24 } 25 26 private void replaceKeyWordAndGenerateService(String templateContent, 27 String outputFileCompletePath, String packageName, 28 String importModelNames, String className) 29 { 30 String temp = null; 31 String packageNameTemplate = "@PACKAGENAME@"; 32 String importModelTemplate = "@IMPORTMODELS@"; 33 String classNameTemplate = "@CLASSNAME@"; 34 temp = templateContent.replaceAll(packageNameTemplate, packageName) 35 .replaceAll(importModelTemplate, importModelNames) 36 .replaceAll(classNameTemplate, className); 37 FileWriter writer = null; 38 try 39 { 40 File file = new File(outputFileCompletePath); 41 writer = new FileWriter(file); 42 writer.write(temp); 43 44 } 45 catch (Exception e) 46 { 47 e.printStackTrace(); 48 } 49 finally 50 { 51 try 52 { 53 writer.close(); 54 } 55 catch (IOException e) 56 { 57 e.printStackTrace(); 58 } 59 } 60 61 } 62 63 public void generateService(String hbmCompletePath, 64 String outputCompletePath) 65 { 66 String hbmContent = FileData.getHbmContent(hbmCompletePath); 67 68 String templateContent = FileData.getTemplateContent(Configer 69 .getConfigerInstance().getDaoTemplatePath()); 70 71 String packageName = AuxiliaryStringProcessingUtil 72 .getServicePackageName(hbmContent); 73 String importModelNames = AuxiliaryStringProcessingUtil 74 .getImportModelNames(hbmContent); 75 String className = AuxiliaryStringProcessingUtil 76 .getClassName(hbmContent); 77 78 String outputFileCompleteDirectory = FileData 79 .getOutputFileCompletePath(outputCompletePath, hbmContent, 80 packageName); 81 String outputFileCompletePath = outputFileCompleteDirectory 82 + File.separator + className + SERVICE_EXT; 83 this.replaceKeyWordAndGenerateService(templateContent, 84 outputFileCompletePath, packageName, importModelNames, 85 className); 86 } 87 }
Configer.java

1 package code.automatic.generation.framework.hbm2service; 2 3 public class Configer 4 { 5 private static Configer configer = new Configer(); 6 private String extName = "\\service_template.java"; 7 private String daoTemplatePath; 8 9 private Configer() 10 { 11 12 } 13 14 public static Configer getConfigerInstance() 15 { 16 return configer; 17 } 18 19 public String getDaoTemplatePath() 20 { 21 return daoTemplatePath; 22 } 23 24 public void setDaoTemplatePath(String daoTemplatePath) 25 { 26 this.daoTemplatePath = daoTemplatePath + this.extName; 27 } 28 29 }
14.生成ServiceImpl---hbm2serviceimpl
CodeGenerater.java

1 package code.automatic.generation.framework.hbm2serviceimpl; 2 3 public class CodeGenerater 4 { 5 private static String outputDirectory; 6 7 public static void main(String[] args) 8 { 9 10 System.out.println("ServiceImpl开始生成!"); 11 12 for (String temp : args) 13 { 14 15 if (temp.startsWith("--outputDirectory")) 16 { 17 outputDirectory = temp 18 .substring("--outputDirectory".length() + 1); 19 } 20 else if (temp.startsWith("--templateDirectory")) 21 { 22 Configer.getConfigerInstance().setDaoTemplatePath( 23 temp.substring("--templateDirectory".length() + 1)); 24 } 25 else 26 { 27 CodeUtil.getCodeUtilInstance().generateServiceImpl(temp, 28 outputDirectory); 29 } 30 31 } 32 System.out.println("ServiceImpl生成完毕!"); 33 } 34 }
CodeUtil.java

1 package code.automatic.generation.framework.hbm2serviceimpl; 2 3 import java.io.File; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 7 import code.automatic.generation.framework.util.AuxiliaryStringProcessingUtil; 8 import code.automatic.generation.framework.util.FileData; 9 10 public class CodeUtil 11 { 12 13 private String SERVICE_EXT = "ServiceImpl.java"; 14 15 private static CodeUtil codeUtil = new CodeUtil(); 16 17 private CodeUtil() 18 { 19 20 } 21 22 public static CodeUtil getCodeUtilInstance() 23 { 24 return codeUtil; 25 } 26 27 private void replaceKeyWordAndGenerateServiceImpl(String templateContent, 28 String outputFileCompletePath, String packageName, 29 String importModelName, String className, String hbmContent) 30 { 31 String temp = null; 32 String packageNameTemplate = "@PACKAGENAME@"; 33 String importModelTemplate = "@IMPORTMODELS@"; 34 String classNameTemplate = "@CLASSNAME@"; 35 String importInterfacesTemplate = "@IMPORTINTERFACES@"; 36 String importServiceInterfacesTemplate = "@IMPORTSERVICEINTERFACE@"; 37 String lowercaseClassNameTemplate = "@classname@"; 38 39 temp = templateContent 40 .replaceAll(packageNameTemplate, packageName) 41 .replaceAll(importModelTemplate, importModelName) 42 .replaceAll(classNameTemplate, className) 43 .replaceAll( 44 importInterfacesTemplate, 45 AuxiliaryStringProcessingUtil.getDaoPackageName( 46 hbmContent).replace(";", ".*;")) 47 .replaceAll( 48 importServiceInterfacesTemplate, 49 AuxiliaryStringProcessingUtil.getServicePackageName( 50 hbmContent).replace(";", ".*;")) 51 .replaceAll( 52 lowercaseClassNameTemplate, 53 String.valueOf(className.toCharArray()[0]) 54 .toLowerCase() + className.substring(1)); 55 FileWriter writer = null; 56 try 57 { 58 File file = new File(outputFileCompletePath); 59 writer = new FileWriter(file); 60 writer.write(temp); 61 62 } 63 catch (Exception e) 64 { 65 e.printStackTrace(); 66 } 67 finally 68 { 69 try 70 { 71 writer.close(); 72 } 73 catch (IOException e) 74 { 75 e.printStackTrace(); 76 } 77 } 78 79 } 80 81 public void generateServiceImpl(String hbmCompletePath, 82 String outputCompletePath) 83 { 84 String hbmContent = FileData.getHbmContent(hbmCompletePath); 85 86 String templateContent = FileData.getTemplateContent(Configer 87 .getConfigerInstance().getDaoTemplatePath()); 88 89 String packageName = AuxiliaryStringProcessingUtil 90 .getServiceImplPackageName(hbmContent); 91 92 String importModelName = AuxiliaryStringProcessingUtil 93 .getImportModelNames(hbmContent); 94 String className = AuxiliaryStringProcessingUtil 95 .getClassName(hbmContent); 96 97 String outputFileCompleteDirectory = FileData 98 .getOutputFileCompletePath(outputCompletePath, hbmContent, 99 packageName); 100 101 String outputFileCompletePath = outputFileCompleteDirectory 102 + File.separator + className + SERVICE_EXT; 103 this.replaceKeyWordAndGenerateServiceImpl(templateContent, 104 outputFileCompletePath, packageName, importModelName, 105 className, hbmContent); 106 } 107 }
Configer.java

1 package code.automatic.generation.framework.hbm2serviceimpl; 2 3 public class Configer 4 { 5 private static Configer configer = new Configer(); 6 private String extName = "\\service_impl_template.java"; 7 private String daoTemplatePath; 8 9 private Configer() 10 { 11 12 } 13 14 public static Configer getConfigerInstance() 15 { 16 return configer; 17 } 18 19 public String getDaoTemplatePath() 20 { 21 return daoTemplatePath; 22 } 23 24 public void setDaoTemplatePath(String daoTemplatePath) 25 { 26 this.daoTemplatePath = daoTemplatePath + this.extName; 27 } 28 29 }
15.生成Action---hbm2action
CodeGenerater.java

1 package code.automatic.generation.framework.hbm2action; 2 3 public class CodeGenerater 4 { 5 private static String outputDirectory; 6 7 public static void main(String[] args) 8 { 9 10 System.out.println("Action 开始生成!"); 11 12 for (String temp : args) 13 { 14 15 if (temp.startsWith("--outputDirectory")) 16 { 17 outputDirectory = temp 18 .substring("--outputDirectory".length() + 1); 19 } 20 else if (temp.startsWith("--templateDirectory")) 21 { 22 Configer.getConfigerInstance().setDaoTemplatePath( 23 temp.substring("--templateDirectory".length() + 1)); 24 } 25 else 26 { 27 CodeUtil.getCodeUtilInstance().generateAction(temp, 28 outputDirectory); 29 } 30 31 } 32 System.out.println("Action 生成完毕!"); 33 } 34 }
CodeUtil.java

1 package code.automatic.generation.framework.hbm2action; 2 3 import java.io.File; 4 5 import code.automatic.generation.framework.util.AuxiliaryStringProcessingUtil; 6 import code.automatic.generation.framework.util.ClassUtil; 7 import code.automatic.generation.framework.util.FileData; 8 9 public class CodeUtil 10 { 11 private String ACTION_SUFFIX = "Action.java"; 12 private String hbmCompletePath; 13 private String outputCompletePath; 14 15 private static CodeUtil codeUtil = new CodeUtil(); 16 17 private CodeUtil() 18 { 19 20 } 21 22 public static CodeUtil getCodeUtilInstance() 23 { 24 return codeUtil; 25 } 26 27 private String replaceKeyWord(String templateContent, String packageName, 28 String ImportModelNames, String importServiceInterfaces, 29 String className) 30 { 31 String temp = null; 32 String packageNameTemplate = "@ACTIONPACKAGENAME@"; 33 String importModelTemplate = "@IMPORTMODELS@"; 34 String classNameTemplate = "@CLASSNAME@"; 35 String importInterfacesTemplate = "@IMPORTSERVICEINTERFACE@"; 36 37 temp = templateContent.replaceAll(packageNameTemplate, packageName) 38 .replaceAll(importModelTemplate, ImportModelNames) 39 .replaceAll(classNameTemplate, className) 40 .replaceAll(importInterfacesTemplate, importServiceInterfaces); 41 return temp; 42 43 } 44 45 public void generateAction(String hbmCompletePath, String outputCompletePath) 46 { 47 this.hbmCompletePath = hbmCompletePath; 48 this.outputCompletePath = outputCompletePath; 49 this.generateAddAndUpdateAction(Configer.getConfigerInstance() 50 .getAddActionTemplateFileName(), 51 AuxiliaryStringProcessingUtil.ADD); 52 this.generateDeleteListAndOtherAction(Configer.getConfigerInstance() 53 .getDeleteActionTemplateFileName(), 54 AuxiliaryStringProcessingUtil.DELETE); 55 this.generateDeleteListAndOtherAction(Configer.getConfigerInstance() 56 .getUpdatePreActionTemplateFileName(), 57 AuxiliaryStringProcessingUtil.UPDATEPRE); 58 this.generateAddAndUpdateAction(Configer.getConfigerInstance() 59 .getUpdateActionTemplateFileName(), 60 AuxiliaryStringProcessingUtil.UPDATE); 61 this.generateDeleteListAndOtherAction(Configer.getConfigerInstance() 62 .getListActionTemplateFileName(), 63 AuxiliaryStringProcessingUtil.LIST); 64 65 } 66 67 private void generateAddAndUpdateAction(String config, String filePrefix) 68 { 69 String allFieldsTemplate = "@ADDATTRIBUTES@"; 70 String allSetterAndGetterTemplate = "@ADDGETTERANDSETTER@"; 71 String setPropertyTemplate = "@SETPROPERTY@"; 72 73 String hbmContent = FileData.getFileContent(hbmCompletePath); 74 String templateContent = FileData.getFileContent(config); 75 String packageName = AuxiliaryStringProcessingUtil 76 .getActionPackageName(hbmContent); 77 String outputFileCompletePathWithFileName = FileData 78 .getOutputFileCompletePath(outputCompletePath, hbmContent, 79 packageName) 80 + File.separator 81 + filePrefix 82 + AuxiliaryStringProcessingUtil.getClassName(hbmContent) 83 + ACTION_SUFFIX; 84 85 String ImportModelNames = AuxiliaryStringProcessingUtil 86 .getImportModelNames(hbmContent); 87 String className = AuxiliaryStringProcessingUtil 88 .getClassName(hbmContent); 89 String importServiceInterfaces = AuxiliaryStringProcessingUtil 90 .getImportServiceInterfaces(hbmContent); 91 92 String temp = this 93 .replaceKeyWord(templateContent, packageName, ImportModelNames, 94 importServiceInterfaces, className) 95 .replaceAll(allFieldsTemplate, 96 ClassUtil.getAllFieldFromModel(hbmContent, filePrefix)) 97 .replaceAll(allSetterAndGetterTemplate, 98 ClassUtil.getSetterAndGetterFromModel(filePrefix)) 99 .replaceAll(setPropertyTemplate, ClassUtil.setFields()); 100 101 FileData.WriteFile(outputFileCompletePathWithFileName, temp); 102 103 } 104 105 private void generateDeleteListAndOtherAction(String config, 106 String filePrefix) 107 { 108 String hbmContent = FileData.getFileContent(hbmCompletePath); 109 String templateContent = FileData.getFileContent(config); 110 String packageName = AuxiliaryStringProcessingUtil 111 .getActionPackageName(hbmContent); 112 String outputFileCompletePathWithFileName = FileData 113 .getOutputFileCompletePath(outputCompletePath, hbmContent, 114 packageName) 115 + File.separator 116 + filePrefix 117 + AuxiliaryStringProcessingUtil.getClassName(hbmContent) 118 + ACTION_SUFFIX; 119 120 String ImportModelNames = AuxiliaryStringProcessingUtil 121 .getImportModelNames(hbmContent); 122 String className = AuxiliaryStringProcessingUtil 123 .getClassName(hbmContent); 124 String importServiceInterfaces = AuxiliaryStringProcessingUtil 125 .getImportServiceInterfaces(hbmContent); 126 127 String temp = this.replaceKeyWord(templateContent, packageName, 128 ImportModelNames, importServiceInterfaces, className); 129 FileData.WriteFile(outputFileCompletePathWithFileName, temp); 130 131 } 132 133 }
Configer.java

1 package code.automatic.generation.framework.hbm2action; 2 3 public class Configer 4 { 5 private static Configer configer = new Configer(); 6 private String addActionTemplateFileName = "\\add_action_template.java"; 7 private String deleteActionTemplateFileName = "\\delete_action_template.java"; 8 private String listActionTemplateFileName = "\\list_action_template.java"; 9 private String updatePreActionTemplateFileName = "\\update_pre_action_template.java"; 10 private String updateActionTemplateFileName = "\\update_action_template.java"; 11 private String daoTemplatePath; 12 13 private Configer() 14 { 15 16 } 17 18 public static Configer getConfigerInstance() 19 { 20 return configer; 21 } 22 23 public String getAddActionTemplateFileName() 24 { 25 return this.daoTemplatePath + addActionTemplateFileName; 26 } 27 28 public void setAddActionTemplateFileName(String addActionTemplateFileName) 29 { 30 this.addActionTemplateFileName = addActionTemplateFileName; 31 } 32 33 public String getDaoTemplatePath() 34 { 35 return daoTemplatePath; 36 } 37 38 public void setDaoTemplatePath(String daoTemplatePath) 39 { 40 this.daoTemplatePath = daoTemplatePath; 41 } 42 43 public String getDeleteActionTemplateFileName() 44 { 45 return this.daoTemplatePath + deleteActionTemplateFileName; 46 } 47 48 public void setDeleteActionTemplateFileName( 49 String deleteActionTemplateFileName) 50 { 51 this.deleteActionTemplateFileName = deleteActionTemplateFileName; 52 } 53 54 public String getListActionTemplateFileName() 55 { 56 return this.daoTemplatePath + listActionTemplateFileName; 57 } 58 59 public void setListActionTemplateFileName(String listActionTemplateFileName) 60 { 61 this.listActionTemplateFileName = listActionTemplateFileName; 62 } 63 64 public String getUpdatePreActionTemplateFileName() 65 { 66 return this.daoTemplatePath + updatePreActionTemplateFileName; 67 } 68 69 public void setUpdatePreActionTemplateFileName( 70 String updatePreActionTemplateFileName) 71 { 72 this.updatePreActionTemplateFileName = updatePreActionTemplateFileName; 73 } 74 75 public String getUpdateActionTemplateFileName() 76 { 77 return this.daoTemplatePath + updateActionTemplateFileName; 78 } 79 80 public void setUpdateActionTemplateFileName( 81 String updateActionTemplateFileName) 82 { 83 this.updateActionTemplateFileName = updateActionTemplateFileName; 84 } 85 86 }
16.生成Jsp---hbm2jsp
CodeGenerater.java

1 package code.automatic.generation.framework.hbm2jsp; 2 3 public class CodeGenerater 4 { 5 private static String outputDirectory; 6 7 public static void main(String[] args) 8 { 9 10 System.out.println("Jsp开始生成!"); 11 12 for (String temp : args) 13 { 14 15 if (temp.startsWith("--outputDirectory")) 16 { 17 outputDirectory = temp 18 .substring("--outputDirectory".length() + 1); 19 } 20 else if (temp.startsWith("--templateDirectory")) 21 { 22 Configer.getConfigerInstance().setJspTemplatePath( 23 temp.substring("--templateDirectory".length() + 1)); 24 } 25 else 26 { 27 CodeUtil.getCodeUtilInstance().generateJsp(temp, 28 outputDirectory); 29 } 30 31 } 32 System.out.println("Jsp生成完毕!"); 33 } 34 }
CodeUtil.java

1 package code.automatic.generation.framework.hbm2jsp; 2 3 import java.io.File; 4 5 import code.automatic.generation.framework.util.AuxiliaryStringProcessingUtil; 6 import code.automatic.generation.framework.util.FileData; 7 8 public class CodeUtil 9 { 10 11 private static CodeUtil codeUtil = new CodeUtil(); 12 private String hbmCompletePath; 13 private String outputCompletePath; 14 private String hbmContent; 15 16 private CodeUtil() 17 { 18 19 } 20 21 public static CodeUtil getCodeUtilInstance() 22 { 23 return codeUtil; 24 } 25 26 public void generateJsp(String hbmCompletePath, String outputCompletePath) 27 { 28 this.hbmCompletePath = hbmCompletePath; 29 this.outputCompletePath = outputCompletePath; 30 this.generateAddJsp(); 31 this.generateListJsp(); 32 this.generateUpdateJsp(); 33 34 } 35 36 private void generateAddJsp() 37 { 38 this.hbmContent = FileData.getFileContent(hbmCompletePath); 39 String templateContent = FileData.getFileContent(Configer 40 .getConfigerInstance().getAddJspTemplate()); 41 String outputFileCompletePathWithFileName = FileData 42 .getOutputFileCompletePathOnlyWithClassName(outputCompletePath, 43 hbmContent) 44 + File.separator 45 + AuxiliaryStringProcessingUtil.ADD 46 + AuxiliaryStringProcessingUtil.getClassName(hbmContent) 47 + ".jsp"; 48 49 String templateTrs = "<tr bgcolor=\"#f0f0f0\">\n\t<td bgcolor=\"#78A1E6\">@property@:" 50 + "</td>\n<td bgcolor=\"#78A1E6\"><input type=text name=\"@property@\" " 51 + "size=\"40\" onblur=\"validate@PROPERTY@(this.value)\" /></td>\n<td bgcolor" 52 + "=\"#78A1E6\"><span id=\"@property@_msg\"><font color=\"red\">*</font></span></td>\n</tr>\n"; 53 String prepareReplacementString = AuxiliaryStringProcessingUtil 54 .replaceKeyWord(AuxiliaryStringProcessingUtil.ADD, templateTrs, 55 this.hbmContent); 56 String finalSourceCode = AuxiliaryStringProcessingUtil 57 .getFinalSourceCode(AuxiliaryStringProcessingUtil.ADD, 58 this.hbmContent, templateContent, 59 prepareReplacementString); 60 FileData.WriteFile(outputFileCompletePathWithFileName, finalSourceCode); 61 62 } 63 64 private void generateListJsp() 65 { 66 String templateContent = FileData.getFileContent(Configer 67 .getConfigerInstance().getListJspTemplate()); 68 String outputFileCompletePathWithFileName = FileData 69 .getOutputFileCompletePathOnlyWithClassName(outputCompletePath, 70 hbmContent) 71 + File.separator 72 + AuxiliaryStringProcessingUtil.LIST 73 + AuxiliaryStringProcessingUtil.getClassName(hbmContent) 74 + ".jsp"; 75 String templateTds = "\t\t\t<td align=\"center\" bgcolor=\"#78A1E6\" nowrap=\"nowrap\">@property@</td>\n"; 76 String templateTdsRecord = "\t\t\t<td align=\"center\" bgcolor=\"#E6ECF9\"><s:property value=\"#dc.@property@\" /></td>\n"; 77 78 String[] prepareReplacementString = new String[2]; 79 prepareReplacementString[0] = AuxiliaryStringProcessingUtil 80 .replaceKeyWord(AuxiliaryStringProcessingUtil.LIST, 81 templateTds, this.hbmContent); 82 prepareReplacementString[1] = AuxiliaryStringProcessingUtil 83 .replaceKeyWord(AuxiliaryStringProcessingUtil.LIST, 84 templateTdsRecord, this.hbmContent); 85 86 String finalSourceCode = AuxiliaryStringProcessingUtil 87 .getFinalSourceCode(AuxiliaryStringProcessingUtil.LIST, 88 this.hbmContent, templateContent, 89 prepareReplacementString); 90 91 FileData.WriteFile(outputFileCompletePathWithFileName, finalSourceCode); 92 } 93 94 private void generateUpdateJsp() 95 { 96 String templateContent = FileData.getFileContent(Configer 97 .getConfigerInstance().getUpdateJspTemplate()); 98 String outputFileCompletePathWithFileName = FileData 99 .getOutputFileCompletePathOnlyWithClassName(outputCompletePath, 100 hbmContent) 101 + File.separator 102 + "Update" 103 + AuxiliaryStringProcessingUtil.getClassName(hbmContent) 104 + ".jsp"; 105 106 String templateItem = "<tr bgcolor=\"#f0f0f0\">\n\t<td bgcolor=\"#78A1E6\">@property@:</td>\n\t<td bgcolor=\"#78A1E6\"><s:textfield name=\"@property@\" value=\"%{bean.@property@}\" size=\"40\" onblur=\"validate@PROPERTY@(this.value)\" /></td>\n\t<td bgcolor=\"#78A1E6\"><span id=\"@property@_msg\"><font color=\"red\">*</font></span></td>\n</tr>"; 107 108 String prepareReplacementString = AuxiliaryStringProcessingUtil 109 .replaceKeyWord(AuxiliaryStringProcessingUtil.UPDATE, 110 templateItem, this.hbmContent); 111 String finalSourceCode = AuxiliaryStringProcessingUtil 112 .getFinalSourceCode(AuxiliaryStringProcessingUtil.UPDATE, 113 this.hbmContent, templateContent, 114 prepareReplacementString); 115 FileData.WriteFile(outputFileCompletePathWithFileName, finalSourceCode); 116 } 117 118 }
Configer.java

1 package code.automatic.generation.framework.hbm2jsp; 2 3 public class Configer 4 { 5 private static Configer configer = new Configer(); 6 private String addJspTemplate = "\\add_template.jsp"; 7 private String listJspTemplate = "\\list_template.jsp"; 8 private String updateJspTemplate = "\\update_template.jsp"; 9 private String jspTemplatePath; 10 11 private Configer() 12 { 13 14 } 15 16 public static Configer getConfigerInstance() 17 { 18 return configer; 19 } 20 21 public void setJspTemplatePath(String jspTemplatePath) 22 { 23 this.jspTemplatePath = jspTemplatePath; 24 } 25 26 public String getAddJspTemplate() 27 { 28 return this.jspTemplatePath + addJspTemplate; 29 } 30 31 public String getListJspTemplate() 32 { 33 return this.jspTemplatePath + listJspTemplate; 34 } 35 36 public String getUpdateJspTemplate() 37 { 38 return this.jspTemplatePath + updateJspTemplate; 39 } 40 41 }
17.增加Struts.xml的配置
CodeGenerater.java

1 package code.automatic.generation.framework.hbm2strutsxml; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class CodeGenerater 7 { 8 private static String outputDirectory; 9 private static String templateDirectory; 10 private static List<String> hbmFiles = new ArrayList<String>(); 11 12 public static void main(String[] args) 13 { 14 15 System.out.println("开始生成Struts.xml配置文件...!"); 16 17 for (String temp : args) 18 { 19 20 if (temp.startsWith("--outputDirectory")) 21 { 22 outputDirectory = temp 23 .substring("--outputDirectory".length() + 1); 24 } 25 else 26 { 27 hbmFiles.add(temp); 28 } 29 30 } 31 CodeUtil.getCodeUtilInstance().generateStrutsXML(outputDirectory, 32 templateDirectory, hbmFiles); 33 34 System.out.println("Struts.xml配置文件生成完毕!"); 35 } 36 }
CodeUtil.java

1 package code.automatic.generation.framework.hbm2strutsxml; 2 3 import java.io.File; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 import java.io.Writer; 7 import java.util.List; 8 9 import org.jdom.Document; 10 import org.jdom.Element; 11 import org.jdom.input.SAXBuilder; 12 import org.jdom.output.Format; 13 import org.jdom.output.XMLOutputter; 14 15 import code.automatic.generation.framework.util.AuxiliaryStringProcessingUtil; 16 import code.automatic.generation.framework.util.FileData; 17 18 public class CodeUtil 19 { 20 private static CodeUtil codeUtil = new CodeUtil(); 21 22 private CodeUtil() 23 { 24 25 } 26 27 public static CodeUtil getCodeUtilInstance() 28 { 29 return codeUtil; 30 } 31 32 @SuppressWarnings("unchecked") 33 public void generateStrutsXML(String outputDirectory, 34 String templateDirectory, List<String> hbmFiles) 35 { 36 Writer writer = null; 37 try 38 { 39 SAXBuilder builder = new SAXBuilder(); 40 builder.setFeature( 41 "http://apache.org/xml/features/nonvalidating/load-external-dtd", 42 false); 43 Document doc = builder.build(new File(outputDirectory 44 + File.separator + "struts.xml")); 45 Element root = doc.getRootElement(); 46 root.addContent(this.getConstant("struts.configuration.xm.reload", 47 "true")); 48 root.addContent(this.getConstant("struts.devMode", "true")); 49 root.addContent(this.getConstant("struts.multipart.maxSize", 50 "2000000000000000000")); 51 root.addContent(this.getConstant("struts.ui.theme", "simple")); 52 root.addContent(this.getConstant("struts.action.excludePattern", 53 "/dwr/.*,/dwr/test/.*")); 54 55 String className = null; 56 boolean flag = false; 57 List<Element> packageElements = root.getChildren("package"); 58 59 for (String hbmFile : hbmFiles) 60 { 61 String hbmContent = FileData.getFileContent(hbmFile); 62 className = AuxiliaryStringProcessingUtil 63 .getClassName(hbmContent); 64 for (Element pack : packageElements) 65 { 66 String nameValue = pack.getAttributeValue("name"); 67 if (className.equals(nameValue)) 68 { 69 flag = true; 70 break; 71 } 72 73 } 74 if (!flag) 75 { 76 Element packageElement = new Element("package"); 77 78 packageElement.setAttribute("name", className) 79 .setAttribute("extends", "struts-default") 80 .setAttribute("namespace", "/" + className); 81 82 Element listAction = new Element("action"); 83 packageElement.addContent(listAction); 84 this.SetPropertyForElement("List", className, listAction, 85 "List" + className + ".jsp", false); 86 87 Element addAction = new Element("action"); 88 packageElement.addContent(addAction); 89 this.SetPropertyForElement("Add", className, addAction, 90 null, true); 91 92 Element deleteAction = new Element("action"); 93 packageElement.addContent(deleteAction); 94 this.SetPropertyForElement("Delete", className, 95 deleteAction, null, true); 96 97 Element updatePreAction = new Element("action"); 98 packageElement.addContent(updatePreAction); 99 this.SetPropertyForElement("UpdatePre", className, 100 updatePreAction, "Update" + className + ".jsp", 101 false); 102 103 Element updateAction = new Element("action"); 104 packageElement.addContent(updateAction); 105 this.SetPropertyForElement("Update", className, 106 updateAction, null, true); 107 108 root.addContent(packageElement); 109 } 110 } 111 112 Format format = Format.getPrettyFormat(); 113 format.setEncoding("UTF-8"); 114 format.setIndent(" "); 115 XMLOutputter out = new XMLOutputter(format); 116 writer = new FileWriter(outputDirectory + File.separator 117 + "struts.xml"); 118 out.output(doc, writer); 119 } 120 catch (Exception e) 121 { 122 e.printStackTrace(); 123 } 124 finally 125 { 126 try 127 { 128 writer.close(); 129 } 130 catch (IOException e) 131 { 132 e.printStackTrace(); 133 } 134 } 135 136 } 137 138 private void SetPropertyForElement(String attrPrefix, String className, 139 Element element, String textValue, boolean param) 140 { 141 element.setAttribute("name", attrPrefix + className + "Action") 142 .setAttribute("class", attrPrefix + className); 143 Element result = new Element("result"); 144 element.addContent(result); 145 if (!param) 146 { 147 result.setAttribute("name", "success").setText(textValue); 148 } 149 else 150 { 151 result.setAttribute("name", "success").setAttribute("type", 152 "redirectAction"); 153 Element paramElement = new Element("param"); 154 result.addContent(paramElement); 155 paramElement.setAttribute("name", "actionName").setText( 156 "List" + className + "Action"); 157 if (!attrPrefix.equals("Add")) 158 { 159 Element paramStartElement = new Element("param"); 160 result.addContent(paramStartElement); 161 paramStartElement.setAttribute("name", "start").setText( 162 "${start}"); 163 Element paramMaxLineSizeElement = new Element("param"); 164 result.addContent(paramMaxLineSizeElement); 165 paramMaxLineSizeElement.setAttribute("name", "maxLineSize") 166 .setText("${maxLineSize}"); 167 168 } 169 } 170 } 171 172 private Element getConstant(String name, String value) 173 { 174 Element result = new Element("constant"); 175 result.setAttribute("name", name).setAttribute("value", value); 176 return result; 177 } 178 179 }
18.生成applicationContext-basic.xml
CodeGenerater.java

1 package code.automatic.generation.framework.hbm2xml; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class CodeGenerater 7 { 8 private static String outputDirectory; 9 private static String springBasicFileName; 10 private static String dbProperty; 11 private static String hibernateProperty; 12 private static String projectRootPath; 13 private static String hbmDirectory; 14 private static List<String> hbmFiles = new ArrayList<String>(); 15 16 public static void main(String[] args) 17 { 18 19 System.out.println("开始生成Spring 基础配置文件...!"); 20 21 for (String temp : args) 22 { 23 24 if (temp.startsWith("--outputDirectory")) 25 { 26 outputDirectory = temp 27 .substring("--outputDirectory".length() + 1); 28 } 29 else if (temp.startsWith("--springxmlFilename")) 30 { 31 springBasicFileName = temp.substring("--springxmlFilename" 32 .length() + 1); 33 } 34 else if (temp.startsWith("--dbproperty")) 35 { 36 dbProperty = temp.substring("--dbproperty".length() + 1); 37 } 38 else if (temp.startsWith("--hibernateProperty")) 39 { 40 hibernateProperty = temp.substring("--hibernateProperty" 41 .length() + 1); 42 } 43 else if (temp.startsWith("--hbmDirectory")) 44 { 45 hbmDirectory = temp.substring("--hbmDirectory".length() + 1); 46 } 47 else if (temp.startsWith("--projectDirectory")) 48 { 49 projectRootPath = temp 50 .substring("--projectDirectory".length() + 1); 51 } 52 else 53 { 54 hbmFiles.add(temp); 55 } 56 57 } 58 CodeUtil.getCodeUtilInstance().generateSpringBasicXML(outputDirectory, 59 springBasicFileName, dbProperty, hibernateProperty, 60 projectRootPath,hbmDirectory ,hbmFiles); 61 System.out.println("Spring 基础配置文件生成完毕!"); 62 } 63 }
CodeUtil.java

1 package code.automatic.generation.framework.hbm2xml; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.io.Writer; 9 import java.util.Enumeration; 10 import java.util.List; 11 import java.util.Properties; 12 13 import org.jdom.Attribute; 14 import org.jdom.Document; 15 import org.jdom.Element; 16 import org.jdom.Namespace; 17 import org.jdom.output.Format; 18 import org.jdom.output.XMLOutputter; 19 20 public class CodeUtil 21 { 22 private static CodeUtil codeUtil = new CodeUtil(); 23 24 private CodeUtil() 25 { 26 27 } 28 29 public static CodeUtil getCodeUtilInstance() 30 { 31 return codeUtil; 32 } 33 34 public void generateSpringBasicXML(String outputDirectory, 35 String springBasicFileName, String dbProperty, 36 String hibernateProperty, String projectRootPath, 37 String hbmDirectory, List<String> hbmFiles) 38 { 39 Writer writer = null; 40 InputStream inStream = null; 41 try 42 { 43 Namespace ns1 = Namespace 44 .getNamespace("http://www.springframework.org/schema/beans"); 45 Namespace ns2 = Namespace.getNamespace("xsi", 46 "http://www.w3.org/2001/XMLSchema-instance"); 47 Namespace ns3 = Namespace.getNamespace("tx", 48 "http://www.springframework.org/schema/tx"); 49 Namespace ns4 = Namespace.getNamespace("p", 50 "http://www.springframework.org/schema/p"); 51 Namespace ns5 = Namespace.getNamespace("context", 52 "http://www.springframework.org/schema/context"); 53 Namespace ns6 = Namespace.getNamespace("aop", 54 "http://www.springframework.org/schema/aop"); 55 56 Element root = new Element("beans", ns1); 57 root.addNamespaceDeclaration(ns2); 58 root.addNamespaceDeclaration(ns3); 59 root.addNamespaceDeclaration(ns4); 60 root.addNamespaceDeclaration(ns5); 61 root.addNamespaceDeclaration(ns6); 62 63 Document doc = new Document(root); 64 root.setAttribute(new Attribute( 65 "schemaLocation", 66 "http://www.springframework.org/schema/beans " 67 + "http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" 68 + " " 69 + "http://www.springframework.org/schema/context " 70 + "http://www.springframework.org/schema/context/spring-context-2.5.xsd" 71 + " " 72 + "http://www.springframework.org/schema/tx " 73 + "http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" 74 + " " 75 + "http://www.springframework.org/schema/aop " 76 + "http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" 77 + " ", ns2)); 78 79 Element dataSourceBean = new Element("bean", ns1); 80 81 dataSourceBean.setAttribute("id", "dataSource"); 82 dataSourceBean.setAttribute("class", 83 "org.apache.commons.dbcp.BasicDataSource"); 84 dataSourceBean.setAttribute("destroy-method", "close"); 85 root.addContent(dataSourceBean); 86 87 inStream = new FileInputStream(projectRootPath + File.separator 88 + dbProperty); 89 Properties pro = new Properties(); 90 pro.load(inStream); 91 Enumeration<?> em = pro.propertyNames(); 92 while (em.hasMoreElements()) 93 { 94 String key = (String) em.nextElement(); 95 String value = pro.getProperty(key); 96 Element property = new Element("property", ns1); 97 property.setAttribute("name", key).setAttribute("value", value); 98 dataSourceBean.addContent(property); 99 } 100 101 Element sessionFactoryBean = new Element("bean", ns1); 102 sessionFactoryBean 103 .setAttribute("id", "sessionFactory") 104 .setAttribute("class", 105 "org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"); 106 root.addContent(sessionFactoryBean); 107 108 Element dataSourceProperty = new Element("property", ns1); 109 dataSourceProperty.setAttribute("name", "dataSource").setAttribute( 110 "ref", "dataSource"); 111 sessionFactoryBean.addContent(dataSourceProperty); 112 113 Element mappingResourcesProperty = new Element("property", ns1); 114 mappingResourcesProperty.setAttribute("name", "mappingResources"); 115 sessionFactoryBean.addContent(mappingResourcesProperty); 116 117 Element list = new Element("list", ns1); 118 mappingResourcesProperty.addContent(list); 119 for (String completeHbmPath : hbmFiles) 120 { 121 Element value = new Element("value", ns1); 122 value.setText(completeHbmPath.substring(completeHbmPath.lastIndexOf("\\")+1)); 123 list.addContent(value); 124 125 } 126 127 Element hibernatePropertiesProperty = new Element("property", ns1); 128 hibernatePropertiesProperty.setAttribute("name", 129 "hibernateProperties"); 130 sessionFactoryBean.addContent(hibernatePropertiesProperty); 131 Element props = new Element("props", ns1); 132 hibernatePropertiesProperty.addContent(props); 133 inStream = new FileInputStream(projectRootPath + File.separator 134 + hibernateProperty); 135 pro = new Properties(); 136 pro.load(inStream); 137 em = pro.propertyNames(); 138 while (em.hasMoreElements()) 139 { 140 String key = (String) em.nextElement(); 141 String value = pro.getProperty(key); 142 Element prop = new Element("prop", ns1); 143 prop.setAttribute("key", key); 144 prop.setText(value); 145 props.addContent(prop); 146 } 147 148 Element hibernateTemplateBean = new Element("bean", ns1); 149 root.addContent(hibernateTemplateBean); 150 hibernateTemplateBean 151 .setAttribute("name", "hibernateTemplate") 152 .setAttribute("class", 153 "org.springframework.orm.hibernate3.HibernateTemplate"); 154 Element sessionFactoryRefBean = new Element("property", ns1); 155 hibernateTemplateBean.addContent(sessionFactoryRefBean); 156 sessionFactoryRefBean.setAttribute("name", "sessionFactory") 157 .setAttribute("ref", "sessionFactory"); 158 159 Element transactionManagerBean = new Element("bean", ns1); 160 root.addContent(transactionManagerBean); 161 Element sessionFactory = new Element("property", ns1); 162 transactionManagerBean.addContent(sessionFactory); 163 sessionFactory.setAttribute("name", "sessionFactory").setAttribute( 164 "ref", "sessionFactory"); 165 transactionManagerBean 166 .setAttribute("id", "transactionManager") 167 .setAttribute("class", 168 "org.springframework.orm.hibernate3.HibernateTransactionManager"); 169 Element aopconfig = new Element("config", ns6); 170 root.addContent(aopconfig); 171 Element pointcut = new Element("pointcut", ns6); 172 aopconfig.addContent(pointcut); 173 pointcut.setAttribute("expression", 174 "execution(public * com.arimadisp.service.impl..*.*(..))") 175 .setAttribute("id", "servicePoinitcut"); 176 Element advisor = new Element("advisor", ns6); 177 aopconfig.addContent(advisor); 178 advisor.setAttribute("advice-ref", "txAdvice").setAttribute( 179 "pointcut-ref", "servicePoinitcut"); 180 181 Element txAdvice = new Element("advice", ns3); 182 root.addContent(txAdvice); 183 txAdvice.setAttribute("id", "txAdvice").setAttribute( 184 "transaction-manager", "transactionManager"); 185 Element txAttributes = new Element("attributes", ns3); 186 txAdvice.addContent(txAttributes); 187 Element txMethod1 = new Element("method", ns3); 188 txAttributes.addContent(txMethod1); 189 txMethod1.setAttribute("name", "get*").setAttribute("read-only", 190 "true"); 191 192 Element txMethod2 = new Element("method", ns3); 193 txAttributes.addContent(txMethod2); 194 txMethod2.setAttribute("name", "update*").setAttribute( 195 "propagation", "REQUIRED"); 196 197 Element txMethod3 = new Element("method", ns3); 198 txAttributes.addContent(txMethod3); 199 txMethod3.setAttribute("name", "save*").setAttribute("propagation", 200 "REQUIRED"); 201 202 Element txMethod4 = new Element("method", ns3); 203 txAttributes.addContent(txMethod4); 204 txMethod4.setAttribute("name", "remove*").setAttribute( 205 "propagation", "REQUIRED"); 206 207 Format format = Format.getPrettyFormat(); 208 format.setEncoding("UTF-8"); 209 format.setIndent(" "); 210 XMLOutputter out = new XMLOutputter(format); 211 writer = new FileWriter(outputDirectory + springBasicFileName); 212 out.output(doc, writer); 213 } 214 catch (Exception e) 215 { 216 e.printStackTrace(); 217 } 218 finally 219 { 220 try 221 { 222 writer.close(); 223 inStream.close(); 224 } 225 catch (IOException e) 226 { 227 e.printStackTrace(); 228 } 229 } 230 231 } 232 }
19.生成Dao层与Service层相关的Spring配置
CodeGenerater.java

1 package code.automatic.generation.framework.hbm2xml.daoconfig; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class CodeGenerater 7 { 8 private static String outputDirectory; 9 private static String springDaoConfigFileName; 10 private static String projectRootPath; 11 private static List<String> hbmFiles = new ArrayList<String>(); 12 13 public static void main(String[] args) 14 { 15 16 System.out.println("开始生成applicationContext-action.xml...!"); 17 18 for (String temp : args) 19 { 20 21 if (temp.startsWith("--outputDirectory")) 22 { 23 outputDirectory = temp 24 .substring("--outputDirectory".length() + 1); 25 } 26 else if (temp.startsWith("--springDaoConfigFileName")) 27 { 28 springDaoConfigFileName = temp 29 .substring("--springDaoConfigFileName".length() + 1); 30 } 31 else if (temp.startsWith("--projectDirectory")) 32 { 33 projectRootPath = temp 34 .substring("--projectDirectory".length() + 1); 35 } 36 else 37 { 38 hbmFiles.add(temp); 39 } 40 41 } 42 CodeUtil.getCodeUtilInstance().generateSpringDaoXML(outputDirectory, 43 springDaoConfigFileName, projectRootPath, hbmFiles); 44 System.out.println("applicationContext-action.xml配置文件生成完毕!"); 45 } 46 }
CodeUtil.java

1 package code.automatic.generation.framework.hbm2xml.daoconfig; 2 3 import java.io.File; 4 import java.io.FileReader; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.io.Writer; 8 import java.util.Arrays; 9 import java.util.List; 10 11 import org.jdom.Attribute; 12 import org.jdom.Document; 13 import org.jdom.Element; 14 import org.jdom.Namespace; 15 import org.jdom.output.Format; 16 import org.jdom.output.XMLOutputter; 17 18 public class CodeUtil 19 { 20 private String ANCHOR = "package"; 21 private String ANCHOR2 = "name"; 22 private String QUOTE = "\""; 23 private String SPOT = "."; 24 private String STAR = "*"; 25 private String SEMI = ";"; 26 private String DAO = "dao.impl"; 27 private String DAO_IMPL = "DaoImpl"; 28 private String SERVICE_IMPL = "ServiceImpl"; 29 private String SERVICE_IMPL_PACKAGE = "service.impl"; 30 private static CodeUtil codeUtil = new CodeUtil(); 31 32 private CodeUtil() 33 { 34 35 } 36 37 public static CodeUtil getCodeUtilInstance() 38 { 39 return codeUtil; 40 } 41 42 private String getFileContent(String fileName) 43 { 44 StringBuffer sbf = new StringBuffer(); 45 FileReader reader = null; 46 try 47 { 48 reader = new FileReader(new File(fileName)); 49 char[] temp = new char[8192]; 50 int n = 0; 51 while ((n = reader.read(temp)) != -1) 52 { 53 sbf.append(Arrays.copyOfRange(temp, 0, n)); 54 } 55 return sbf.toString(); 56 } 57 catch (Exception e) 58 { 59 e.printStackTrace(); 60 } 61 finally 62 { 63 try 64 { 65 reader.close(); 66 } 67 catch (IOException e) 68 { 69 e.printStackTrace(); 70 } 71 } 72 return ""; 73 } 74 75 private String getClassName(String hbmContent) 76 { 77 int pos1 = hbmContent.indexOf(ANCHOR2); 78 int pos2 = hbmContent.indexOf(QUOTE, pos1); 79 int pos3 = hbmContent.indexOf(QUOTE, pos2 + 1); 80 return hbmContent.substring(pos2 + 1, pos3); 81 } 82 83 private String getModelNames(String hbmContent) 84 { 85 int pos1 = hbmContent.indexOf(ANCHOR); 86 int pos2 = hbmContent.indexOf(QUOTE, pos1); 87 int pos3 = hbmContent.indexOf(QUOTE, pos2 + 1); 88 return hbmContent.substring(pos2 + 1, pos3) + SPOT + STAR + SEMI; 89 } 90 91 private String getPackageName(String hbmContent) 92 { 93 String temp = this.getModelNames(hbmContent); 94 temp = temp.substring(0, temp.lastIndexOf(SPOT)); 95 temp = temp.substring(0, temp.lastIndexOf(SPOT) + 1); 96 return temp; 97 } 98 99 public void generateSpringDaoXML(String outputDirectory, 100 String springDaoConfigFileName, String projectRootPath, 101 List<String> hbmFiles) 102 { 103 Writer writer = null; 104 try 105 { 106 Namespace ns1 = Namespace 107 .getNamespace("http://www.springframework.org/schema/beans"); 108 Namespace ns2 = Namespace.getNamespace("xsi", 109 "http://www.w3.org/2001/XMLSchema-instance"); 110 Namespace ns3 = Namespace.getNamespace("tx", 111 "http://www.springframework.org/schema/tx"); 112 Namespace ns4 = Namespace.getNamespace("p", 113 "http://www.springframework.org/schema/p"); 114 Namespace ns5 = Namespace.getNamespace("context", 115 "http://www.springframework.org/schema/context"); 116 Namespace ns6 = Namespace.getNamespace("aop", 117 "http://www.springframework.org/schema/aop"); 118 119 Element root = new Element("beans", ns1); 120 root.addNamespaceDeclaration(ns2); 121 root.addNamespaceDeclaration(ns3); 122 root.addNamespaceDeclaration(ns4); 123 root.addNamespaceDeclaration(ns5); 124 root.addNamespaceDeclaration(ns6); 125 126 Document doc = new Document(root); 127 root.setAttribute(new Attribute( 128 "schemaLocation", 129 "http://www.springframework.org/schema/beans " 130 + "http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" 131 + " " 132 + "http://www.springframework.org/schema/context " 133 + "http://www.springframework.org/schema/context/spring-context-2.5.xsd" 134 + " " 135 + "http://www.springframework.org/schema/tx " 136 + "http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" 137 + " " 138 + "http://www.springframework.org/schema/aop " 139 + "http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" 140 + " ", ns2)); 141 142 for (String completeHbmPath : hbmFiles) 143 { 144 Element daoImplBean = new Element("bean", ns1); 145 root.addContent(daoImplBean); 146 String hbmContent = this.getFileContent(completeHbmPath); 147 String implementationClassName = this.getClassName(hbmContent); 148 String completePackageNamePath = this 149 .getPackageName(hbmContent) 150 + DAO 151 + SPOT 152 + implementationClassName; 153 154 daoImplBean 155 .setAttribute( 156 "id", 157 String.valueOf( 158 implementationClassName.toCharArray()[0]) 159 .toLowerCase() 160 + implementationClassName.substring(1) 161 + DAO_IMPL).setAttribute("class", 162 completePackageNamePath + DAO_IMPL); 163 Element hibernateTemplateProperty = new Element("property", ns1); 164 daoImplBean.addContent(hibernateTemplateProperty); 165 hibernateTemplateProperty.setAttribute("name", 166 "hibernateTemplate").setAttribute("ref", 167 "hibernateTemplate"); 168 Element serviceBean = new Element("bean", ns1); 169 root.addContent(serviceBean); 170 String serviceClassName = this.getPackageName(hbmContent) 171 + SERVICE_IMPL_PACKAGE + SPOT + implementationClassName 172 + SERVICE_IMPL; 173 serviceBean 174 .setAttribute( 175 "id", 176 String.valueOf( 177 implementationClassName.toCharArray()[0]) 178 .toLowerCase() 179 + implementationClassName.substring(1) 180 + SERVICE_IMPL).setAttribute("class", 181 serviceClassName); 182 Element daoImplProperty = new Element("property", ns1); 183 serviceBean.addContent(daoImplProperty); 184 185 daoImplProperty 186 .setAttribute( 187 "name", 188 String.valueOf( 189 implementationClassName.toCharArray()[0]) 190 .toLowerCase() 191 + implementationClassName.substring(1) 192 + "Dao") 193 .setAttribute( 194 "ref", 195 String.valueOf( 196 implementationClassName.toCharArray()[0]) 197 .toLowerCase() 198 + implementationClassName.substring(1) 199 + DAO_IMPL); 200 } 201 202 Format format = Format.getPrettyFormat(); 203 format.setEncoding("UTF-8"); 204 format.setIndent(" "); 205 XMLOutputter out = new XMLOutputter(format); 206 writer = new FileWriter(outputDirectory + springDaoConfigFileName); 207 out.output(doc, writer); 208 } 209 catch (Exception e) 210 { 211 e.printStackTrace(); 212 } 213 finally 214 { 215 try 216 { 217 writer.close(); 218 } 219 catch (IOException e) 220 { 221 e.printStackTrace(); 222 } 223 } 224 225 } 226 }
20.生成Action相关的Spring配置
CodeGenerater.java

1 package code.automatic.generation.framework.hbm2xml.actionconfig; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class CodeGenerater 7 { 8 private static String outputDirectory; 9 private static String springActionConfigFileName; 10 private static String projectRootPath; 11 private static List<String> hbmFiles = new ArrayList<String>(); 12 13 public static void main(String[] args) 14 { 15 16 System.out.println("开始生成Spring Action配置文件...!"); 17 18 for (String temp : args) 19 { 20 21 if (temp.startsWith("--outputDirectory")) 22 { 23 outputDirectory = temp 24 .substring("--outputDirectory".length() + 1); 25 } 26 else if (temp.startsWith("--springActionConfigFileName")) 27 { 28 springActionConfigFileName = temp 29 .substring("--springActionConfigFileName".length() + 1); 30 } 31 else if (temp.startsWith("--projectDirectory")) 32 { 33 projectRootPath = temp 34 .substring("--projectDirectory".length() + 1); 35 } 36 else 37 { 38 hbmFiles.add(temp); 39 } 40 41 } 42 CodeUtil.getCodeUtilInstance().generateSpringActionXML(outputDirectory, 43 springActionConfigFileName, projectRootPath, hbmFiles); 44 45 System.out.println("Spring Action配置文件生成完毕!"); 46 } 47 }
CodeUtil.java

1 package code.automatic.generation.framework.hbm2xml.actionconfig; 2 3 import java.io.FileWriter; 4 import java.io.IOException; 5 import java.io.Writer; 6 import java.util.List; 7 8 import org.jdom.Attribute; 9 import org.jdom.Document; 10 import org.jdom.Element; 11 import org.jdom.Namespace; 12 import org.jdom.output.Format; 13 import org.jdom.output.XMLOutputter; 14 15 import code.automatic.generation.framework.util.AuxiliaryStringProcessingUtil; 16 import code.automatic.generation.framework.util.FileData; 17 18 public class CodeUtil 19 { 20 private static CodeUtil codeUtil = new CodeUtil(); 21 private String list_Action = "List"; 22 private String add_Action = "Add"; 23 private String delete_Action = "Delete"; 24 private String updatePre_Action = "UpdatePre"; 25 private String update_Action = "Update"; 26 private String action = "Action"; 27 28 private CodeUtil() 29 { 30 31 } 32 33 public static CodeUtil getCodeUtilInstance() 34 { 35 return codeUtil; 36 } 37 38 public void generateSpringActionXML(String outputDirectory, 39 String springActionConfigFileName, String projectRootPath, 40 List<String> hbmFiles) 41 { 42 Writer writer = null; 43 try 44 { 45 Namespace ns1 = Namespace 46 .getNamespace("http://www.springframework.org/schema/beans"); 47 Namespace ns2 = Namespace.getNamespace("xsi", 48 "http://www.w3.org/2001/XMLSchema-instance"); 49 Namespace ns3 = Namespace.getNamespace("tx", 50 "http://www.springframework.org/schema/tx"); 51 Namespace ns4 = Namespace.getNamespace("p", 52 "http://www.springframework.org/schema/p"); 53 Namespace ns5 = Namespace.getNamespace("context", 54 "http://www.springframework.org/schema/context"); 55 Namespace ns6 = Namespace.getNamespace("aop", 56 "http://www.springframework.org/schema/aop"); 57 58 Element root = new Element("beans", ns1); 59 root.addNamespaceDeclaration(ns2); 60 root.addNamespaceDeclaration(ns3); 61 root.addNamespaceDeclaration(ns4); 62 root.addNamespaceDeclaration(ns5); 63 root.addNamespaceDeclaration(ns6); 64 65 Document doc = new Document(root); 66 root.setAttribute(new Attribute( 67 "schemaLocation", 68 "http://www.springframework.org/schema/beans " 69 + "http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" 70 + " " 71 + "http://www.springframework.org/schema/context " 72 + "http://www.springframework.org/schema/context/spring-context-2.5.xsd" 73 + " " 74 + "http://www.springframework.org/schema/tx " 75 + "http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" 76 + " " 77 + "http://www.springframework.org/schema/aop " 78 + "http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" 79 + " ", ns2)); 80 81 for (String completeHbmPath : hbmFiles) 82 { 83 Element listActionBean = new Element("bean", ns1); 84 root.addContent(listActionBean); 85 String hbmContent = FileData.getFileContent(completeHbmPath); 86 this.SetPropertyForElement(hbmContent, listActionBean, 87 list_Action, ns1); 88 89 Element addActionBean = new Element("bean", ns1); 90 root.addContent(addActionBean); 91 this.SetPropertyForElement(hbmContent, addActionBean, 92 add_Action, ns1); 93 94 Element deleteActionBean = new Element("bean", ns1); 95 root.addContent(deleteActionBean); 96 this.SetPropertyForElement(hbmContent, deleteActionBean, 97 delete_Action, ns1); 98 99 Element updatePreActionBean = new Element("bean", ns1); 100 root.addContent(updatePreActionBean); 101 this.SetPropertyForElement(hbmContent, updatePreActionBean, 102 updatePre_Action, ns1); 103 104 Element updateActionBean = new Element("bean", ns1); 105 root.addContent(updateActionBean); 106 this.SetPropertyForElement(hbmContent, updateActionBean, 107 update_Action, ns1); 108 109 } 110 111 Format format = Format.getPrettyFormat(); 112 format.setEncoding("UTF-8"); 113 format.setIndent(" "); 114 XMLOutputter out = new XMLOutputter(format); 115 writer = new FileWriter(outputDirectory 116 + springActionConfigFileName); 117 out.output(doc, writer); 118 } 119 catch (Exception e) 120 { 121 e.printStackTrace(); 122 } 123 finally 124 { 125 try 126 { 127 writer.close(); 128 } 129 catch (IOException e) 130 { 131 e.printStackTrace(); 132 } 133 } 134 135 } 136 137 private void SetPropertyForElement(String hbmContent, Element actionBean, 138 String aciontPrefixName, Namespace ns) 139 { 140 String className = AuxiliaryStringProcessingUtil 141 .getClassName(hbmContent); 142 String name = "service"; 143 String ref = className.substring(0, 1).toLowerCase() 144 + className.substring(1) + "ServiceImpl"; 145 String scope = "prototype"; 146 String id = aciontPrefixName + className; 147 String completeActionClassName = AuxiliaryStringProcessingUtil 148 .getActionPackageName(hbmContent).replace(";", 149 "." + id + action); 150 actionBean.setAttribute("id", id) 151 .setAttribute("class", completeActionClassName) 152 .setAttribute("scope", scope); 153 Element property = new Element("property", ns); 154 actionBean.addContent(property); 155 property.setAttribute("name", name).setAttribute("ref", ref); 156 157 } 158 }
21.依赖的相关工具类
AuxiliaryStringProcessingUtil.java

1 package code.automatic.generation.framework.util; 2 3 public class AuxiliaryStringProcessingUtil 4 { 5 public static String ANCHOR = "package"; 6 public static String ANCHOR2 = "name"; 7 public static String QUOTE = "\""; 8 public static String SPOT = "."; 9 public static String STAR = "*"; 10 public static String SEMI = ";"; 11 public static String ACTION = "action"; 12 public static String SERVICE = "service"; 13 public static String SERVICEIMPL = "service.impl"; 14 public static String ADD = "Add"; 15 public static String DELETE = "Delete"; 16 public static String LIST = "List"; 17 public static String UPDATEPRE = "UpdatePre"; 18 public static String UPDATE = "Update"; 19 public static String DAO = "dao"; 20 public static String DAOIMPL = "dao.impl"; 21 22 // Add 23 public static String LOWERCASE_PROPERTY = "@property@"; // name 24 public static String CAPITAL_PROPERTY = "@PROPERTY@"; // Name 25 public static String FIRST_LETTER_CAPITAL_CLASSNAME = "@CLASSNAME@"; // DcouementCatalog 26 public static String MANAY_TRS = "@MORETRS@"; // 多个TR 27 28 // List(有两个stringTemplate)还有@property@,@CLASSNAME@ 29 public static String TABLE_HEADER = "@MORETDSHEADER@"; // 表头TD 30 public static String EACH_RECORD = "@MORETRSRECORD@"; // 每一条记录TD 31 32 // Update有@property@,@CLASSNAME@,@PROPERTY@ 33 public static String MANY_ITEM = "@MORETRITEMS@"; 34 35 public static String getFinalSourceCode(String filePrefix, 36 String hbmContent, String templateContent, 37 String... prepareReplacementString) 38 { 39 String finalSourceCode = ""; 40 String className = AuxiliaryStringProcessingUtil 41 .getClassName(hbmContent); 42 if ("Add".equals(filePrefix)) 43 { 44 finalSourceCode = templateContent.replaceAll( 45 FIRST_LETTER_CAPITAL_CLASSNAME, className).replaceAll( 46 MANAY_TRS, prepareReplacementString[0]); 47 } 48 else if ("List".equals(filePrefix)) 49 { 50 finalSourceCode = templateContent 51 .replaceAll(FIRST_LETTER_CAPITAL_CLASSNAME, className) 52 .replaceAll(TABLE_HEADER, prepareReplacementString[0]) 53 .replaceAll(EACH_RECORD, prepareReplacementString[1]); 54 } 55 else 56 { 57 finalSourceCode = templateContent.replaceAll( 58 FIRST_LETTER_CAPITAL_CLASSNAME, className).replaceAll( 59 MANY_ITEM, prepareReplacementString[0]); 60 61 } 62 63 return finalSourceCode; 64 } 65 66 public static String replaceKeyWord(String filePrefix, String sourceFile, 67 String hbmContent) 68 { 69 70 StringBuffer result = new StringBuffer(); 71 ClassUtil.getAllFieldFromModel(hbmContent, filePrefix); 72 String[][] fields = ClassUtil.fields; 73 74 for (int i = 0; i < fields.length; i++) 75 { 76 String property = fields[i][1]; // name 77 String firstLetterCapitalProperty = property.substring(0, 1) 78 .toUpperCase() + property.substring(1);// Name 79 String temp = sourceFile.replaceAll(LOWERCASE_PROPERTY, property); 80 if ("Add".equals(filePrefix)) 81 { 82 result.append(temp.replaceAll(CAPITAL_PROPERTY, 83 firstLetterCapitalProperty)); 84 } 85 else if ("List".equals(filePrefix)) 86 { 87 result.append(temp); 88 } 89 else 90 { 91 if (temp.contains("name=\"id\"")) 92 { 93 continue; 94 } 95 result.append(temp.replaceAll(CAPITAL_PROPERTY, 96 firstLetterCapitalProperty)); 97 } 98 99 } 100 return result.toString(); 101 } 102 103 public static String getImportModelNames(String hbmContent) // com.arimadisp.model.*; 104 { 105 int pos1 = hbmContent.indexOf(ANCHOR); 106 int pos2 = hbmContent.indexOf(QUOTE, pos1); 107 int pos3 = hbmContent.indexOf(QUOTE, pos2 + 1); 108 return hbmContent.substring(pos2 + 1, pos3) + SPOT + STAR + SEMI; 109 } 110 111 public static String getActionPackageName(String hbmContent) // com.arimadisp.action.documentcatalog; 112 { 113 String temp = getGeneralPackageName(hbmContent); 114 return temp + ACTION + SPOT + getClassName(hbmContent).toLowerCase() 115 + SEMI; 116 } 117 118 public static String getDaoPackageName(String hbmContent) // com.arimadisp.dao.documentcatalog; 119 { 120 String temp = getGeneralPackageName(hbmContent); 121 return temp + DAO + SPOT + getClassName(hbmContent).toLowerCase() 122 + SEMI; 123 124 } 125 126 public static String getDaoImplPackageName(String hbmContent) // com.arimadisp.dao.impl; 127 { 128 String temp = getGeneralPackageName(hbmContent); 129 return temp + DAOIMPL + SEMI; 130 131 } 132 133 public static String getServicePackageName(String hbmContent) // com.arimadisp.service; 134 { 135 String temp = getGeneralPackageName(hbmContent); 136 return temp + SERVICE + SEMI; 137 138 } 139 140 public static String getServiceImplPackageName(String hbmContent) // com.arimadisp.service.impl; 141 { 142 String temp = getGeneralPackageName(hbmContent); 143 return temp + SERVICEIMPL + SEMI; 144 145 } 146 147 public static String getGeneralPackageName(String hbmContent) // com.arimadisp. 148 { 149 String temp = getImportModelNames(hbmContent); 150 temp = temp.substring(0, temp.lastIndexOf(SPOT)); 151 temp = temp.substring(0, temp.lastIndexOf(SPOT) + 1); 152 return temp; 153 } 154 155 public static String getClassName(String hbmContent) // DocumentCatalog 156 157 { 158 int pos1 = hbmContent.indexOf(ANCHOR2); 159 int pos2 = hbmContent.indexOf(QUOTE, pos1); 160 int pos3 = hbmContent.indexOf(QUOTE, pos2 + 1); 161 return hbmContent.substring(pos2 + 1, pos3); 162 } 163 164 public static String getModelPackageName(String hbmContent) // com.arimadisp.model.DocumentCatalog; 165 { 166 String temp = getImportModelNames(hbmContent); // com.arimadisp.model.*; 167 return temp.replace("*", getClassName(hbmContent)).replace(";", " ") 168 .trim(); 169 } 170 171 public static String getActionClassName(String hbmContent) // AddDocumentCatalogAction 172 { 173 String temp = getClassName(hbmContent); 174 return ADD + temp + "Action"; 175 } 176 177 public static String getImportServiceInterfaces(String hbmContent) // com.arimadisp.service.*; 178 { 179 String temp = getGeneralPackageName(hbmContent); 180 return temp + SERVICE + SPOT + STAR + SEMI; 181 } 182 }
ClassUtil.java

1 package code.automatic.generation.framework.util; 2 3 import java.lang.reflect.Field; 4 5 public class ClassUtil 6 { 7 8 public static String[][] fields = null; 9 10 public static String getAllFieldFromModel(String hbmContent, 11 String filePrefix) 12 { 13 StringBuffer sbf = new StringBuffer(); 14 try 15 { 16 17 Class<?> c = Class.forName(AuxiliaryStringProcessingUtil 18 .getModelPackageName(hbmContent)); 19 Field[] field = c.getDeclaredFields(); 20 fields = new String[field.length][2]; 21 for (int i = 0; i < field.length; i++) 22 { 23 String type = field[i].getType().getName(); // java.lang.String 24 String typeName = type.substring(type.lastIndexOf(".") + 1); // String 25 String value = field[i].getName(); // name 26 fields[i][0] = typeName; 27 fields[i][1] = value; 28 } 29 for (int i = 0; i < fields.length; i++) 30 { 31 sbf.append("private ").append(fields[i][0] + " ") 32 .append(fields[i][1]).append(";\n\t"); 33 } 34 } 35 catch (Exception e) 36 { 37 e.printStackTrace(); 38 } 39 return sbf.toString(); 40 } 41 42 public static String getSetterAndGetterFromModel(String filePrefix) 43 { 44 StringBuffer sbf = new StringBuffer(); 45 for (int i = 0; i < fields.length; i++) 46 { 47 String methodBasicName = fields[i][1].substring(0, 1).toUpperCase() 48 + fields[i][1].substring(1); 49 sbf.append("public ").append(fields[i][0]).append(" ") 50 .append("get" + methodBasicName) 51 .append("()\n\t{\n\t\treturn ") 52 .append("this." + fields[i][1]).append(";\n\t}\n\t") 53 .append("public void set").append(methodBasicName) 54 .append("(" + fields[i][0]) 55 .append(" " + fields[i][1] + ")\n\t{\n\t\tthis.") 56 .append(fields[i][1] + " =") 57 .append(fields[i][1] + ";\n\t}\n\t"); 58 } 59 return sbf.toString(); 60 } 61 62 public static String setFields() 63 { 64 StringBuffer sbf = new StringBuffer(); 65 for (int i = 0; i < fields.length; i++) 66 { 67 String methodBasicName = fields[i][1].substring(0, 1).toUpperCase() 68 + fields[i][1].substring(1); 69 sbf.append("bean.set").append(methodBasicName).append("(this.") 70 .append(fields[i][1] + ");\n\t\t"); 71 } 72 return sbf.toString(); 73 } 74 }
FileData.java

1 package code.automatic.generation.framework.util; 2 3 import java.io.File; 4 import java.io.FileReader; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.util.Arrays; 8 9 public class FileData 10 { 11 public static String getFileContent(String fileName) 12 { 13 StringBuffer sbf = new StringBuffer(); 14 FileReader reader = null; 15 try 16 { 17 reader = new FileReader(new File(fileName)); 18 char[] temp = new char[8192]; 19 int n = 0; 20 while ((n = reader.read(temp)) != -1) 21 { 22 sbf.append(Arrays.copyOfRange(temp, 0, n)); 23 } 24 return sbf.toString(); 25 } 26 catch (Exception e) 27 { 28 e.printStackTrace(); 29 } 30 finally 31 { 32 try 33 { 34 reader.close(); 35 } 36 catch (IOException e) 37 { 38 e.printStackTrace(); 39 } 40 } 41 return ""; 42 } 43 44 public static void WriteFile(String outputFileCompletePath, String temp) 45 { 46 FileWriter writer = null; 47 try 48 { 49 File file = new File(outputFileCompletePath); 50 writer = new FileWriter(file); 51 writer.write(temp); 52 53 } 54 catch (Exception e) 55 { 56 e.printStackTrace(); 57 } 58 finally 59 { 60 try 61 { 62 writer.close(); 63 } 64 catch (IOException e) 65 { 66 e.printStackTrace(); 67 } 68 } 69 } 70 71 public static String getHbmContent(String hbmFileName) 72 { 73 return getFileContent(hbmFileName); 74 } 75 76 public static String getTemplateContent(String templateFileName) 77 { 78 return getFileContent(templateFileName); 79 } 80 81 public static String getOutputFilePath(String packageName) 82 { 83 return packageName.replace(AuxiliaryStringProcessingUtil.SPOT, 84 File.separator); 85 } 86 87 public static String getOutputFileCompletePath(String outputCompletePath, 88 String hbmContent, String completePackageName) 89 { 90 String outputFileCompleteDirectory = outputCompletePath 91 + File.separator 92 + getOutputFilePath(completePackageName.replace(";", " ") 93 .trim()); 94 File file = new File(outputFileCompleteDirectory); 95 if (!file.exists()) 96 { 97 file.mkdirs(); 98 } 99 String result = getOutputFilePath(outputFileCompleteDirectory); 100 return result; 101 } 102 103 public static String getOutputFileCompletePathOnlyWithClassName( 104 String outputCompletePath, String hbmContent) 105 { 106 String outputFileCompleteDirectory = outputCompletePath 107 + File.separator 108 + AuxiliaryStringProcessingUtil.getClassName(hbmContent); 109 File file = new File(outputFileCompleteDirectory); 110 if (!file.exists()) 111 { 112 file.mkdirs(); 113 } 114 return outputFileCompleteDirectory; 115 } 116 }
PagingComponent.java

1 package code.automatic.generation.framework.util; 2 3 import javax.servlet.http.HttpServletRequest; 4 5 public class PagingComponent 6 { 7 public static StringBuffer setKeyWordString(StringBuffer sbf, 8 String keyWordString,String resourceString) 9 { 10 sbf.append(" <a href=\"").append(resourceString).append("?"); 11 if("".equals(keyWordString)) 12 { 13 sbf.append("start="); 14 } 15 else 16 { 17 sbf.append(keyWordString).append("&start="); 18 } 19 return sbf; 20 } 21 22 public static String getPaging(HttpServletRequest request, 23 String keyWordString, int start, int maxLineSize, long totalCount) 24 { 25 StringBuffer sbf = new StringBuffer(); 26 String temp = request.getRequestURI(); 27 String resourceString = temp.substring(temp.lastIndexOf("/") + 1); 28 29 long totalPageSize = totalCount / maxLineSize 30 + (totalCount % maxLineSize == 0 ? 0 : 1); 31 if (totalPageSize <= 1) 32 { 33 return ""; 34 } 35 sbf.append("["); 36 if (start > 0) 37 { 38 //[<a href="ListDocumentCatalogAction.action?start=1&maxLineSize=10"><img src="../Images/prev.gif" width="10px" height="10px" border="0" /></a> 39 setKeyWordString(sbf, keyWordString, resourceString) 40 .append(start - maxLineSize) 41 .append("&maxLineSize=") 42 .append(maxLineSize) 43 .append("\"><img src=\"../Images/prev.gif\" width=\"10\" height=\"10\" border=\"0\" /></a>") 44 .append(" "); 45 } 46 47 int currentPage = start / maxLineSize + 1; 48 int low = currentPage - 5; 49 int high = currentPage + 5; 50 if (low <= 0) 51 { 52 low = 1; 53 } 54 if (low > 2) 55 { 56 sbf.append(" <a href=\"").append(resourceString).append("?"); 57 setKeyWordString(sbf, keyWordString, resourceString).append("0") 58 .append("&maxLineSize=").append(maxLineSize).append("\">") 59 .append("1</a>").append("..."); 60 } 61 62 while (low < currentPage) 63 { 64 /** 65 * 0-9 1 66 * 10-19 2 67 * 20- 29 3 68 * 30-39 4 69 * 40-49 5 70 * 50-59 6 71 * 60-69 7 72 * 70-79 8 73 * 74 * 1 ... 3 4 5 6 7 8 75 * low currentPage 76 */ 77 setKeyWordString(sbf, keyWordString, resourceString) 78 .append((low - 1) * maxLineSize).append("&maxLineSize=") 79 .append(maxLineSize).append("\">").append(low) 80 .append("</a>").append(" "); 81 low++; 82 } 83 sbf.append("<b>" + currentPage + "</b>"); 84 currentPage++; 85 while (currentPage <= high && currentPage <= totalPageSize) 86 { 87 /** 88 * 0-9 1 89 * 10-19 2 90 * 20- 29 3 91 * 30-39 4 92 * 40-49 5 93 * 50-59 6 94 * 60-69 7 95 * 70-79 8 96 * 97 * 1 ... 3 4 5 6 7 8 98 * currentPage high 99 */ 100 setKeyWordString(sbf, keyWordString, resourceString) 101 .append((currentPage - 1) * maxLineSize) 102 .append("&maxLineSize=").append(maxLineSize).append("\">") 103 .append(currentPage).append("</a>").append(" "); 104 currentPage++; 105 } 106 if (high + 1 < totalPageSize) 107 { 108 sbf.append("..."); 109 } 110 if (high + 1 <= totalPageSize) 111 { 112 setKeyWordString(sbf, keyWordString, resourceString) 113 .append((totalPageSize - 1) * maxLineSize) 114 .append("&maxLineSize=").append(maxLineSize).append("\">") 115 .append(totalPageSize).append("</a>").append(" "); 116 } 117 if (totalCount > (start + maxLineSize)) 118 { 119 //<a href="ListDocumentCatalogAction.action?start=1&maxLineSize=10"><img src="../Images/next.gif" width="10px" height="10px" border="0" /></a> 120 setKeyWordString(sbf, keyWordString, resourceString) 121 .append(start + maxLineSize) 122 .append("&maxLineSize=") 123 .append(maxLineSize) 124 .append("\"><img src=\"../Images/next.gif\" width=\"10\" height=\"10\" border=\"0\" /></a>") 125 .append(" "); 126 } 127 sbf.append("]").append(" 共").append(totalPageSize).append("页"); 128 return sbf.toString(); 129 } 130 }
三、测试生成