![[计算机]freemarker根据模版生成文件使用例子.doc_第1页](http://file.renrendoc.com/FileRoot1/2019-1/5/e05e8c9c-3795-4681-b30c-f38db66514f2/e05e8c9c-3795-4681-b30c-f38db66514f21.gif)
![[计算机]freemarker根据模版生成文件使用例子.doc_第2页](http://file.renrendoc.com/FileRoot1/2019-1/5/e05e8c9c-3795-4681-b30c-f38db66514f2/e05e8c9c-3795-4681-b30c-f38db66514f22.gif)
![[计算机]freemarker根据模版生成文件使用例子.doc_第3页](http://file.renrendoc.com/FileRoot1/2019-1/5/e05e8c9c-3795-4681-b30c-f38db66514f2/e05e8c9c-3795-4681-b30c-f38db66514f23.gif)
![[计算机]freemarker根据模版生成文件使用例子.doc_第4页](http://file.renrendoc.com/FileRoot1/2019-1/5/e05e8c9c-3795-4681-b30c-f38db66514f2/e05e8c9c-3795-4681-b30c-f38db66514f24.gif)
![[计算机]freemarker根据模版生成文件使用例子.doc_第5页](http://file.renrendoc.com/FileRoot1/2019-1/5/e05e8c9c-3795-4681-b30c-f38db66514f2/e05e8c9c-3795-4681-b30c-f38db66514f25.gif)
已阅读5页,还剩11页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
目录说明1工具类11.接口Render12.基本类bean RenderClass13.基本类bean RenderProperty24.FreemarkerRender35.模版hibernate3.ftl46.工具类Assistant5如何使用16说明Java中使用freemarker根据模版来生成具有一定格式的文件。本例以java动态生成 hibernate的*.hbm.xml文件为例子,并且假设已经导入了freemarker .jar文件工具类1. 接口Renderpublic interface Render void render(RenderClass target,String template,String outpath);2. 基本类bean RenderClassimport java.util.List;public class RenderClass private String className;private String tableName;private String classPath;private List properties;public RenderClass()properties = null;public String getClassName() return className;public void setClassName(String className) this.className = className;public String getTableName() return tableName;public void setTableName(String tableName) this.tableName = tableName;public List getProperties() return properties;public void setProperties(List properties) perties = properties;public void setClassPath(String classPath) this.classPath = classPath;public String getClassPath() return classPath;3. 基本类bean RenderPropertypackage j.table.function;/*/public class RenderProperty extends BuildPropertyprivate boolean primary;private String name;private String type;private String sequence;private Integer length;private String field;/* 省略set跟get方法*/4. FreemarkerRenderpackage *;import java.io.FileOutputStream;import java.io.PrintWriter;import java.io.StringWriter;import freemarker.cache.ClassTemplateLoader;import freemarker.template.Configuration;import freemarker.template.ObjectWrapper;import freemarker.template.SimpleHash;import freemarker.template.Template;import freemarker.template.TemplateExceptionHandler;public class FreemarkerRender implements Renderprivate Configuration templateconfig;public FreemarkerRender()this.initialize();public void initialize()tryif (templateconfig=null)templateconfig = new Configuration();templateconfig.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);templateconfig.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER);templateconfig.setTemplateLoader(new ClassTemplateLoader(this.getClass(),/);templateconfig.setTemplateUpdateDelay(1200);templateconfig.setDefaultEncoding(gb2312);templateconfig.setLocale(new java.util.Locale(zh_CN);templateconfig.setNumberFormat(0.#);catch (Exception e)public void render(RenderClass target,String template,String outpath)tryStringWriter writer = new StringWriter();Template tl = templateconfig.getTemplate(template,templateconfig.getLocale();SimpleHash root = new SimpleHash();root.put(entity, target);cess(root, writer);Assistant.createNewFile(outpath);FileOutputStream fos = new FileOutputStream(outpath);PrintWriter pwriter = new PrintWriter(fos);pwriter.write(writer.toString();pwriter.close();fos.close(); catch (Exception ex)ex.printStackTrace();5. 模版hibernate3.ftl column name=$property.field?upper_case length=$property.lengthcolumn name=$property.field?upper_case precision=$property.length scale=0 6. 工具类Assistant这个类为通用工具类,可单独拷贝到其他项目使用。该类的结构及功能有:package j.table.function;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.text.SimpleDateFormat;import java.util.Calendar;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import org.apache.log4j.Logger;public class Assistant private static final Logger log = Logger.getLogger(Assistant.class);public static String convertRequestParameter(String parameter) throws Exceptionreturn convertRequestParameter(parameter,null);public static String convertRequestParameter(String parameter,String format) throws Exceptionif (parameter!=null)if (format=null)format=utf-8;parameter = .URLDecoder.decode(parameter,format);return parameter;/0public static boolean notEmpty(HttpServletRequest request,String key)if (request.getParameter(key)!=null & request.getParameter(key).length()0)return true;elsereturn false;public static void writeFileContent(String url,String content ,ServletContext context) throws ExceptionwriteFileContent( getFullPath(url,context),content);public static String HTMLEncode(String txt) if (txt!=null & txt.length()0)txt=txt.replaceAll(&,&);txt=txt.replaceAll(,>);txt=txt.replaceAll(,");txt=txt.replaceAll(,);return txt;public static boolean existFile(String urlpath,ServletContext context)File file = new File(getFullPath(urlpath, context);if (file.exists()return true;elsereturn false;public static void writeFileContent(String path,String content) throws ExceptionFile file = new File(path);if (!file.exists()file.createNewFile();OutputStreamWriter write= new OutputStreamWriter(new FileOutputStream(file),GBK);BufferedWriter writer=new BufferedWriter(write);writer.write(content);writer.close();write.close();public static String getFileContent(String url,ServletContext context) throws ExceptionString filepath = getFullPath(url,context);return getFileContent(filepath);public static String getFileContent(String path) throws ExceptionStringBuffer buf = new StringBuffer();File file = new File(path);if (file.exists()InputStreamReader read = new InputStreamReader(new FileInputStream(file),GBK);BufferedReader reader=new BufferedReader(read);tryString content = reader.readLine();while (content!=null)buf.append(content);content = reader.readLine();finallyif (reader!=null)reader.close();if (read!=null)read.close();return buf.toString();/()public static java.util.Date addTimeByDay(java.util.Date date,int days) throws ExceptionCalendar calendar=Calendar.getInstance(); calendar.setTime(date);calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)+days);return calendar.getTime();public static java.util.Date addTimeByMinutes(java.util.Date date,int minutes) throws ExceptionCalendar calendar=Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.MINUTE,calendar.get(Calendar.MINUTE)+minutes);return calendar.getTime();public static java.util.Date addTimeBySeconds(java.util.Date date,int seconds) throws ExceptionCalendar calendar=Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.SECOND,calendar.get(Calendar.SECOND)+seconds);return calendar.getTime();/public static java.util.Date nowTime() throws ExceptionSimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd);String datestr = sdf.format(java.util.Calendar.getInstance().getTime();return sdf.parse(datestr);/public static java.util.Date nowFullTime() throws ExceptionSimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);String datestr = sdf.format(java.util.Calendar.getInstance().getTime();return sdf.parse(datestr);public static java.util.Date nowFullTime(String format) throws ExceptionSimpleDateFormat sdf = new SimpleDateFormat(format);String datestr = sdf.format(java.util.Calendar.getInstance().getTime();return sdf.parse(datestr);public static String convertDateStrToString(String datestr,String format) throws ExceptionString result = null;SimpleDateFormat sdf = new SimpleDateFormat(format);tryresult = sdf.format(sdf.parse(datestr);catch (Exception ex) sdf = new SimpleDateFormat(yyyy-MM-dd);result = sdf.format(sdf.parse(datestr);return result;public static String convertDateToString(java.util.Date date,String format) throws ExceptionSimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.format(date);public static java.util.Date formatDateStr(String datestr) throws ExceptionSimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd);return sdf.parse(datestr);public static java.util.Date formatDateStr(String datestr,String format) throws Exceptionjava.util.Date result = null;SimpleDateFormat sdf = new SimpleDateFormat(format);tryresult = sdf.parse(datestr);catch (Exception ex) sdf = new SimpleDateFormat(yyyy-MM-dd);result = sdf.parse(datestr);return result;public static java.util.Date formatFullDateStr(String datestr) throws Exceptionjava.util.Date result = null;SimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);tryresult = sdf.parse(datestr);catch (Exception ex) sdf = new SimpleDateFormat(yyyy-MM-dd);result = sdf.parse(datestr);return result;/public static String getFileName(String filepath)filepath = filepath.replace(/, );String filename = filepath;if (filepath.lastIndexOf()0)filename = filepath.substring(filepath.lastIndexOf()+1);return filename;public static void copy(ServletContext context,String form,String to ,boolean removeold) throws java.io.IOExceptioncopy(getFullPath(form,context),getFullPath(to,context),removeold);/removeold public static void copy( String from, String to,boolean removeold )throws java.io.IOExceptionint BUFF_SIZE = 1024;byte buffer = new byte BUFF_SIZE ;java.io.InputStream in = null;java.io. OutputStream out = null;tryin = new FileInputStream( from );out = new FileOutputStream( to );while ( true ) synchronized ( buffer ) int amountRead = in.read( buffer ); if ( amountRead = -1 ) break; out.write( buffer, 0, amountRead ); finallyif ( in != null ) in.close();if ( out != null ) out.close();System.out.println(.Copy Finish);if (removeold)java.io.File file =new java.io.File(from);if (file.delete()System.out.println(delete file:+file.getPath();file.delete();public static String getUploadPath(String path)if (path.indexOf(/)!=0)path = /+path;if (path.lastIndexOf(/)!=path.length()-1)path = path+/;return path;/public static String getFullPath(String url,ServletContext context)url = url.replace(, /);String path = context.getRealPath(url);return path.replace(/, );/public static boolean deleteFile(String url,ServletContext context) throws Exceptionjava.io.File file =new java.io.File(getFullPath(url.replace(/, ),context);String filepath = file.getPath();String ext = filepath.substring(filepath.lastIndexOf(.)+1);String minifilepath = filepath.substring(0,filepath.lastIndexOf(.)+_mini.+ext;java.io.File minifile = new java.io.File(minifilepath);if (minifile.exists()minifile.delete();if (file.exists()log.debug(delete file:+file.getPath();return file.delete();return false;/水 public static String createPathByDate(String url,ServletContext context)String fullpath = getFullPath(url,context);if (fullpath.lastIndexOf()!=fullpath.length()-1)fullpath +=;Calendar nowtime = Calendar.getInstance();fullpath +=String.valueOf(nowtime.get(Calendar.YEAR)+;SimpleDateFormat sdf = new SimpleDateFormat(MMdd);fullpath+=sdf.format(nowtime.getTime()+;File file = new File(fullpath);if (!file.exists()file.mkdirs();if (url.lastIndexOf()!=url.length()-1 & url.lastIndexOf(/)!=url.length()-1)url +=/;url += String.valueOf(nowtime.get(Calendar.YEAR)+/;url += sdf.format(nowtime.getTime()+/;return url;public static boolean createPath(String path,ServletContext context) throws ExceptionString fullpath = getFullPath(path,context);File file = new File(fullpath);boolean result= true;if (!file.exists()result =file.mkdirs();return result;/public static String getContextUrl(String url,HttpServletRequest request,ServletCo
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 政府采购增补合同范本
- 2025标准个人租房合同 房屋租赁合同范本
- 特种产品采购合同范本
- 人防口部安装合同范本
- 市场推广合同范本
- 美居招商合同范本
- 上海租车位合同范本
- 拆迁铁门出售合同范本
- 房房屋转租合同范本
- 2025保健品购销合同模板
- 老年学概论(第3版)PPT完整全套教学课件
- (完整版)Hamilton汉密尔顿焦虑量表
- 检验科实验室安全应急预案
- 教育教学理论试题与答案
- 净化装饰与机电安装工程URS
- GB/T 42064-2022普通照明用设备闪烁特性光闪烁计测试法
- WS/T 368-2012医院空气净化管理规范
- LY/T 2381-2014结构用木质材料基本要求
- JJG 1003-2016流量积算仪
- GB 31247-2014电缆及光缆燃烧性能分级
- 学院货物、服务采购询价表
评论
0/150
提交评论