版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、.目录说明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,Strin
2、g 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 setClassN
3、ame(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 setCl
4、assPath(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 sequenc
5、e;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.ObjectWrap
6、per;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 (templateconf
7、ig=null)templateconfig = new Configuration();templateconfig.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);templateconfig.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER);templateconfig.setTemplateLoader(new ClassTemplateLoader(this.getClass(),"/");templateconfig.s
8、etTemplateUpdateDelay(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 w
9、riter = 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 p
10、writer = new PrintWriter(fos);pwriter.write(writer.toString();pwriter.close();fos.close(); catch (Exception ex)ex.printStackTrace();5. 模版hibernate3.ftl<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-/Hibernate/Hibernate Mapping DTD 3.0/EN&
11、quot;"<hibernate-mapping> <class name="$entity.className" table="$entity.tableName" dynamic-update="false" dynamic-insert="false" select-before-update="false" optimistic-lock="version"> <#if perties?exists>&
12、lt;#list perties as property><#if property.primary><id name="$" type="$property.type"><#else><property name="$" type="$property.type"></#if><#if property.type="java.lang.String"&
13、gt;<column name="$property.field?upper_case" <#if property.length?exists>length="$property.length"</#if>></column><#elseif property.type="java.util.Date"><column name="$property.field?upper_case" length=7></column><
14、#elseif property.type="java.lang.Long" | property.type="java.lang.Integer"| property.type="java.lang.Short"><column name="$property.field?upper_case" <#if property.length?exists>precision="$property.length"</#if> scale="0"
15、></column></#if><#if property.primary=true><generator class="native"/></id><#else></property></#if></#list></#if> </class></hibernate-mapping>6. 工具类Assistant这个类为通用工具类,可单独拷贝到其他项目使用。该类的结构及功能有:package j.ta
16、ble.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.serv
17、let.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(para
18、meter,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 ke
19、y)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 HTMLEn
20、code(String txt) if (txt!=null && txt.length()>0)txt=txt.replaceAll("&","&");txt=txt.replaceAll("<","<");txt=txt.replaceAll(">",">");txt=txt.replaceAll(""",""");tx
21、t=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)
22、 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 getF
23、ileContent(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()InputStreamReade
24、r 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();retur
25、n 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 addTimeByMi
26、nutes(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
27、 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");
28、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()
29、.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 convertDateStrToStrin
30、g(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 stati
31、c 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");r
32、eturn 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");re
33、sult = 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 SimpleDateFor
34、mat("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(&
35、#39;')+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
36、.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 )
37、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()
38、;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.repla
39、ce('', '/');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);Str
40、ing 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
41、(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
42、 +=""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
43、 (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 Strin
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026山东日照市教育局直属学校招聘第一批急需紧缺教师29人备考题库(名师系列)附答案详解
- 2026广东惠州市惠城职业技术学校春季学期招聘化工实训室管理员(外聘合同制)1人备考题库及参考答案详解(黄金题型)
- 2026四川成都市邛崃市招聘事业单位人员13人备考题库带答案详解(考试直接用)
- 2026上半年四川事业单位统考安州区考试招聘教师26人备考题库附参考答案详解(巩固)
- 2026中国邮政集团有限公司安徽省分公司社会招聘备考题库及参考答案详解【a卷】
- 2025福建南平市公路建设管理有限公司招聘笔试及体测笔试历年典型考点题库附带答案详解
- 中建一局西北公司2026届春季校园招聘备考题库附参考答案详解(达标题)
- 2026北京大学艺术学院招聘劳动合同制人员1人备考题库(黄金题型)附答案详解
- 2026云南省房物业管理有限公司招聘12人备考题库含答案详解ab卷
- 校长书记安全责任制度
- 2026年安徽卫生健康职业学院单招综合素质考试题库带答案详解ab卷
- (新教材)2026年人音版二年级下册音乐全册教案
- 2026年春青岛版(新教材)小学科学三年级下册(全册)教学设计(附目录P199)
- 23G409先张法预应力混凝土管桩
- JJG 150-2005 金属布氏硬度计检定规程-(高清现行)
- GB∕T 17766-2020 固体矿产资源储量分类
- 《圆的面积》说课.ppt课件
- 小学语文教师培训:《制定双向细目表提高命题科学性》优质课件
- (高清版)GB_T 40916-2021液化气储运用高强度聚氨酯泡沫塑料
- 东北林业大学信纸模板
- 汽车减振器的设计(页)
评论
0/150
提交评论