
正文
java生成模版代码 java模板编程
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
如何利用SQL中数据使用FreeMarker生成JAVA实体bean代码
利用freemarker生成JAVA BEAN
Freemarker模板代码如下:
package ${packageName};
/**
* #if author == "adams" @author adams /#if
*/
pulic class ${className} {
#list attrs as a
private ${a.type} ${a.field};
/#list
#list attrs as a
public void set${a.field?cap_first}(${a.type} ${a.field}){
this.${a.field} = ${a.field};
}
public ${a.type} get${a.field?cap_first}(){
return this.${a.field};
}
/#list
}
Java代码如下
package com.my.learn.freemarker;
public class Attr{
public String field;
public String type;
public Attr(String field, String type){
this.field = field;
this.type = type;
}
public String getField(){
return this.field;
}
public String getType(){
return this.type;
}
public void setField(String field){
this.field = field;
}
public void setType(String type){
this.type = type;
}
}
package com.my.learn.freemarker;
import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException;
public class FmAppUseage {
public static void main(String[] args){
ListObject list = new ArrayListObject();
list.add(new Attr("username", "String"));
list.add(new Attr("password", "String"));
list.add(new Attr("age", "int"));
list.add(new Attr("hobby", "String"));
MapString,Object root = new HashMapString, Object();
root.put("packageName", "com.my.learn.freemarker");
root.put("className", "User");
root.put("attrs", list);
root.put("author", "adams");
Configuration cfg = new Configuration();
String path = FmAppUseage.class.getResource("/").getPath()+"template";
try {
cfg.setDirectoryForTemplateLoading(new File(path));
Template template = cfg.getTemplate("/demo.ftl");
StringWriter out = new StringWriter();
template.process(root, out);
System.out.println(out.toString());
} catch (IOException e) {
System.out.println("Cause==" + e.getCause());
} catch (TemplateException e) {
System.out.println("Cause==" + e.getCause());
}
}
}
输出结果如下:
package com.my.learn.freemarker;
/**
* @author adams
*/
pulic class User {
private String username;
private String password;
private int age;
private String hobby;
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return this.username;
}
public void setPassword(String password){
this.password = password;
}
public String getPassword(){
return this.password;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
public void setHobby(String hobby){
this.hobby = hobby;
}
public String getHobby(){
return this.hobby;
}
}
当在笔者刚做测试时,将Attr的类定义在了FmAppUseage类的内部,导致不能正常运行,只能将其移除单独成一个类时,便能正常运行了。 转载仅供参考,版权属于原作者。祝你愉快,满意请采纳哦
相关问答
Q1: JAVA,Spring boot怎么据数据库数据生成Excel模板?,含下拉框
只不过,jxl比较小,好用java生成模版代码!对于下拉框联动java生成模版代码的功能
jxl没有直接可以处理的!只能做好模板,然后用jxl往模板写数据!这样做,不完美,仅供参考02第一:excel中的联动处理
名称-定义 02设置一个区域,用来取值的区域,名称为 第一级别下拉框的选项名
第一级别 02 下拉框 数据 有效性 序列 值为 选项框 和 前面设置的区域名称相同
第二级别 02 下拉框 数据 有效性 序列 值为02=INDIRECT(B9) B9为第一级别的下拉框位置
第二:java程序的处理
A:对action进行判断 准备需要的值02filePath = CommAttachInfoFactory.rootPath
+ "/filedata/npForm/scaleTarget/模板录入模板/type-"+types[k]+".xls";
request.setAttribute("path", filePath);try{new OperationExcel().UpdateLuruExcel(filePath, temFileName,scaleTaskInfo);
} catch (Exception e) {
e.printStackTrace();}02B:具体的操作并生成文件02public void UpdateLuruExcel(String filename,String overDept,ScaleTargetForm scaleTaskInfo){try{Workbook wb = Workbook.getWorkbook(new File(filename));
WritableWorkbook workbook = Workbook.createWorkbook( new File(filename),wb);
WritableSheet sheet = workbook.getSheet(0);
sheet.addCell(new Label(0,1,scaleTaskInfo.getTask_name()+
"-"+scaleTaskInfo.getTask_start_time()));
workbook.write();
workbook.close(); }catch(Exception e){
e.printStackTrace();}}02附件为 一个做好的三级联动例子其中 选择区域的值 02可以做到另外一个sheet中,这样美观
Q2: 如何创建 Java 项目模板?
用eclipse插件开发(RCPjava生成模版代码,也就是你讲java生成模版代码的swt/jface)做一个插件吧.
首先建个模板工程,就是一个你要作为模板java生成模版代码的普通工程;
然后做一个插件,可以是一个按钮,点击弹出一个对话框,进行一些基本配置,如项目名、路径等,确定后,将把模板工程拷贝到目标的工作区中,然后改一下项目配置(一般你的项目根目录下都会有项目的基本属性的文件,.project、.classpath等,可以用插件直接编辑它们),之后导入工程,模板就导入了
不知道你是不是这个意思
Q3: 用Java POI到实现一个Excel模板生成。但是遇到一个比较奇特的问题。
我这边使用的时候是前台先遍历标题,再遍历内容,再传到后台,在后台手工拼的标题(如果是多行标题),再遍历。不知道你说的下拉列表功能是直接用的插件还是什么。
Q4: java 调用word模板实现循环套打生成word文档
1,模版里做循环,需要循环的地方 在模版里加入 #list reportListas a /#list 编辑好。
2,代码里
MapString,Object resMap = new HashMap();
resMap.put("reportList", list);
t.process(resMap,out);
Q5: 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 != null CommonUtils.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 = (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("*************** 恭喜! 报告创建成功 结束 ***************");
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("数据库报告服务器地址配置错误或网络不通!!2.连接是否超时" + e.getMessage());
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
msg = "7";
logger.error("数据库报告服务器地址配置错误或网络不通!!2.连接是否超时" + 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生成模版代码和java模板编程的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。






