基于FreeMarker实现代码生成器(详细教程)

4 篇文章 0 订阅
1 篇文章 0 订阅

基于FreeMarker实现代码生成器

一、使用方式:
  1. 修改 database.properties 配置文件中的 JDBC-URL、userName、password
  2. 修改模板路径和文件生成路径
  3. 运行程序,生成代码:运行 Gernerator 类 Main 方法
二、具体代码(本人亲测有效):

结构

1.实体类(Cloumn.class,Table.class)
Cloumn.class

import com.code.constant.TypeConstant;
import com.code.util.StringUtils;
/**
 * <p>列实体类</p>
 * <p/>
 *
 */
public class Cloumn {

    private String cloumnName;
    private String comment;
    private String cloumnType;

    public String getCloumnName() {
        return cloumnName;
    }

    public void setCloumnName(String cloumnName) {
        this.cloumnName = cloumnName;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public String getCloumnType() {
        return cloumnType;
    }

    public void setCloumnType(String cloumnType) {
        this.cloumnType = cloumnType;
    }

    public String getFieldName() {
        return StringUtils.putOffUnderline(this.cloumnName);
    }

    public String getJavaType() {
        return TypeConstant.getJavaType(this.cloumnType);
    }

    public String getUpperCasecloumnName(){
        return StringUtils.captureName(getFieldName());
    }
}


Table.class

import com.code.util.StringUtils;

import java.io.Serializable;
import java.util.List;

/**
 * <p>表实体类</p>
 * <p/>
 * 
 */
public class Table implements Serializable {

    private String tableName;

    private String comment;

    private List<Cloumn> cloumns;

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public List<Cloumn> getCloumns() {
        return cloumns;
    }

    public void setCloumns(List<Cloumn> cloumns) {
        this.cloumns = cloumns;
    }

    public String getClassName(){
      return  StringUtils.captureName(StringUtils.putOffUnderline(this.tableName));
    }
}

2.constant(Constant.class,TypeConstant.class)
Constant.class

/**
 * 路径类
 */
public class Constant {
    //模板路径
    public static String template_path = "项目路径//resources//ftl";

    public static String service_save_path = "E://workspace//test";
    public static String servie_impl_save_path = "E://workspace//test";
    public static String mapper_save_path = "E://workspace//itrip//test";
    public static String model_save_path = "E://workspace//itrip//test";
}

TypeConstant.class

public class TypeConstant {
    /***
     * 类型常量
     */
    private static Map<String, String> typeMap = new HashMap<String, String>();

    static {
        typeMap.put("BIGINT", "Long");
        typeMap.put("INT", "Integer");
        typeMap.put("VARCHAR", "String");
        typeMap.put("TEXT", "String");
        typeMap.put("DATETIME", "Date");
        typeMap.put("DECIMAL", "Double");
    }

    public static void addType(String columnType, String javaType) {
        typeMap.put(columnType, javaType);
    }

    public static String getJavaType(String columnType) {
        return typeMap.get(columnType);
    }
}

3.handler(MvcHandler.class,TableHandler.class)
MvcHandler.class

import com.code.bean.Table;
import com.code.constant.Constant;
import com.code.util.FreeMarkerUtils;
import com.code.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class MvcHandler {

    String templateFile = Constant.template_path;

    public void executeModule(Table table) {
        Map input = new HashMap();
        input.put("table", table);
        input.put("package", "itrip");
        input.put("lowerClassName", StringUtils.lowerName(table.getClassName()));
        String fileName = table.getClassName() + ".java";
        String savePath = Constant.model_save_path;
        String templateName = "model";
        FreeMarkerUtils.genteratorFile(input, templateFile, templateName, savePath, fileName);
    }

    public void executeService(Table table) {
        Map input = new HashMap();
        input.put("table", table);
        input.put("package", "itrip");
        input.put("lowerClassName", StringUtils.lowerName(table.getClassName()));
        String fileName = table.getClassName() + "Service" + ".java";
        String savePath = Constant.service_save_path + "//" + StringUtils.lowerName(table.getClassName()) + "//";
        String templateName = "service";
        FreeMarkerUtils.genteratorFile(input, templateFile, templateName, savePath, fileName);
    }

    public void executeServiceImpl(Table table) {
        Map input = new HashMap();
        input.put("table", table);
        input.put("package", "itrip");
        input.put("lowerClassName", StringUtils.lowerName(table.getClassName()));
        String fileName = table.getClassName() + "ServiceImpl" + ".java";
        String savePath = Constant.servie_impl_save_path + "//" + StringUtils.lowerName(table.getClassName()) + "//";
        String templateName = "serviceImpl";
        FreeMarkerUtils.genteratorFile(input, templateFile, templateName, savePath, fileName);
    }

    public void executeMapper(Table table) {
        Map input = new HashMap();
        input.put("table", table);
        input.put("package", "itrip");
        input.put("lowerClassName", StringUtils.lowerName(table.getClassName()));
        String fileName = table.getClassName() + "Mapper" + ".xml";
        String savePath = Constant.mapper_save_path + "//" + StringUtils.lowerName(table.getClassName()) + "//";
        String templateName = "mapper";
        FreeMarkerUtils.genteratorFile(input, templateFile, templateName, savePath, fileName);
    }

    public void executeClazzMapper(Table table) {
        Map input = new HashMap();
        input.put("table", table);
        input.put("package", "itrip");
        input.put("lowerClassName", StringUtils.lowerName(table.getClassName()));
        String fileName = table.getClassName() + "Mapper" + ".java";
        String savePath = Constant.mapper_save_path + "//" + StringUtils.lowerName(table.getClassName()) + "//";
        String templateName = "clazzMapper";
        FreeMarkerUtils.genteratorFile(input, templateFile, templateName, savePath, fileName);
    }
}

TableHandler.class

import com.code.bean.Cloumn;
import com.code.bean.Table;


import java.sql.*;
import java.util.*;

/**
 *
 */
public class TableHandler {

    private List<String> tableExceptList = new ArrayList<String>();

    private static String DBDRIVER ="com.mysql.jdbc.Driver";

    private static String DBURL = "jdbc:mysql://localhost:3306/itripdb?useUnicode=true&characterEncoding=utf-8";

    private static String DBUSER = "root";


    private static String DBPASS = "123456";

    public void addExceptTable(String tableName) {
        tableExceptList.add(tableName);
    }

    private List<Table> queryDataTables() {
        DatabaseMetaData dmd = null;
        Connection conn = null;
        List<Table> tables = new ArrayList<Table>();
        try {
            Class.forName(DBDRIVER);//1、加载驱动
            //2、获取连接对象Connection
            conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
            DatabaseMetaData dbmd = conn.getMetaData();
            //3、生成Statment
            ResultSet resultSet = dbmd.getTables(null, null, null, new String[]{"TABLE"});
            while (resultSet.next()) {
                Table table = new Table();
                table.setCloumns(new ArrayList<Cloumn>());
                String tableName = resultSet.getString("TABLE_NAME");
                String remarkes = getCommentByTableName(tableName);
                table.setTableName(tableName);
                table.setComment(remarkes);
                ResultSet rs = dbmd.getColumns(null, "%", tableName, "%");
                while (rs.next()) {
                    Cloumn cloumn = new Cloumn();
                    cloumn.setCloumnName(rs.getString("COLUMN_NAME"));
                    cloumn.setComment(rs.getString("REMARKS"));
                    cloumn.setCloumnType(rs.getString("TYPE_NAME"));
                    table.getCloumns().add(cloumn);
                }
                tables.add(table);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return tables;
    }

    public List<Table> getTables() {
        List<Table> dataTableList = queryDataTables();
        if (null != dataTableList && dataTableList.size() != 0) {
            if (null != tableExceptList && tableExceptList.size() == 0) {
                for (String tableName : tableExceptList) {
                    Iterator<Table> it = dataTableList.iterator();
                    while (it.hasNext()) {
                        Table x = it.next();
                        if (x.getTableName().equals(tableName)) {
                            it.remove();
                        }
                    }
                }
            }
        }
        return dataTableList;
    }

    private static String getCommentByTableName(String tableName) throws Exception {
        Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SHOW CREATE TABLE " + tableName);
        String comment = null;
        if (rs != null && rs.next()) {
            comment = parse(rs.getString(2));
        }
        rs.close();
        stmt.close();
        conn.close();
        return comment;
    }

    /**
     * 返回注释信息
     *
     * @param all
     * @return
     */
    private static String parse(String all) {
        String comment = null;
        int index = all.indexOf("COMMENT='");
        if (index < 0) {
            return "";
        }
        comment = all.substring(index + 9);
        comment = comment.substring(0, comment.length() - 1);
        return comment;
    }
}

4.util(FreeMarkerUtils.class,HelloFreeMarker.class,PropertiesUtils.class,StringUtils.class)
FreeMarkerUtils.class

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;


import java.io.*;
import java.util.Map;


public class FreeMarkerUtils {

    private static Template getTemplate(String template_path,String templateFileName){
        Configuration configuration = new Configuration();
        Template template =null;
        try {
            configuration.setDirectoryForTemplateLoading(new File(template_path));
            configuration.setObjectWrapper(new DefaultObjectWrapper());
            configuration.setDefaultEncoding("UTF-8");   //设置编码
            //模板文件
            template=configuration.getTemplate(templateFileName + ".ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return template;
    }

    public static void genteratorFile(Map<String,String> input,String template_path,String templateFileName,String savePath,String fileName){
        Template template=getTemplate(template_path,templateFileName);
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        Writer writer = null;
        try {
            writer=new OutputStreamWriter(new FileOutputStream(savePath+"\\"+fileName), "UTF-8");
            template.process(input, writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

HelloFreeMarker.class

import java.util.*;
import java.io.*;
import freemarker.template.*;

public class HelloFreeMarker{

    private Configuration cfg;

    public void init() throws Exception{
        //初始化FreeMarker配置
        //创建一个Configuration实例
        cfg = new Configuration();
        //设置FreeMarker的模版文件位置
        cfg.setDirectoryForTemplateLoading(new File("templates"));
    }

    public void process()throws Exception{
        Map root = new HashMap();
        root.put("name", "FreeMarker!");
        root.put("msg" , "您已经完成了第一个FreeMarker的示例");
        Template t = cfg.getTemplate("test.ftl");
        t.process(root, new OutputStreamWriter(System.out));
    }

    public static void main(String[] args)throws Exception{
        HelloFreeMarker hf = new HelloFreeMarker();
        hf.init();
        hf.process();
    }
}

PropertiesUtils.class

import java.io.InputStreamReader;
import java.util.Properties;

/**
 * <p></p>
 * search 项目专用的读取配置文件的工具类
 * @author XX
 * @version v1.0
 *
 */
public class PropertiesUtils {

    private static Properties props;

    /**
     * 加载配置文件
     *
     * @param fileName
     */
    private static void readProperties(String fileName) {
        try {
            props = new Properties();
            InputStreamReader inputStream = new InputStreamReader(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName), "UTF-8");
            props.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 根据key读取对应的value
     *
     * @param key
     * @return
     */
    public static String get(String fileName,String key) {
        readProperties(fileName);
        return props.getProperty(key);
    }

}

StringUtils.class

public class StringUtils {
    /**
     * 某位置字母大写
     *
     * @param name
     * @param indx
     * @return
     */
    public static String captureName(String name, int indx) {
        name = name.substring(0, indx) + name.substring(indx, indx + 1).toUpperCase() + name.substring(indx + 1);
        return name;
    }

    /**
     * 首字母大写
     *
     * @param name
     * @return
     */
    public static String captureName(String name) {
        name = name.substring(0, 1).toUpperCase() + name.substring(1);
        return name;
    }

    /***
     * 首字母小写
     *
     * @param name
     * @return
     */
    public static String lowerName(String name) {
        name = name.substring(0, 1).toLowerCase() + name.substring(1);
        return name;
    }

    /***
     * 去掉下划线 并用驼峰原则进行转化
     *
     * @return
     */
    public static String putOffUnderline(String columnName) {
        StringBuffer fieldNameBuffer = null;
        String tempNameArray[] = columnName.split("_");
        for (int i = 0; i < tempNameArray.length; i++) {
            if (i == 0) {
                fieldNameBuffer = new StringBuffer(tempNameArray[i]);
            } else {
                fieldNameBuffer.append(captureName(tempNameArray[i]));
            }
        }
        return fieldNameBuffer.toString();
    }

    public static void main(String[] args) {
        String a = putOffUnderline("a_bccc_d");
        System.out.println(a);
    }
}

5.启动类(Genterator.class)
Genterator.class

import com.code.bean.Table;
import com.code.handler.MvcHandler;
import com.code.handler.TableHandler;


import java.util.List;

/**
 * <p></p>
 * <p/>
 * 
 */
public class Genterator {

    public static void main(String args[]) throws Exception {
        TableHandler tableHandler = new TableHandler();
        tableHandler.addExceptTable("");//排除某一个表
        MvcHandler mvcHandler = new MvcHandler();
        List<Table> tableList = tableHandler.getTables();
        for (Table table : tableList) {
            mvcHandler.executeModule(table);
            mvcHandler.executeService(table);
            mvcHandler.executeServiceImpl(table);
            mvcHandler.executeMapper(table);
            mvcHandler.executeClazzMapper(table);
        }
    }
}
模板文件

在这里插入图片描述
clazzMapper.ftl

package cn.${package}.mapper.${lowerClassName};
import cn.${package}.pojo.${table.className};
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;

public interface ${table.className}Mapper {

	public ${table.className} get${table.className}ById(@Param(value = "id") Long id)throws Exception;

	public List<${table.className}>	get${table.className}ListByMap(Map<String,Object> param)throws Exception;

	public Integer get${table.className}CountByMap(Map<String,Object> param)throws Exception;

	public Integer insert${table.className}(${table.className} ${lowerClassName})throws Exception;

	public Integer update${table.className}(${table.className} ${lowerClassName})throws Exception;

	public Integer delete${table.className}ById(@Param(value = "id") Long id)throws Exception;

}

mapper.ftl

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.${package}.mapper.${lowerClassName}.${table.className}Mapper">

    <select id="get${table.className}ById" resultType="cn.${package}.pojo.${table.className}" >
        select
        <#list table.cloumns as cloumn>
            <#if cloumn_has_next>
                ${cloumn.cloumnName} as ${cloumn.fieldName},
            <#else>
                ${cloumn.cloumnName} as ${cloumn.fieldName}
            </#if>
        </#list>
        from ${table.tableName}
        <trim prefix="where" prefixOverrides="and | or">
            <if test="id != null">
                and id=${r"#{id}"}
            </if>
        </trim>
    </select>

    <select id="get${table.className}ListByMap" resultType="cn.${package}.pojo.${table.className}" parameterType="java.util.Map">
        select
        <#list table.cloumns as cloumn>
            <#if cloumn_has_next>
                ${cloumn.cloumnName} as ${cloumn.fieldName},
            <#else>
                ${cloumn.cloumnName} as ${cloumn.fieldName}
            </#if>
        </#list>
        from ${table.tableName}
        <trim prefix="where" prefixOverrides="and | or">
            <#list table.cloumns as cloumn>
                <#if cloumn_has_next>
                    <if test="${cloumn.fieldName} != null and ${cloumn.fieldName}!=''">
                        and ${cloumn.cloumnName}=${r"#{"}${cloumn.fieldName}}
                    </if>
                </#if>
            </#list>
        </trim>
         order by creationDate desc
        <if test="beginPos != null and beginPos!='' and pageSize != null  and pageSize !='' ">
            limit ${r"#{"}beginPos},${r"#{"}pageSize}
        </if>
    </select>

    <select id="get${table.className}CountByMap" resultType="Integer"  parameterType="java.util.Map">
        select count(*) from ${table.tableName}
        <trim prefix="where" prefixOverrides="and | or">
        <#list table.cloumns as cloumn>
            <#if cloumn_has_next>
                <if test="${cloumn.fieldName} != null and ${cloumn.fieldName}!=''">
                    and ${cloumn.cloumnName}=${r"#{"}${cloumn.fieldName}}
                </if>
            <#else>
                <if test="${cloumn.fieldName} != null and ${cloumn.fieldName}!=''">
                    and ${cloumn.cloumnName}=${r"#{"}${cloumn.fieldName}}
                </if>
            </#if>
        </#list>
        </trim>
    </select>

    <insert id="insert${table.className}" parameterType="cn.${package}.pojo.${table.className}">
        insert into ${table.tableName}(
        <#list table.cloumns as cloumn>
                <#if cloumn_has_next>
                    <#if  cloumn.cloumnName!='id'>
                        ${cloumn.cloumnName},
                    </#if>
                <#else>
                    <#if  cloumn.cloumnName!='id'>
                        ${cloumn.cloumnName})
                    </#if>
                </#if>
        </#list>
        values(
        <#list table.cloumns as cloumn>
            <#if cloumn_has_next>
                <#if  cloumn.cloumnName!='id'>
                     ${r"#{"}${cloumn.fieldName}},
                </#if>
            <#else>
                <#if  cloumn.cloumnName!='id'>
                    ${r"#{"}${cloumn.fieldName}})
                </#if>
            </#if>
        </#list>
    </insert>

    <update id="update${table.className}" parameterType="cn.${package}.pojo.${table.className}">
        update ${table.tableName}
        <trim prefix="set" suffixOverrides="," suffix="where id=${r"#{"}id}">
            <#list table.cloumns as cloumn>
                <#if cloumn_has_next>
                    <if test="${cloumn.fieldName} != null and ${cloumn.fieldName}!=''">
                        ${cloumn.cloumnName}=${r"#{"}${cloumn.fieldName}},
                    </if>
                <#else>
                    <if test="${cloumn.fieldName} != null and ${cloumn.fieldName}!=''">
                        ${cloumn.cloumnName}=${r"#{"}${cloumn.fieldName}}
                    </if>
                </#if>
            </#list>
        </trim>
    </update>

    <delete id="delete${table.className}ById" parameterType="Long">
        delete from ${table.tableName} where id = ${r"#{"}id}
    </delete>
</mapper>

model.ftl

package cn.${package}.pojo;
import java.io.Serializable;
import java.util.Date;
/***
*   ${table.comment}
*/
public class ${table.className} implements Serializable {
        <#list table.cloumns as cloumn>
        //${cloumn.comment}
        private ${cloumn.javaType} ${cloumn.fieldName};
        </#list>
        //get set 方法
        <#list table.cloumns as cloumn>
            public void set${cloumn.upperCasecloumnName} (${cloumn.javaType}  ${cloumn.javaType}){
                this.${cloumn.fieldName}=${cloumn.fieldName};
            }
            public  ${cloumn.cloumnType} get${cloumn.upperCasecloumnName}(){
                return this.${cloumn.fieldName};
            }
        </#list>
}

service.ftl

package cn.${package}.service.${lowerClassName};
import cn.${package}.pojo.${table.className};
import java.util.List;
import java.util.Map;
import java.util.List;
import java.util.Map;
import cn.itrip.common.Page;
/**
* Created by shang-pc on 2015/11/7.
*/
public interface ${table.className}Service {

    public ${table.className} get${table.className}ById(Long id)throws Exception;

    public List<${table.className}>	get${table.className}ListByMap(Map<String,Object> param)throws Exception;

    public Integer get${table.className}CountByMap(Map<String,Object> param)throws Exception;

    public Integer itriptxAdd${table.className}(${table.className} ${lowerClassName})throws Exception;

    public Integer itriptxModify${table.className}(${table.className} ${lowerClassName})throws Exception;

    public Integer itriptxDelete${table.className}ById(Long id)throws Exception;

    public Page<${table.className}> query${table.className}PageByMap(Map<String,Object> param,Integer pageNo,Integer pageSize)throws Exception;
}

serviceImpl.ftl

package cn.${package}.service.${lowerClassName};
import cn.${package}.mapper.${lowerClassName}.${table.className}Mapper;
import cn.${package}.pojo.${table.className};
import cn.itrip.common.EmptyUtils;
import cn.itrip.common.Page;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import cn.itrip.common.Constants;
@Service
public class ${table.className}ServiceImpl implements ${table.className}Service {

    @Resource
    private ${table.className}Mapper ${lowerClassName}Mapper;

    public ${table.className} get${table.className}ById(Long id)throws Exception{
        return ${lowerClassName}Mapper.get${table.className}ById(id);
    }

    public List<${table.className}>	get${table.className}ListByMap(Map<String,Object> param)throws Exception{
        return ${lowerClassName}Mapper.get${table.className}ListByMap(param);
    }

    public Integer get${table.className}CountByMap(Map<String,Object> param)throws Exception{
        return ${lowerClassName}Mapper.get${table.className}CountByMap(param);
    }

    public Integer itriptxAdd${table.className}(${table.className} ${lowerClassName})throws Exception{
            ${lowerClassName}.setCreationDate(new Date());
            return ${lowerClassName}Mapper.insert${table.className}(${lowerClassName});
    }

    public Integer itriptxModify${table.className}(${table.className} ${lowerClassName})throws Exception{
        ${lowerClassName}.setModifyDate(new Date());
        return ${lowerClassName}Mapper.update${table.className}(${lowerClassName});
    }

    public Integer itriptxDelete${table.className}ById(Long id)throws Exception{
        return ${lowerClassName}Mapper.delete${table.className}ById(id);
    }

    public Page<${table.className}> query${table.className}PageByMap(Map<String,Object> param,Integer pageNo,Integer pageSize)throws Exception{
        Integer total = ${lowerClassName}Mapper.get${table.className}CountByMap(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<${table.className}> ${lowerClassName}List = ${lowerClassName}Mapper.get${table.className}ListByMap(param);
        page.setRows(${lowerClassName}List);
        return page;
    }

}

test.ftl

<html>
<head>
    <title>${name}</title>
</head>
<body>
    <p>${msg}</p>
</body>
</html>

database.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/sss?useUnicode=true&characterEncoding=utf-8
user=root
password=root
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.code</groupId>
    <artifactId>parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>6</source>
                    <target>6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
    </dependencies>
</project>
三、运行效果

在这里插入图片描述
在这里插入图片描述

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: FreeMarker是一个用于生成动态内容的Java模板引擎。它是基于模板和数据模型的,可以将模板文件和数据模型结合起来生成最终的输出结果。 Java基于FreeMarker生成器源码的主要涉及以下几个方面: 1. 导入必要的包:首先需要导入FreeMarker的相关包,包括FreeMarker的核心类、配置类以及模板加载器等。这些包的导入是使用FreeMarker进行模板生成的基础。 2. 配置模板引擎:通过创建Configuration对象来配置FreeMarker模板引擎的相关设置。可以设置模板文件的加载路径、字符编码、错误处理方式等。 3. 加载模板文件:使用TemplateLoader从指定的路径或者是classpath中加载模板文件。加载模板文件后,可以将其编译成Template对象,以便后续的模板生成。 4. 准备数据模型:根据需要的输出结果,准备好数据模型。数据模型可以是一个Java对象,也可以是一个Map,包含了模板需要的各种数据。 5. 生成输出结果:在模板生成时,将数据模型传入模板,调用process方法来生成输出结果。process方法会将数据模型与模板结合起来,生成最终的输出结果。 Java基于FreeMarker生成器源码的核心思想是使用模板引擎将模板文件和数据模型结合起来,生成最终的输出结果。通过配置模板引擎、加载模板文件、准备数据模型,可以实现各种类型的输出结果,如HTML页面、XML文档、邮件模板等。使用FreeMarker可以实现模板的复用,提高系统的可维护性和扩展性。 ### 回答2: FreeMarker是一款基于Java的模板引擎,它的生成器源码提供了一种将模板文件与数据进行组合并生成输出文件的机制。 FreeMarker生成器源码主要包含以下几个关键部分: 1. 模板文件:模板文件是FreeMarker生成器的核心。它使用FreeMarker的模板语法,定义了输出文件的结构和内容。模板文件中可以嵌入变量、条件判断语句、循环语句等,通过填充数据来生成最终的输出文件。 2. 数据源:生成器源码接收数据源作为输入,这些数据源可以是数据库查询结果、API返回的数据、用户输入等。数据源可以包含多个数据对象,每个对象对应模板文件中的一个变量。数据源可以通过Java代码从各种位置获取,然后传递给生成器来生成最终的输出文件。 3. FreeMarker配置:配置对象包含了一些生成器的基本设置,比如模板文件所在的路径、输出文件的编码格式等。配置对象可以通过Java代码进行定制,以满足生成器的需求。 4. 模板引擎:模板引擎是FreeMarker生成器的核心处理引擎,它负责将模板文件和数据源进行组合,并生成最终的输出文件。模板引擎会根据模板文件中的语法规则,将数据源的数据填充到模板文件的相应位置,生成最终的输出文件。 5. 输出文件:生成器会将最终的输出文件保存到指定的位置,可以是本地文件系统、网络位置或者其他目标。 通过以上几个关键部分的协作,FreeMarker生成器源码实现了将模板文件和数据源进行组合的功能,方便开发人员根据需求生成各种类型的输出文件。它可以应用于各种场景,比如生成静态网页、生成报表、生成邮件内容等等。其灵活且可定制的特性,使得Java基于FreeMarker生成器源码成为了开发人员常用的工具之一。 ### 回答3: Java基于Freemarker生成器源码是一种使用Java语言和Freemarker模板引擎的代码,用于根据模板生成特定类型的文本文件(如HTML、XML、Java等)。 Java基于Freemarker生成器源码的核心思路是将模板文件与数据模型进行结合,生成最终的文本文件。首先,需要准备好模板文件,这个模板文件是一个普通的文本文件,其中嵌入了一些特殊的Freemarker语法标签。这些标签用来表示可替换的部分、循环、条件语句等等。 接下来,通过Java代码读取模板文件,并使用Freemarker引擎解析模板文件。这一步骤将模板文件转换成一个Freemarker的Template对象,然后将数据模型与模板进行合并。数据模型可以是一个Java对象,也可以是一个Map对象。在合并过程中,模板中的Freemarker语法标签会被替换成具体的值或逻辑,从而生成最终的文本文件。 最后,通过Java代码将生成的文本文件保存到指定的位置。生成器源码中通常包含一些文件操作的逻辑,用于创建、保存或输出生成的文本文件。 使用Java基于Freemarker生成器源码可以提高开发的效率和灵活性。通过准备好模板文件和相应的数据模型,我们可以快速生成各种类型的文本文件,无需手动编写大量重复的代码。同时,由于模板文件是可配置的,可以根据具体需求动态生成不同的文本内容。这使得代码的维护和修改更加方便。 总结来说,Java基于Freemarker生成器源码是一种利用Freemarker模板引擎和Java语言实现的代码,用于根据模板和数据模型生成特定类型的文本文件。它能够提高开发效率和灵活性,使得文本文件的生成、修改和维护更加方便。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值