Freemarker是一個(gè)模板框架。我們可以通過(guò)Freemarker進(jìn)行代碼生成或頁(yè)面的靜態(tài)生成。 現(xiàn)在簡(jiǎn)單的說(shuō)一下怎樣使用Freemarker Freemarker的主要生成類(lèi)
創(chuàng)新互聯(lián)建站是一家專(zhuān)注于網(wǎng)站制作、網(wǎng)站建設(shè)與策劃設(shè)計(jì),湟源網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)建站做網(wǎng)站,專(zhuān)注于網(wǎng)站建設(shè)十年,網(wǎng)設(shè)計(jì)領(lǐng)域的專(zhuān)業(yè)建站公司;建站業(yè)務(wù)涵蓋:湟源等地區(qū)。湟源做網(wǎng)站價(jià)格咨詢(xún):028-86922220
public boolean generate(String templateFileName, Map data,
String fileName) {
try {
//取得模板的位置
String templateFileDir=templateFileName.substring(0, templateFileName.lastIndexOf("/"));
//取得模板的名字
String templateFile=templateFileName.substring(templateFileName.lastIndexOf("/"), templateFileName.length());
//取得生成文件的路徑
String genFileDir=fileName.substring(0, fileName.lastIndexOf("/"));
Template template = ConfigurationHelper.getConfiguration(templateFileDir).getTemplate(templateFile);
File fileDir=new File(genFileDir);
org.apache.commons.io.FileUtils.forceMkdir(fileDir);
File output = new File(fileName);
if(output.exists()){
//如何代碼已存在不重復(fù)生成
return false;
}
Writer writer = new FileWriter(output);
template.process(data, writer);
writer.close();
} catch (TemplateException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
代碼中的Map 是模板所需要的數(shù)據(jù),我們可以通過(guò)面向?qū)ο竦姆椒ò褦?shù)據(jù)存在模板中public boolean genDaoInterface(String fileName){
DaoModel daoModel=new DaoModel();
//設(shè)置Dao實(shí)現(xiàn)類(lèi)的包名
daoModel.setPackageName(DaoConstant.PACKAGE);
//取得接口名
String className=StringUtils.substringBefore(fileName,".");
//設(shè)置接口名
daoModel.setClassName(className);
MapString, Object data = new HashMapString, Object();
data.put("model", daoModel);
//設(shè)置生成的位置
String filePath=new String("src/"+package2path(DaoConstant.PACKAGE)+"/"+fileName);
//代碼生成
return super.generate(DaoConstant.INTERFACE_TEMPLATE, data, filePath);
}
data.put("model", daoModel);由這句代碼可看出我們將可以在模板中直接調(diào)用這些數(shù)據(jù)package ${model.packageName};
public interface ${model.className} extends BaseHibernateDao {
}
zip包,然后自動(dòng)下載下來(lái)
1.預(yù)先定義好模板
2.界面輸入相關(guān)參數(shù)
3.解析模板生成代碼并下載
最后放出源代碼:
package com.et.controller.system.createcode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.et.controller.base.BaseController;
import com.et.util.DelAllFile;
import com.et.util.FileDownload;
import com.et.util.FileZip;
import com.et.util.Freemarker;
import com.et.util.PageData;
import com.et.util.PathUtil;
/**
* 類(lèi)名稱(chēng):FreemarkerController
* 創(chuàng)建人:Harries
* 創(chuàng)建時(shí)間:2015年1月12日
* @version
*/
@Controller
@RequestMapping(value=”/createCode”)
public class CreateCodeController extends BaseController {
/**
* 生成代碼
*/
@RequestMapping(value=”/proCode”)
public void proCode(HttpServletResponse response) throws Exception{
PageData pd = new PageData();
pd = this.getPageData();
/* ============================================================================================= */
String packageName = pd.getString(“packageName”); //包名 ========1
String objectName = pd.getString(“objectName”); //類(lèi)名 ========2
String tabletop = pd.getString(“tabletop”); //表前綴 ========3
tabletop = null == tabletop?””:tabletop.toUpperCase(); //表前綴轉(zhuǎn)大寫(xiě)
String zindext = pd.getString(“zindex”); //屬性總數(shù)
int zindex = 0;
if(null != zindext !””.equals(zindext)){
zindex = Integer.parseInt(zindext);
}
ListString[] fieldList = new ArrayListString[](); //屬性集合 ========4
for(int i=0; i zindex; i++){
fieldList.add(pd.getString(“field”+i).split(“,fh,”)); //屬性放到集合里面
}
MapString,Object root = new HashMapString,Object(); //創(chuàng)建數(shù)據(jù)模型
root.put(“fieldList”, fieldList);
root.put(“packageName”, packageName); //包名
root.put(“objectName”, objectName); //類(lèi)名
root.put(“objectNameLower”, objectName.toLowerCase()); //類(lèi)名(全小寫(xiě))
root.put(“objectNameUpper”, objectName.toUpperCase()); //類(lèi)名(全大寫(xiě))
root.put(“tabletop”, tabletop); //表前綴
root.put(“nowDate”, new Date()); //當(dāng)前日期
DelAllFile.delFolder(PathUtil.getClasspath()+”admin/ftl”); //生成代碼前,先清空之前生成的代碼
/* ============================================================================================= */
String filePath = “admin/ftl/code/”; //存放路徑
String ftlPath = “createCode”; //ftl路徑
/*生成controller*/
Freemarker.printFile(“controllerTemplate.ftl”, root, “controller/”+packageName+”/”+objectName.toLowerCase()+”/”+objectName+”Controller.java”, filePath, ftlPath);
/*生成service*/
Freemarker.printFile(“serviceTemplate.ftl”, root, “service/”+packageName+”/”+objectName.toLowerCase()+”/”+objectName+”Service.java”, filePath, ftlPath);
/*生成mybatis xml*/
Freemarker.printFile(“mapperMysqlTemplate.ftl”, root, “mybatis_mysql/”+packageName+”/”+objectName+”Mapper.xml”, filePath, ftlPath);
Freemarker.printFile(“mapperOracleTemplate.ftl”, root, “mybatis_oracle/”+packageName+”/”+objectName+”Mapper.xml”, filePath, ftlPath);
/*生成SQL腳本*/
Freemarker.printFile(“mysql_SQL_Template.ftl”, root, “mysql數(shù)據(jù)庫(kù)腳本/”+tabletop+objectName.toUpperCase()+”.sql”, filePath, ftlPath);
Freemarker.printFile(“oracle_SQL_Template.ftl”, root, “oracle數(shù)據(jù)庫(kù)腳本/”+tabletop+objectName.toUpperCase()+”.sql”, filePath, ftlPath);
/*生成jsp頁(yè)面*/
Freemarker.printFile(“jsp_list_Template.ftl”, root, “jsp/”+packageName+”/”+objectName.toLowerCase()+”/”+objectName.toLowerCase()+”_list.jsp”, filePath, ftlPath);
Freemarker.printFile(“jsp_edit_Template.ftl”, root, “jsp/”+packageName+”/”+objectName.toLowerCase()+”/”+objectName.toLowerCase()+”_edit.jsp”, filePath, ftlPath);
/*生成說(shuō)明文檔*/
Freemarker.printFile(“docTemplate.ftl”, root, “說(shuō)明.doc”, filePath, ftlPath);
//this.print(“oracle_SQL_Template.ftl”, root); 控制臺(tái)打印
/*生成的全部代碼壓縮成zip文件*/
FileZip.zip(PathUtil.getClasspath()+”admin/ftl/code”, PathUtil.getClasspath()+”admin/ftl/code.zip”);
/*下載代碼*/
FileDownload.fileDownload(response, PathUtil.getClasspath()+”admin/ftl/code.zip”, “code.zip”);
}
}
首先是action的createDoc方法:
[java]
/**
* 通過(guò)HttpCient調(diào)用報(bào)告服務(wù)器的方法生成報(bào)告 DOC
*/
public String createDoc() throws Exception {
//定義放回成功與否的判斷碼
String prMsg="";
// 獲取當(dāng)前登錄的用戶(hù)
UserVo userVo = CommonUtils.getUserMessage();
//獲取模版類(lèi)型
docType = Struts2Utils.getParameter("docType");
//重新創(chuàng)建文檔
String creatOrnot = Struts2Utils.getParameter("creatOrnot");
//獲取組組編號(hào)參數(shù)
workgroupId = Struts2Utils.getParameter("workgroupId");
//獲取評(píng)估用例實(shí)例ID參數(shù)
evtcaseInstId = Struts2Utils.getParameter("evtcaseInstId");
if(CommonUtils.isNotNull(docType)){
//獲取項(xiàng)目Id
projectId = Struts2Utils.getParameter("projectId");
if(!CommonUtils.isNotNull(projectId)){
if(CommonUtils.isNotNull(this.getIdFromSession("PM_PROJECTID"))){
projectId = this.getIdFromSession("PM_PROJECTID").toString();
}else{
Struts2Utils.getRequest().setAttribute("msg", "請(qǐng)先選擇項(xiàng)目!");
}
}
if(CommonUtils.isNotNull(projectId)){
prMsg = infoSystemDescService.downloadFileByUrl(projectId, userVo.getUserId(), workgroupId, evtcaseInstId, docType, creatOrnot);
}
}
return "docList";
}
注:在我貼出來(lái)的代碼中,能看懂就行了,有些不用管他(可能是其他業(yè)務(wù)方面的判斷),關(guān)于最后返回的prMsg---代表各種狀態(tài) 主要表示成功與否或者是出錯(cuò)的信息。
接著我貼出service層的方法downloadFileByUrl
[java]
/prep/pp/ppre name="code" class="java"pre name="code" class="java"/**
* 功能:
* 1.(生成報(bào)告文檔)
* 2.保存指定URL的源文件到指定路徑下
* @param projectId
* @param userId
* @param workgroupId
* @param evtcaseInstId
* @param docType
* @param creatOrnot
* @return
* @throws Exception
*/
@SuppressWarnings("deprecation")
public synchronized String downloadFileByUrl(String projectId,String userId,String workgroupId,String evtcaseInstId,String docType,String creatOrnot) throws Exception {
String msg = "1";//"1":默認(rèn)為創(chuàng)建成功的提示信息 "2":標(biāo)識(shí)創(chuàng)建失敗
String srcUrl = ""; //報(bào)告服務(wù)器的執(zhí)行路徑
HttpResponse response = null;
FileOutputStream out = null;
HttpClient httpclient = null;
HttpGet httpget = null;
long time1 = System.currentTimeMillis();
//獲取保存后的路徑
TProjDoc projDoc = projectDocDao.findFileByType(userId, Integer.parseInt(docType), Long.parseLong(projectId), workgroupId,evtcaseInstId);
if(projDoc == null || (projDoc != null CommonUtils.isNotNull(creatOrnot) creatOrnot.equals("1"))){ //FT_任務(wù)編號(hào)_[FID]
try {
//獲取報(bào)告服務(wù)器的執(zhí)行路徑
srcUrl = xmlPathDef.getActionUrl(docType, projectId,userId,workgroupId,evtcaseInstId);
HttpParams httpParams = new BasicHttpParams();
// 設(shè)置最大連接數(shù)
ConnManagerParams.setMaxTotalConnections(httpParams, 1);
// 設(shè)置獲取連接的最大等待時(shí)間
//ConnManagerParams.setTimeout(httpParams, 6000);
// 設(shè)置每個(gè)路由最大連接數(shù)
ConnPerRouteBean connPerRoute = new ConnPerRouteBean(1);
ConnManagerParams.setMaxConnectionsPerRoute(httpParams,connPerRoute);
// 設(shè)置連接超時(shí)時(shí)間
HttpConnectionParams.setConnectionTimeout(httpParams, 6000);
// 設(shè)置讀取超時(shí)時(shí)間
if(docType.toString().equals(XmlPathDef.SPOTTEST_DOC) docType.toString().equals(XmlPathDef.FTEST_DOC)){
HttpConnectionParams.setSoTimeout(httpParams, 2400000);
}else{
HttpConnectionParams.setSoTimeout(httpParams, 600000);
}
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(httpParams, registry);
httpclient = new DefaultHttpClient(connectionManager, httpParams);
httpget = new HttpGet(srcUrl);
//執(zhí)行返回
response = httpclient.execute(httpget);
//如果是本機(jī)既當(dāng)服務(wù)器,又當(dāng)報(bào)表服務(wù)器,那么就只生成一遍
String ipvalues = xmlPathDef.getRepUrl();
if(CommonUtils.isNotNull(ipvalues)){
if(ipvalues.indexOf(":") != -1){
ipvalues = ipvalues.substring(0,ipvalues.lastIndexOf(":"));
}
}
HttpEntity entity = response.getEntity();
//獲取保存后的路徑
projDoc = projectDocDao.findFileByType(userId,Integer.parseInt(docType), Long.parseLong(projectId), workgroupId,evtcaseInstId);
String filePath = "";
if(projDoc != null)
filePath = projDoc.getPath();
if(CommonUtils.isNotNull(filePath)){
String basepath = XmlPathDef.getBasePath();
String outFilePath = (basepath + filePath).replaceAll("\\\\", "\\/");
XmlPathDef.isExists(outFilePath);
File wdFile = new File(outFilePath);
out = new FileOutputStream(wdFile);
int l;
byte[] tmp = new byte[2048];
while ((l = instream.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
out.close();
System.out.println("****************************** ");
System.out.println("");
System.out.println("*************** 恭喜! 報(bào)告創(chuàng)建成功 結(jié)束 ***************");
System.out.println("");
}else{
msg = "8";//說(shuō)明word創(chuàng)建成功,但是數(shù)據(jù)沒(méi)有保存成功
response = null;
}
}else{
msg = "2";
}
} catch (ClientProtocolException e) {
msg = "7";
e.printStackTrace();
} catch (IOException e) {
msg = "7";
logger.error("數(shù)據(jù)庫(kù)報(bào)告服務(wù)器地址配置錯(cuò)誤或網(wǎng)絡(luò)不通??!2.連接是否超時(shí)" + e.getMessage());
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
msg = "7";
logger.error("數(shù)據(jù)庫(kù)報(bào)告服務(wù)器地址配置錯(cuò)誤或網(wǎng)絡(luò)不通??!2.連接是否超時(shí)" + e.getMessage());
e.printStackTrace();
}
}
}
}
long time2 = System.currentTimeMillis();
long numTime = time2 - time1;
if(docType.toString().equals(XmlPathDef.SPOTTEST_DOC) docType.toString().equals(XmlPathDef.FTEST_DOC)){
if(numTime = 2401000){
msg = "9";
}
}else{
if(numTime = 601000){
msg = "9";
}
}
System.out.println("");
String loggerinfo = "********* 報(bào)告類(lèi)型為 :" + docType + " 執(zhí)行時(shí)間為: " + (time2 - time1) /1000 + " 秒!***************";
System.out.println(loggerinfo);
System.out.println("");
System.out.println("*****************************");
logger.info(loggerinfo);
return msg;
}
新聞名稱(chēng):java代碼模板生成 java 代碼生成
文章網(wǎng)址:http://jinyejixie.com/article24/dophoje.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、手機(jī)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)公司、網(wǎng)站改版、動(dòng)態(tài)網(wǎng)站、網(wǎng)站導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)