spring-boot mybatis-plus 集成 + 代码生成器 自定义controller、service、serviceimpl、jsp模板

转自 https://blog.csdn.net/qq_33842795/article/details/80227382

maven依赖

spring boot 和 thymeleaf 结合 controller 返回的控制器路径不能以/ 开头 

否则运行没问题,发布之后就找不到文件

<mybatisplus-spring-boot-starter.version>1.0.4</mybatisplus-spring-boot-starter.version>
<mybatisplus.version>2.1.0</mybatisplus.version>
<!-- mybatis-plus begin -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatisplus-spring-boot-starter</artifactId>
   <version>${mybatisplus-spring-boot-starter.version}</version>
</dependency>
<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus</artifactId>
   <version>${mybatisplus.version}</version>
</dependency>
<!-- 模板引擎 代码生成 -->
<dependency>
   <groupId>org.apache.velocity</groupId>
   <artifactId>velocity</artifactId>
   <version>1.7</version>
</dependency>
<!-- mybatis-plus end -->
myabtis配置类

#MyBatis
mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.dcy.entity
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 0
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
    #序列接口实现类配置
    #key-generator: com.baomidou.springboot.xxx
    #逻辑删除配置
    #logic-delete-value: 0
    #logic-not-delete-value: 1
    #自定义填充策略接口实现
    #meta-object-handler: com.baomidou.springboot.MyMetaObjectHandler
    #自定义SQL注入器
    #sql-injector: com.baomidou.springboot.xxx
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    #不加这个查询数据为空时,字段将被隐藏
call-setters-on-nulls: true

@EnableTransactionManagement
@Configuration
@MapperScan("com.dcy.mapper*")
public class MybatisPlusConfig {

    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
    @Bean
    @Profile({"dev","test"})// 设置 dev test 环境开启
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        /*<!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 -->*/
        //performanceInterceptor.setMaxTime(1000);
        /*<!--SQL是否格式化 默认false-->*/
        //performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }

    /**
     * mybatis-plus分页插件<br>
     * 文档:http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的支持
        return paginationInterceptor;
    }
}
代码生成器  这里控制器用的自己写的模板

public class MpGenerator {

    /**
     * <p>
     * MySQL 生成演示
     * </p>
     */
    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();
        // 选择 freemarker 引擎,默认 Veloctiy
        // mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir("E://test//");
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        //gc.setKotlin(true);//是否生成 kotlin 代码
        gc.setAuthor("董春雨");

        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        // gc.setMapperName("%sDao");
        // gc.setXmlName("%sDao");
        // gc.setServiceName("MP%sService");
        // gc.setServiceImplName("%sServiceDiy");
        // gc.setControllerName("%sAction");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert(){
            // 自定义数据库表字段类型转换【可选】
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                System.out.println("转换类型:" + fieldType);
                // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
                return super.processTypeConvert(fieldType);
            }
        });
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/nxxsba?characterEncoding=utf8");
        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
        //strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(new String[] { "app_certificate" }); // 需要生成的表
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        // 自定义实体父类
        // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
        // 自定义实体,公共字段
        // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
        // 自定义 mapper 父类
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // 自定义 service 父类
        // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        // 自定义 service 实现类父类
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定义 controller 父类
        // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
        // 【实体】是否生成字段常量(默认 false)
        // public static final String ID = "test_id";
         strategy.setEntityColumnConstant(true);
        // 【实体】是否为构建者模型(默认 false)
        // public User setName(String name) {this.name = name; return this;}
        //strategy.setEntityBuilderModel(true);
        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.dcy");
        pc.setController("controller");
        pc.setEntity("model");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】  ${cfg.abc}
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };

        // 自定义 xxListIndex.html 生成
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        focList.add(new FileOutConfig("/templatesMybatis/list.html.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return "E://test//html//" + tableInfo.getEntityName() + "ListIndex.html";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 自定义  xxAdd.html 生成
        focList.add(new FileOutConfig("/templatesMybatis/add.html.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return "E://test//html//" + tableInfo.getEntityName() + "Add.html";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        //  自定义 xxUpdate.html生成
        focList.add(new FileOutConfig("/templatesMybatis/update.html.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return "E://test//html//" + tableInfo.getEntityName() + "Update.html";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 关闭默认 xml 生成,调整生成 至 根目录
        /*TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        mpg.setTemplate(tc);*/

        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
         TemplateConfig tc = new TemplateConfig();
         tc.setController("/templatesMybatis/controller.java.vm");
         tc.setService("/templatesMybatis/service.java.vm");
         tc.setServiceImpl("/templatesMybatis/serviceImpl.java.vm");
         tc.setEntity("/templatesMybatis/entity.java.vm");
         tc.setMapper("/templatesMybatis/mapper.java.vm");
         tc.setXml("/templatesMybatis/mapper.xml.vm");
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
         mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();

        // 打印注入设置【可无】
        System.err.println(mpg.getCfg().getMap().get("abc"));
    }


}
模板文件  自定义controller模板文件   comtroller.java.vm

package ${package.Controller};


#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
import com.alibaba.fastjson.JSON;
import com.dcy.constant.Constant;
import com.dcy.model.BootStrapTable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author ${author}
 * @since ${date}
 */
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("/a#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end
    private final Logger logger = LoggerFactory.getLogger(${table.controllerName}.class);

    @Autowired
    public ${table.serviceName} i${entity}Service;

    /**
     * 跳转列表页面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(method= RequestMethod.GET,value = {"/${table.entityPath}Index"})
    public String index(HttpServletRequest request, Model model) {
        return "${table.entityPath}ListIndex";
    }

    /**
     * 分页查询数据
     *
     * @param bootStrapTable  分页信息
     * @param ${table.entityPath}   查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/get${entity}PageList")
    public Map<String, Object> get${entity}List(BootStrapTable<${entity}> bootStrapTable,${entity} ${table.entityPath}) {
        Map<String,Object> result = new HashMap<String,Object>();
        try {
            result = bootStrapTable.setRows(i${entity}Service.selectPage(bootStrapTable,${table.entityPath}));
        } catch (Exception e) {
            logger.error("get${entity}List -=- {}",e.toString());
            result.put(Constant.BOOTSTAP_TABLE_ROWS, new ArrayList<>());
            result.put(Constant.BOOTSTRAP_TABLE_TOTAL, 0);
        }
        return result;
    }

    /**
     * 跳转添加页面
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(method=RequestMethod.GET,value="/${table.entityPath}Add")
    public String ${table.entityPath}Add(HttpServletRequest request,HttpServletResponse response,Model model) {
        try {


        }catch (Exception ex){
            logger.error("${table.entityPath}Add -=- {}",ex.toString());
        }
        return "${table.entityPath}Add";
    }

    /**
     * 跳转修改页面
     * @param request
     * @param id  实体ID
     * @return
     */
    @RequestMapping(method=RequestMethod.GET,value="/${table.entityPath}Update")
    public String ${table.entityPath}Update(HttpServletRequest request,Long id) {
        try {
            ${entity} ${table.entityPath} = i${entity}Service.selectById(id);
            request.setAttribute("${table.entityPath}",${table.entityPath});
        }catch (Exception ex){
            logger.error("${table.entityPath}Update -=- {}",ex.toString());
        }
        return "${table.entityPath}Upd";
    }

    /**
     * 保存和修改公用的
     * @param ${table.entityPath}  传递的实体
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method=RequestMethod.POST,value="/${table.entityPath}Save")
    public int ${table.entityPath}Save(${entity} ${table.entityPath}) {
        int count = 0;
        try {
            count = i${entity}Service.insertOrUpdate(${table.entityPath}) ? 1 : 0;
        } catch (Exception e) {
            logger.error("${table.entityPath}Save -=- {}",e.toString());
        }
        return count;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method= RequestMethod.POST,value="/${table.entityPath}Delete")
    public int ${table.entityPath}Delete(Long id){
        int count = 0;
        try {
            count = i${entity}Service.deleteById(id) ? 1 : 0;
        }catch (Exception e){
            logger.error("${table.entityPath}Delete -=- {}",e.toString());
        }
        return count;
    }

    /**
     * 批量删除对象
     * @param item 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method= RequestMethod.POST,value="/${table.entityPath}BatchDelete")
    public int deleteBatchIds(String item){
        int count = 0;
        try {
            List<Long> ids = (List<Long>) JSON.parse(item);
            count = i${entity}Service.deleteBatchIds(ids) ? 1 : 0;
        }catch (Exception e){
            logger.error("${table.entityPath}BatchDelete -=- {}",e.toString());
        }
        return count;
    }


}
entity.java.vm

package ${package.Entity};

#if(${activeRecord})
import java.io.Serializable;

#end
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${entityLombokModel})

import com.baomidou.mybatisplus.annotations.Version;

import lombok.Data;
import lombok.experimental.Accessors;
#end

/**
 * <p>
 * $!{table.comment}
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${entityLombokModel})
@Data
@Accessors(chain = true)
#end
#if(${table.convert})
@TableName("${table.name}")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#else
public class ${entity} implements Serializable {
#end

    private static final long serialVersionUID = 1L;

## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})
#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!field.comment" != "")
    /**
     * ${field.comment}
     */
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
   @TableId(value="${field.name}", type= IdType.AUTO)
#elseif(${field.convert})
    @TableId("${field.name}")
#end
## 普通字段
#elseif(${field.fill})
## -----   存在字段填充设置   -----
#if(${field.convert})
   @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
#else
   @TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
   @TableField("${field.name}")
#end
## 乐观锁注解
#if(${versionFieldName}==${field.name})
   @Version
#end
## 逻辑删除注解
#if(${logicDeleteFieldName}==${field.name})
    @TableLogic
#end
   private ${field.propertyType} ${field.propertyName};
#end
## ----------  END 字段循环遍历  ----------

#if(!${entityLombokModel})
#foreach($field in ${table.fields})
#if(${field.propertyType.equals("boolean")})
#set($getprefix="is")
#else
#set($getprefix="get")
#end

   public ${field.propertyType} ${getprefix}${field.capitalName}() {
      return ${field.propertyName};
   }

#if(${entityBuilderModel})
   public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#else
   public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#end
      this.${field.propertyName} = ${field.propertyName};
#if(${entityBuilderModel})
      return this;
#end
   }
#end
#end

#if(${entityColumnConstant})
#foreach($field in ${table.fields})
   public static final String ${field.name.toUpperCase()} = "${field.name}";

#end
#end
#if(${activeRecord})
   @Override
   protected Serializable pkVal() {
#if(${keyPropertyName})
      return this.${keyPropertyName};
#else
      return this.id;
#end
   }

#end
#if(!${entityLombokModel})
   @Override
   public String toString() {
      return "${entity}{" +
#foreach($field in ${table.fields})
#if($!{velocityCount}==1)
         "${field.propertyName}=" + ${field.propertyName} +
#else
         ", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
         "}";
   }
#end
}


mapper.java.vm

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};

/**
 * <p>
  * $!{table.comment} Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}


mapper.xml.vm

<?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="${package.Mapper}.${table.mapperName}">

#if(${enableCache})
   <!-- 开启二级缓存 -->
   <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>

#end
#if(${baseResultMap})
   <!-- 通用查询映射结果 -->
   <resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
#foreach($field in ${table.fields})
#if(${field.keyFlag})##生成主键排在第一位
      <id column="${field.name}" property="${field.propertyName}" />
#end
#end
#foreach($field in ${table.commonFields})##生成公共字段
   <result column="${field.name}" property="${field.propertyName}" />
#end
#foreach($field in ${table.fields})
#if(!${field.keyFlag})##生成普通字段
      <result column="${field.name}" property="${field.propertyName}" />
#end
#end
   </resultMap>

#end
#if(${baseColumnList})
    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
#foreach($field in ${table.commonFields})
   #if(${field.name} == ${field.propertyName})${field.name}#else${field.name} AS ${field.propertyName}#end,
#end
        ${table.fieldNames}
    </sql>
#end
</mapper>

service.java.vm

package ${package.Service};

import com.baomidou.mybatisplus.plugins.Page;
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import com.dcy.model.BootStrapTable;

import java.util.List;

/**
 * <p>
 * $!{table.comment} 服务类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {

    /**
     *  分页查询
     * @param bootStrapTable
     * @param ${table.entityPath}
     * @return
     */
    Page<${entity}> selectPage(BootStrapTable<${entity}> bootStrapTable,${entity} ${table.entityPath});


    List<AppCertificate> selectList(${entity} ${table.entityPath});
}
serviceImpl.java.vm

package ${package.ServiceImpl};

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dcy.model.BootStrapTable;
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.dcy.utils.lang.StringUtils;

import java.util.List;
/**
 * <p>
 * $!{table.comment} 服务实现类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Service
@Transactional
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {


    @Autowired
    private ${table.mapperName} ${table.entityPath}Mapper;

    @Override
    public Page<${entity}> selectPage(BootStrapTable<${entity}> bootStrapTable, ${entity} ${table.entityPath}) {
        EntityWrapper<${entity}> entityWrapper = new EntityWrapper<${entity}>();
        getEntityWrapper(entityWrapper,${table.entityPath});
        return super.selectPage(bootStrapTable.getPagePlus(),entityWrapper);
    }

    @Override
    public List<${entity}> selectList(${entity} ${table.entityPath}) {
        EntityWrapper<${entity}> entityWrapper = new EntityWrapper<${entity}>();
        getEntityWrapper(entityWrapper,${table.entityPath});
        return super.selectList(entityWrapper);
    }

    /**
     *  公共查询条件
     * @param entityWrapper
     * @return
     */
    public EntityWrapper<${entity}> getEntityWrapper(EntityWrapper<${entity}> entityWrapper,${entity} ${table.entityPath}){
        //条件拼接
#foreach($field in ${table.fields})
    #if(!${field.keyFlag})
        if (StringUtils.isNotBlank(${table.entityPath}.${getprefix}${field.capitalName}())){
            entityWrapper.like(${entity}.${field.name.toUpperCase()},${table.entityPath}.${getprefix}${field.capitalName}());
        }
    #end
#end
        return entityWrapper;
    }
}
html 页面代码生成器   前端页面使用super ui  可自行修改 基本语法一样的

add.html.vm   默认都不能为空,生成之后 自行删减

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:replace="common/common_header :: common_header(~{::title},~{},~{})">
    <title>添加首页</title>
</head>
<body style="height: 100%">
<section class="content">
    <div class="row">
        <form class="form-horizontal" id="form-admin-add" onsubmit="return false;">
            <div class="col-md-12">
    #foreach($field in ${table.fields})
        #if(!${field.keyFlag})##生成普通字段
            <div class="form-group">
                <label class="col-sm-2 control-label">${field.comment}</label>
                <div class="col-sm-10">
                    <input id="${field.propertyName}" name="${field.propertyName}" value="" class="form-control"/>
                </div>
            </div>
        #end
    #end

                <div class="form-group">
                    <label class="col-sm-2 control-label"></label>
                    <div class="col-sm-10">
                        <button class="btn btn-primary" id="submit" type="submit"><i class="fa fa-save"></i> 保存
                        </button>
                        <button type="button" class="btn btn-danger" onclick="layer_close();"><i
                                class="fa fa-close"></i> 关闭
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>
</body>
<div th:replace="common/common_foot :: foot"></div>
<script th:src="@{/content/plugins/jquery.validation/jquery.validate.js}"></script>
<script th:src="@{/content/plugins/jquery.validation/validate-methods.js}"></script>
<script th:src="@{/content/common/validation/common.validation.js}"></script>
<script th:inline="javascript">#macro(dian).#end #set($bootstrapTable = '$table')

    $(function () {
        $(".select2").select2({
            placeholder: "请选择",
            width: "100%" //设置下拉框的宽度
        });
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
            checkboxClass: 'icheckbox_square-blue',
            radioClass: 'iradio_square-blue',
            increaseArea: '20%' // optional
        });
        $("#form-admin-add").validate({
            rules: {
            #foreach($field in ${table.fields})
                #if(!${field.keyFlag})##生成普通字段
                    ${field.propertyName}: {
                        required: true
                    }#if(${table.fields.size()} != ${velocityCount}),
                    #end
                #end
            #end
            },
            onkeyup: false,
            submitHandler: function (form) {
                $.ajax({
                    url: getRootPath()+"/a/${table.entityPath}/${table.entityPath}Save",
                    type: "Post",
                    dataType: "json",
                    data: $(form).serialize(),
                    success: function (result) {
                        if (result > 0) {
                            opaler();
                        } else {
                            opalerNO();
                        }
                        //刷新父级页面
                        parent.$bootstrapTable#dian()bootstrapTable('refresh'); //再刷新DT
                    }
                });
            }
        });
    });
</script>
</html>

猜你喜欢

转载自blog.csdn.net/liuxy_236/article/details/86605257