RuoYi
2020-07-31 56ea7c9caf2eec22d5a7e9ce84e9ffff09b4d95d
代码生成支持自定义路径
1 files added
1 files renamed
8 files modified
357 ■■■■■ changed files
ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/file/FileUtils.java 142 ●●●●● patch | view | raw | blame | history
ruoyi-modules/ruoyi-gen/src/main/java/com/ruoyi/gen/controller/GenController.java 22 ●●●● patch | view | raw | blame | history
ruoyi-modules/ruoyi-gen/src/main/java/com/ruoyi/gen/domain/GenTable.java 26 ●●●●● patch | view | raw | blame | history
ruoyi-modules/ruoyi-gen/src/main/java/com/ruoyi/gen/service/GenTableServiceImpl.java 70 ●●●●● patch | view | raw | blame | history
ruoyi-modules/ruoyi-gen/src/main/java/com/ruoyi/gen/service/IGenTableService.java 16 ●●●● patch | view | raw | blame | history
ruoyi-modules/ruoyi-gen/src/main/resources/mapper/generator/GenTableMapper.xml 14 ●●●● patch | view | raw | blame | history
ruoyi-ui/src/api/tool/gen.js 9 ●●●●● patch | view | raw | blame | history
ruoyi-ui/src/views/tool/gen/genInfoForm.vue 46 ●●●●● patch | view | raw | blame | history
ruoyi-ui/src/views/tool/gen/index.vue 10 ●●●● patch | view | raw | blame | history
sql/ry_20200730.sql 2 ●●●●● patch | view | raw | blame | history
ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/file/FileUtils.java
New file
@@ -0,0 +1,142 @@
package com.ruoyi.common.core.utils.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
/**
 * 文件处理工具类
 *
 * @author ruoyi
 */
public class FileUtils extends org.apache.commons.io.FileUtils
{
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os 输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException
    {
        FileInputStream fis = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }
    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath)
    {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists())
        {
            file.delete();
            flag = true;
        }
        return flag;
    }
    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename)
    {
        return filename.matches(FILENAME_PATTERN);
    }
    /**
     * 下载文件名重新编码
     *
     * @param request 请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException
    {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE"))
        {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        }
        else if (agent.contains("Firefox"))
        {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        }
        else if (agent.contains("Chrome"))
        {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        else
        {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }
}
ruoyi-modules/ruoyi-gen/src/main/java/com/ruoyi/gen/controller/GenController.java
@@ -148,15 +148,27 @@
    }
    /**
     * 生成代码
     * 生成代码(下载方式)
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:code')")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
    {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }
    /**
     * 生成代码(自定义路径)
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:code')")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/genCode/{tableName}")
    public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
    public AjaxResult genCode(HttpServletResponse response, @PathVariable("tableName") String tableName)
    {
        byte[] data = genTableService.generatorCode(tableName);
        genCode(response, data);
        genTableService.generatorCode(tableName);
        return AjaxResult.success();
    }
    /**
@@ -168,7 +180,7 @@
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException
    {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.generatorCode(tableNames);
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }
ruoyi-modules/ruoyi-gen/src/main/java/com/ruoyi/gen/domain/GenTable.java
@@ -55,6 +55,12 @@
    @NotBlank(message = "作者不能为空")
    private String functionAuthor;
    /** 生成代码方式(0zip压缩包 1自定义路径) */
    private String genType;
    /** 生成路径(不填默认项目路径) */
    private String genPath;
    /** 主键信息 */
    private GenTableColumn pkColumn;
@@ -180,6 +186,26 @@
        this.functionAuthor = functionAuthor;
    }
    public String getGenType()
    {
        return genType;
    }
    public void setGenType(String genType)
    {
        this.genType = genType;
    }
    public String getGenPath()
    {
        return genPath;
    }
    public void setGenPath(String genPath)
    {
        this.genPath = genPath;
    }
    public GenTableColumn getPkColumn()
    {
        return pkColumn;
ruoyi-modules/ruoyi-gen/src/main/java/com/ruoyi/gen/service/GenTableServiceImpl.java
@@ -1,6 +1,7 @@
package com.ruoyi.gen.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
@@ -22,7 +23,9 @@
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.GenConstants;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.text.CharsetKit;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.gen.domain.GenTable;
import com.ruoyi.gen.domain.GenTableColumn;
@@ -201,13 +204,13 @@
    }
    /**
     * 生成代码
     * 生成代码(下载方式)
     * 
     * @param tableName 表名称
     * @return 数据
     */
    @Override
    public byte[] generatorCode(String tableName)
    public byte[] downloadCode(String tableName)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
@@ -217,13 +220,55 @@
    }
    /**
     * 批量生成代码
     * 生成代码(自定义路径)
     *
     * @param tableName 表名称
     * @return 数据
     */
    @Override
    public void generatorCode(String tableName)
    {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        // 查询列信息
        List<GenTableColumn> columns = table.getColumns();
        setPkColumn(table, columns);
        VelocityInitializer.initVelocity();
        VelocityContext context = VelocityUtils.prepareContext(table);
        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm"))
            {
                // 渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, Constants.UTF8);
                tpl.merge(context, sw);
                try
                {
                    String path = getGenPath(table, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
                }
                catch (IOException e)
                {
                    throw new CustomException("渲染模板失败,表名:" + table.getTableName());
                }
            }
        }
    }
    /**
     * 批量生成代码(下载方式)
     * 
     * @param tableNames 表数组
     * @return 数据
     */
    @Override
    public byte[] generatorCode(String[] tableNames)
    public byte[] downloadCode(String[] tableNames)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
@@ -346,4 +391,21 @@
            genTable.setParentMenuName(parentMenuName);
        }
    }
    /**
     * 获取代码生成地址
     *
     * @param table 业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    public static String getGenPath(GenTable table, String template)
    {
        String genPath = table.getGenPath();
        if (StringUtils.equals(genPath, "/"))
        {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
        }
        return genPath + File.separator + VelocityUtils.getFileName(template, table);
    }
}
ruoyi-modules/ruoyi-gen/src/main/java/com/ruoyi/gen/service/IGenTableService.java
@@ -75,20 +75,28 @@
    public Map<String, String> previewCode(Long tableId);
    /**
     * 生成代码
     * 生成代码(下载方式)
     * 
     * @param tableName 表名称
     * @return 数据
     */
    public byte[] generatorCode(String tableName);
    public byte[] downloadCode(String tableName);
    /**
     * 批量生成代码
     * 生成代码(自定义路径)
     *
     * @param tableName 表名称
     * @return 数据
     */
    public void generatorCode(String tableName);
    /**
     * 批量生成代码(下载方式)
     * 
     * @param tableNames 表数组
     * @return 数据
     */
    public byte[] generatorCode(String[] tableNames);
    public byte[] downloadCode(String[] tableNames);
    /**
     * 修改保存参数校验
ruoyi-modules/ruoyi-gen/src/main/resources/mapper/generator/GenTableMapper.xml
@@ -15,6 +15,8 @@
        <result property="businessName"   column="business_name"   />
        <result property="functionName"   column="function_name"   />
        <result property="functionAuthor" column="function_author" />
        <result property="genType"        column="gen_type"        />
        <result property="genPath"        column="gen_path"        />
        <result property="options"        column="options"         />
        <result property="createBy"       column="create_by"       />
        <result property="createTime"     column="create_time"     />
@@ -50,7 +52,7 @@
    </resultMap>
    
    <sql id="selectGenTableVo">
        select table_id, table_name, table_comment, class_name, tpl_category, package_name, module_name, business_name, function_name, function_author, options, create_by, create_time, update_by, update_time, remark from gen_table
        select table_id, table_name, table_comment, class_name, tpl_category, package_name, module_name, business_name, function_name, function_author, gen_type, gen_path, options, create_by, create_time, update_by, update_time, remark from gen_table
    </sql>
    
    <select id="selectGenTableList" parameterType="GenTable" resultMap="GenTableResult">
@@ -100,7 +102,7 @@
    </select>
    
    <select id="selectGenTableById" parameterType="Long" resultMap="GenTableResult">
        SELECT t.table_id, t.table_name, t.table_comment, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.options, t.remark,
        SELECT t.table_id, t.table_name, t.table_comment, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
               c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
        FROM gen_table t
             LEFT JOIN gen_table_column c ON t.table_id = c.table_id
@@ -108,7 +110,7 @@
    </select>
    
    <select id="selectGenTableByName" parameterType="String" resultMap="GenTableResult">
        SELECT t.table_id, t.table_name, t.table_comment, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.options, t.remark,
        SELECT t.table_id, t.table_name, t.table_comment, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
               c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
        FROM gen_table t
             LEFT JOIN gen_table_column c ON t.table_id = c.table_id
@@ -126,6 +128,8 @@
            <if test="businessName != null and businessName != ''">business_name,</if>
            <if test="functionName != null and functionName != ''">function_name,</if>
            <if test="functionAuthor != null and functionAuthor != ''">function_author,</if>
            <if test="genType != null and genType != ''">gen_type,</if>
            <if test="genPath != null and genPath != ''">gen_path,</if>
            <if test="remark != null and remark != ''">remark,</if>
             <if test="createBy != null and createBy != ''">create_by,</if>
            create_time
@@ -139,6 +143,8 @@
            <if test="businessName != null and businessName != ''">#{businessName},</if>
            <if test="functionName != null and functionName != ''">#{functionName},</if>
            <if test="functionAuthor != null and functionAuthor != ''">#{functionAuthor},</if>
            <if test="genType != null and genType != ''">#{genType},</if>
            <if test="genPath != null and genPath != ''">#{genPath},</if>
            <if test="remark != null and remark != ''">#{remark},</if>
             <if test="createBy != null and createBy != ''">#{createBy},</if>
            sysdate()
@@ -152,6 +158,8 @@
            <if test="tableComment != null and tableComment != ''">table_comment = #{tableComment},</if>
            <if test="className != null and className != ''">class_name = #{className},</if>
            <if test="functionAuthor != null and functionAuthor != ''">function_author = #{functionAuthor},</if>
            <if test="genType != null and genType != ''">gen_type = #{genType},</if>
            <if test="genPath != null and genPath != ''">gen_path = #{genPath},</if>
            <if test="tplCategory != null and tplCategory != ''">tpl_category = #{tplCategory},</if>
            <if test="packageName != null and packageName != ''">package_name = #{packageName},</if>
            <if test="moduleName != null and moduleName != ''">module_name = #{moduleName},</if>
ruoyi-ui/src/api/tool/gen.js
@@ -42,6 +42,7 @@
    params: data
  })
}
// 预览生成代码
export function previewTable(tableId) {
  return request({
@@ -49,6 +50,7 @@
    method: 'get'
  })
}
// 删除表数据
export function delTable(tableId) {
  return request({
@@ -57,3 +59,10 @@
  })
}
// 生成代码(自定义路径)
export function genCode(tableName) {
  return request({
    url: '/code/gen/genCode/' + tableName,
    method: 'get'
  })
}
ruoyi-ui/src/views/tool/gen/genInfoForm.vue
@@ -60,14 +60,56 @@
      </el-col>
      <el-col :span="12">
        <el-form-item prop="functionName">
        <el-form-item>
          <span slot="label">
            上级菜单
            <el-tooltip content="分配到指定菜单下,例如 系统管理" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <treeselect :append-to-body="true" v-model="info.parentMenuId" :options="menus" :normalizer="normalizer" :show-count="true" placeholder="请选择系统菜单"/>
          <treeselect
            :append-to-body="true"
            v-model="info.parentMenuId"
            :options="menus"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="请选择系统菜单"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="genType">
          <span slot="label">
            生成代码方式
            <el-tooltip content="默认为zip压缩包下载,也可以自定义生成路径" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-radio v-model="info.genType" label="0">zip压缩包</el-radio>
          <el-radio v-model="info.genType" label="1">自定义路径</el-radio>
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="info.genType == '1'">
        <el-form-item prop="genPath">
          <span slot="label">
            自定义路径
            <el-tooltip content="填写磁盘绝对路径,若不填写,则生成到当前Web项目下" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-input v-model="info.genPath">
            <el-dropdown slot="append">
              <el-button type="primary">
                最近路径快速选择
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="info.genPath = '/'">恢复默认的生成基础路径</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
ruoyi-ui/src/views/tool/gen/index.vue
@@ -166,7 +166,7 @@
</template>
<script>
import { listTable, previewTable, delTable } from "@/api/tool/gen";
import { listTable, previewTable, delTable, genCode } from "@/api/tool/gen";
import importTable from "./importTable";
import { downLoadZip } from "@/utils/zipdownload";
export default {
@@ -241,7 +241,13 @@
        this.msgError("请选择要生成的数据");
        return;
      }
      downLoadZip("/code/gen/batchGenCode?tables=" + tableNames, "ruoyi");
      if(row.genType === "1") {
        genCode(row.tableName).then(response => {
          this.msgSuccess("成功生成到自定义路径:" + row.genPath);
        });
      } else {
        downLoadZip("/tool/gen/batchGenCode?tables=" + tableNames, "ruoyi");
      }
    },
    /** 打开导入表弹窗 */
    openImportTable() {
sql/ry_20200730.sql
File was renamed from sql/ry_20200711.sql
@@ -637,6 +637,8 @@
  business_name     varchar(30)                                comment '生成业务名',
  function_name     varchar(50)                                comment '生成功能名',
  function_author   varchar(50)                                comment '生成功能作者',
  gen_type          char(1)         default '0'                comment '生成代码方式(0zip压缩包 1自定义路径)',
  gen_path          varchar(200)    default '/'                comment '生成路径(不填默认项目路径)',
  options           varchar(1000)                              comment '其它生成选项',
  create_by         varchar(64)     default ''                 comment '创建者',
  create_time         datetime                                   comment '创建时间',