java通过模板生成代码 模板 java

如何使用Freemarker生成java代码Freemarker是一个模板框架 。我们可以通过Freemarker进行代码生成或页面的静态生成 。现在简单的说一下怎样使用Freemarker Freemarker的主要生成类
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()){
//如何代码已存在不重复生成
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 是模板所需要的数据,我们可以通过面向对像的方法把数据存在模板中public boolean genDaoInterface(String fileName){
DaoModel daoModel=new DaoModel();
//设置Dao实现类的包名
daoModel.setPackageName(DaoConstant.PACKAGE);
//取得接口名
String className=StringUtils.substringBefore(fileName,".");
//设置接口名
daoModel.setClassName(className);
MapString, Object data = https://www.04ip.com/post/new HashMapString, Object();
data.put("model", daoModel);
//设置生成的位置
String filePath=new String("src/" package2path(DaoConstant.PACKAGE) "/" fileName);
//代码生成
return super.generate(DaoConstant.INTERFACE_TEMPLATE, data, filePath);
}
data.put("model", daoModel);由这句代码可看出我们将可以在模板中直接调用这些数据package ${model.packageName};
public interface ${model.className} extends BaseHibernateDao {
}
JAVA根据模板生成HTML页面的技术Velocity
变量定义:用$标志
表达式语句:以#开始
强控制语言:变量赋值:#set $this = "Velocity"
外部引用:#include ( $1 )
条件控制:#if …. #end
非 兼容性语 言
JDynamiTe
变量定义:用{}包装
表达式语句:写在注释格式(!-- ?)中
弱控制语言
兼容语言
XSLT
变量定义:xml标签
表达式:xsl标签
强控制语言:外部引用:import,include
条件控制:if,choose…when…otherwise
非兼容语言
Tapestry
采用component的形式开发 。
变量定义(组件定义):在html标签中加上jwcid
表达式语句:ognl规范
兼容语言
java如何根据word模板生成word文档首先是action的createDoc方法:
[java]
/**
* 通过HttpCient调用报告服务器的方法生成报告 DOC
*/
public String createDoc() throws Exception {
//定义放回成功与否的判断码
String prMsg="";
// 获取当前登录的用户
UserVo userVo = CommonUtils.getUserMessage();
//获取模版类型
docType = Struts2Utils.getParameter("docType");
//重新创建文档
String creatOrnot = Struts2Utils.getParameter("creatOrnot");
//获取组组编号参数
workgroupId = Struts2Utils.getParameter("workgroupId");
//获取评估用例实例ID参数
evtcaseInstId = Struts2Utils.getParameter("evtcaseInstId");
if(CommonUtils.isNotNull(docType)){
//获取项目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", "请先选择项目!");
}
}
if(CommonUtils.isNotNull(projectId)){
prMsg = infoSystemDescService.downloadFileByUrl(projectId, userVo.getUserId(), workgroupId, evtcaseInstId, docType, creatOrnot);
}
}
return "docList";
}
注:在我贴出来的代码中,能看懂就行了,有些不用管他(可能是其他业务方面的判断),关于最后返回的prMsg---代表各种状态 主要表示成功与否或者是出错的信息 。
接着我贴出service层的方法downloadFileByUrl
[java]
/prep/pp/ppre name="code" class="java"pre name="code" class="java"/**
* 功能:
* 1.(生成报告文档)
* 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":默认为创建成功的提示信息 "2":标识创建失败
String srcUrl = "";//报告服务器的执行路径
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 != nullCommonUtils.isNotNull(creatOrnot)creatOrnot.equals("1"))){//FT_任务编号_[FID]
try {
//获取报告服务器的执行路径
srcUrl = xmlPathDef.getActionUrl(docType, projectId,userId,workgroupId,evtcaseInstId);
HttpParams httpParams = new BasicHttpParams();
// 设置最大连接数
ConnManagerParams.setMaxTotalConnections(httpParams, 1);
// 设置获取连接的最大等待时间
//ConnManagerParams.setTimeout(httpParams, 6000);
// 设置每个路由最大连接数
ConnPerRouteBean connPerRoute = new ConnPerRouteBean(1);
ConnManagerParams.setMaxConnectionsPerRoute(httpParams,connPerRoute);
// 设置连接超时时间
HttpConnectionParams.setConnectionTimeout(httpParams, 6000);
// 设置读取超时时间
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);
//执行返回
response = httpclient.execute(httpget);
//如果是本机既当服务器,又当报表服务器,那么就只生成一遍
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 = (basepathfilePath).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("*************** 恭喜! 报告创建成功结束***************");
System.out.println("");
}else{
msg = "8";//说明word创建成功,但是数据没有保存成功
response = null;
}
}else{
msg = "2";
}
} catch (ClientProtocolException e) {
msg = "7";
e.printStackTrace();
} catch (IOException e) {
msg = "7";
logger.error("数据库报告服务器地址配置错误或网络不通?。?.连接是否超时"e.getMessage());
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
msg = "7";
logger.error("数据库报告服务器地址配置错误或网络不通?。?.连接是否超时"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 = "********* 报告类型为 :"docType" 执行时间为: "(time2 - time1) /1000" 秒!***************";
System.out.println(loggerinfo);
System.out.println("");
System.out.println("*****************************");
logger.info(loggerinfo);
return msg;
}
java中根据xml模板创建xml/**
* 复制单个文件
* @param oldPath String 原文件路径 如:c:/fqf.txt
* @param newPath String 复制后路径 如:f:/fqf.txt
* @return boolean
*/
public void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum= byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
java freemarker用模板生成静态html页面freemarker是data model=输出 。需要替换你模型的所有代号的 , 替换一次就行了,你的asp的eval实际上也是替换
java代码生成器怎么用zip包,然后自动下载下来
1.预先定义好模板
2.界面输入相关参数
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;
/**
* 类名称:FreemarkerController
* 创建人:Harries
* 创建时间:2015年1月12日
* @version
*/
@Controller
@RequestMapping(value=https://www.04ip.com/post/”/createCode”)
public class CreateCodeController extends BaseController {
/**
* 生成代码
*/
@RequestMapping(value=https://www.04ip.com/post/”/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”); //类名 ========2
String tabletop = pd.getString(“tabletop”); //表前缀 ========3
tabletop = null == tabletop?””:tabletop.toUpperCase(); //表前缀转大写
String zindext = pd.getString(“zindex”); //属性总数
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(); //创建数据模型
root.put(“fieldList”, fieldList);
【java通过模板生成代码 模板 java】root.put(“packageName”, packageName); //包名
root.put(“objectName”, objectName); //类名
root.put(“objectNameLower”, objectName.toLowerCase()); //类名(全小写)
root.put(“objectNameUpper”, objectName.toUpperCase()); //类名(全大写)
root.put(“tabletop”, tabletop); //表前缀
root.put(“nowDate”, new Date()); //当前日期
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数据库脚本/” tabletop objectName.toUpperCase() ”.sql”, filePath, ftlPath);
Freemarker.printFile(“oracle_SQL_Template.ftl”, root, “oracle数据库脚本/” tabletop objectName.toUpperCase() ”.sql”, filePath, ftlPath);
/*生成jsp页面*/
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);
/*生成说明文档*/
Freemarker.printFile(“docTemplate.ftl”, root, “说明.doc”, filePath, ftlPath);
//this.print(“oracle_SQL_Template.ftl”, root); 控制台打印
/*生成的全部代码压缩成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”);
}
}
关于java通过模板生成代码和模板 java的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读