博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网页模板生产器
阅读量:6911 次
发布时间:2019-06-27

本文共 6491 字,大约阅读时间需要 21 分钟。

package FreeMarker;import java.io.File;  import java.io.FileOutputStream;  import java.io.IOException;  import java.io.OutputStreamWriter;  import java.text.SimpleDateFormat;  import java.util.ArrayList;  import java.util.Date;  import java.util.HashMap;  import java.util.List;import java.util.Locale;import java.util.Map;    import freemarker.template.Configuration;  import freemarker.template.Template;  import freemarker.template.TemplateException;    public class Test {        /**      * @param args      */      @SuppressWarnings({ "deprecation", "unchecked", "rawtypes" })      public static void main(String[] args) {          //System.out.println(System.getProperty("user.dir")+"============");          Configuration cfg = new Configuration();          try {              cfg.setClassForTemplateLoading(Test.class, "/FreeMarker");//指定模板所在的classpath目录            cfg.setEncoding(Locale.CHINA, "gbk");            cfg.setSharedVariable("upperFC", new UpperFirstCharacter());//添加一个"宏"共享变量用来将属性名首字母大写              Template t = cfg.getTemplate("javabean.html");//指定模板              cfg.setSharedVariable("upperFC", new UpperFirstCharacter());//添加一个"宏"共享变量用来将属性名首字母大写                FileOutputStream fos = new FileOutputStream(new File("Item.java"));//java文件的生成目录                //模拟数据源              Map data = new HashMap();              data.put("basepackage", "com.ook");//包名              data.put("collection", "item");              data.put("entity", "Item");              data.put("entityDes", "商品entity");              SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");              data.put("entityCt", df.format(new Date()));                List propertyList = new ArrayList();              Map proMap = new HashMap();              proMap.put("proType", String.class.getSimpleName());              proMap.put("proName", "name");              proMap.put("des", "");              propertyList.add(proMap);                proMap = new HashMap();              proMap.put("proType", Date.class.getSimpleName());              proMap.put("proName", "ct");              proMap.put("des", "//添加时间");              propertyList.add(proMap);                            proMap = new HashMap();              proMap.put("proType", int.class.getSimpleName());              proMap.put("proName", "hotCnt");              proMap.put("des", "//阅读量");              propertyList.add(proMap);                data.put("properties", propertyList);              t.process(data, new OutputStreamWriter(fos,"utf-8"));//              fos.flush();              fos.close();                                          System.out.println("文件生成完毕~");          } catch (IOException e) {              e.printStackTrace();          } catch (TemplateException e) {              e.printStackTrace();          }      }    }
package FreeMarker;import java.io.IOException;  import java.io.Writer;  import java.util.Map;  import freemarker.core.Environment;  import freemarker.template.TemplateDirectiveBody;  import freemarker.template.TemplateDirectiveModel;  import freemarker.template.TemplateException;  import freemarker.template.TemplateModel;  import freemarker.template.TemplateModelException;    public class UpperFirstCharacter implements TemplateDirectiveModel{          @SuppressWarnings("rawtypes")      public   void  execute(Environment env,                Map params, TemplateModel[] loopVars,                TemplateDirectiveBody body)                        throws  TemplateException, IOException {            // Check if no parameters were given:             if  (!params.isEmpty()) {                throw   new  TemplateModelException(                        "This directive doesn't allow parameters." );            }            if  (loopVars.length !=  0 ) {                throw   new  TemplateModelException(                        "This directive doesn't allow loop variables." );            }              // If there is non-empty nested content:             if  (body !=  null ) {                // Executes the nested body. Same as <#nested> in FTL, except                 // that we use our own writer instead of the current output writer.                 body.render(new  UpperCaseFilterWriter(env.getOut()));            } else  {                throw   new  RuntimeException( "missing body" );            }        }          /**         * A {
@link Writer} that transforms the character stream to upper case * and forwards it to another {
@link Writer}. */ private static class UpperCaseFilterWriter extends Writer { private final Writer out; UpperCaseFilterWriter (Writer out) { this .out = out; } public void write( char [] cbuf, int off, int len) throws IOException { // char[] transformedCbuf = new char[len]; // for (int i = 0; i < len; i++) { // transformedCbuf[i] = Character.toUpperCase(cbuf[i + off]); // } // out.write(transformedCbuf); cbuf[0 ] = Character.toUpperCase(cbuf[ 0 ]); out.write(String.valueOf(cbuf).trim());///把右边空格去掉 } public void flush() throws IOException { out.flush(); } public void close() throws IOException { out.close(); } } }
package ${basepackage}.entity;    import java.util.Date;  import java.io.Serializable;  import org.springframework.data.annotation.Id;  import org.springframework.data.mongodb.core.mapping.Document;    /**   * ${entityDes}   * @date ${entityCt}   */  @Document(collection="${collection}")  public class ${entity} implements Serializable{      private static final long serialVersionUID = 1L;      @Id      private String id;  <#list properties as pro>      private ${pro.proType} ${pro.proName};${pro.des}  
public String getId() { return id; } public void setId(String id) { this.id = id; } <#list properties as pro> public void set<@upperFC>${pro.proName}
(${pro.proType} ${pro.proName}){ this.${pro.proName}=${pro.proName}; } public ${pro.proType} get<@upperFC>${pro.proName}
(){ return this.${pro.proName}; }
}

 

转载于:https://www.cnblogs.com/chenxuezhouLearnProgram/p/5712978.html

你可能感兴趣的文章
memcached与redis有什么区别
查看>>
【synchronized底层原理之2】悲观锁与乐观锁、线程阻塞的代价等
查看>>
双亲委派的认识
查看>>
Spring Cloud Spring Boot mybatis分布式微服务云架构(一)快速入门
查看>>
iOS雪花动画、音频图、新闻界面框架、2048游戏、二维码条形码扫码生成等源码...
查看>>
深入理解Java自带的线程池和缓冲队列
查看>>
【C++】智能指针简述(三):scoped_ptr
查看>>
Gogs:可能是比Gitlab更好的选择
查看>>
金融壹账通陈敏如:科技助力普惠金融 构建东南亚数字金融生态圈
查看>>
Node.js RESTful API
查看>>
Linux快速入门(一)
查看>>
IT兄弟连 JavaWeb教程 ElasticSearch在Linux下的安装和启动、常见问题解决
查看>>
spring cloud+docker+jenkins 自动化构建(2)
查看>>
iOS核心动画笔记3-视觉效果
查看>>
Ubuntu17 Jdk8 Tomcat64位环境搭建
查看>>
程序员也可以设计高大尚的xmind思维导图
查看>>
#生活琐事# 关于元宵节,红茶童鞋的记事
查看>>
OSChina 娱乐弹弹弹——程序猿眼中的女人
查看>>
OSChina 周二乱弹 —— 世界这么大,老板想让你去看看
查看>>
OSChina 周日乱弹 ——缘小小断腿记
查看>>