springboot-thymeleaf
核心技术
- 核心框架:springboot
- 持久层框架:mybatis,mybatis-puls
- 模块引擎:thymeleaf
- 日志管理:LogBack
- 数据库:mysql
- 视图框架:SpringMvc
- API文档:Swagger2
环境搭配
pom.xml
<!--thymeleaf引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql引擎-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Mybatis-Plus启动器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<!--mybatis-plus自动代码生成-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!--添加 模板引擎 依赖 代码生成器-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--knife4j的版本-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.7</version>
</dependency>
yml
spring:
application:
name: school
# 数据源配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/school?userUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
username: root
password: root
# 格式化时区
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
# jackson实体转json时 为NULL不参加序列化的汇总
default-property-inclusion: non_null
thymeleaf:
cache: false #关闭thymeleaf缓存
# 配置端口号
server:
port: 8081
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
# 扫描 Mapper.xml
mapper-locations: classpath*:/mapper/*.xml
# 配置别名
type-aliases-package: com.bdqn.school.entity
# 逻辑删除
global-config:
db-config:
logic-delete-field: deleted # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
框架构造
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.commons.lang3.StringUtils;
import java.util.Scanner;
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 创建代码生成器对象
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(scanner("请输入你的项目路径") + "/src/main/java");
gc.setAuthor("cp");
//生成之后是否打开资源管理器
gc.setOpen(false);
//重新生成时是否覆盖文件
gc.setFileOverride(false);
//%s 为占位符
//mp生成service层代码,默认接口名称第一个字母是有I
gc.setServiceName("%sService");
//设置主键生成策略 自动增长
gc.setIdType(IdType.AUTO);
//设置Date的类型 只使用 java.util.date 代替
gc.setDateType(DateType.ONLY_DATE);
//开启实体属性 Swagger2 注解
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
//使用mysql数据库
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("请输入模块名"));
pc.setParent("com.bdqn");
pc.setController("controller");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setMapper("mapper");
pc.setEntity("entity");
pc.setXml("mapper");
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//设置哪些表需要自动生成
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
//实体类名称驼峰命名
strategy.setNaming(NamingStrategy.underline_to_camel);
//列名名称驼峰命名
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//使用简化getter和setter
strategy.setEntityLombokModel(true);
//设置controller的api风格 使用RestController
strategy.setRestControllerStyle(true);
//驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix("");
mpg.setStrategy(strategy);
mpg.execute();
}
}
config配置文件
Knife4jConfiguration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Knife4jConfiguration {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
//.title("swagger-bootstrap-ui-demo RESTful APIs")
.description("# swagger-bootstrap-ui-demo RESTful APIs")
.termsOfServiceUrl("http://www.xx.com/")
.contact("xx@qq.com")
.version("1.0")
.build())
//分组名称
.groupName("2.X版本")
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.bdqn.school.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
MybatisPlusConfig
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
MyMetaObjectHandler
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
// 起始版本 3.3.0(推荐使用)
this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
// 起始版本 3.3.0(推荐使用)
//在执行增加操作的时候,不仅仅要给createTime赋值,而且要给modifiedTime赋值
this.strictInsertFill(metaObject, "modifiedTime", Date.class, new Date());
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
// 起始版本 3.3.0(推荐)
this.strictUpdateFill(metaObject, "modifiedTime", Date.class, new Date());
}
/**
* 乐观锁
* @return
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
Thymeleaf
创建HTML
<html xmlns:th="http://www.thymeleaf.org">
获取变量值${…}
<p th:text="${name}"></p>
链接表达式: @{…}
<a th:href="@{/student/edit}">edit</a>
判断
<div th:if="${yes}">
<p>hell</p>
</div>
循环
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<!-- 不存在则忽略,显示hello null!(可以通过默认值进行设置)-->
<p th:text="'Hello ' + (${name}?:'admin')">3333</p>
<table>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
</tr>
<tr th:each="emp : ${empList}">
<td th:text="${emp.id}">1</td>
<td th:text="${emp.name}">海</td>
<td th:text="${emp.age}">18</td>
</tr>
</table>
</body>
</html>
常用标签
表单模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="@{/find}">
<select name="tj" >
<option th:value="2">状态</option>
<option th:value="1">未满员</option>
<option th:value="0">已满员</option>
</select>
<input type="text" name="classname"th:value="${classname}">
<button type="submit">查询</button>
</form>
<table border="1">
<tr>
<th>ID</th>
<th>班级名称</th>
<th>限定人数</th>
<th>已有人数</th>
<th>状态</th>
<th colspan="2">操作</th>
</tr>
<tr th:each="li : ${list.getRecords()}">
<td th:text="${li.classId}"></td>
<td th:text="${li.className}"></td>
<td th:text="${li.classEstimateNumber}"></td>
<td th:text="${li.classActualNumber}"></td>
<td th:text="${li.getClassState()==1}?'满员':'未满员'"></td>
<!-- <td><a th:if="${li.getClassState()!=1}">新增</a></td>-->
<!-- #dates.format(li.createtime,'yyyy-MM-dd HH:mm')-->
<td>
<a th:onclick="|javascript:add('${li.classState}','${li.classId}')|">新增</span></a>
</td>
<td>
<a th:onclick="|javascript:xq('${li.classId}')|">详情</a>
</td>
</tr>
<tr>
<td style="text-align: center" colspan="4">
<a th:href="@{/find(pageNum=1,tj=${tj})}">首页</a>|
<a th:if="${list?.hasPrevious()}" th:href="@{/find(pageNum=${list.current}-1,tj=${tj})}">上一页</a>|
<a th:if="${list?.hasNext()}" th:href="@{/find(pageNum=${list.current}+1,tj=${tj})}">下一页</a>
<a th:href="@{/find(pageNum=${list?.pages},tj=${tj})}">末页</a>
第<span th:text="${list?.current}"></span>页/共<span th:text="${list?.pages}"></span>页
</td>
</tr>
</table>
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
<script>
function add(classState,classId) {
if(classState==1){
alert("此班级已满员!")
}else {
location.href='/add?classId='+classId;
}
}
function xq(classId) {
location.href='/xq?classId='+classId;
}
</script>
</body>
</html>
新增模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>编辑</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<style type="text/css">
.form-box{
width: 800px;
height: 500px;
border: 1px solid #DCDFE6;
position: absolute;
top: 50%;
left: 50%;
/*平移*/
transform: translate(-50%,-50%);
padding: 10px;
}
.form-box:hover{
box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}
.form-title{
text-align: center;
}
</style>
</head>
<body>
<div class="form-box">
<h1>新增用户信息</h1>
<form th:action="@{/addatu}" th:method="post">
<!-- <div class="form-group">-->
<!-- <label for="id">学生编号</label>-->
<!-- <input type="text" class="form-control" name="studentId" id="id" readonly placeholder="学生编号">-->
<!-- </div>-->
<div class="form-group">
<label for="name">学生姓名</label>
<input type="text" class="form-control" name="studentName" id="name" placeholder="请输入学生姓名">
</div>
<div class="form-group">
<label for="gender">学生性别</label>
<input type="text" class="form-control" name="studentSex" id="gender" placeholder="请输入学生性别">
</div>
<div class="form-group">
<label for="age">学生出生日期</label>
<input type="date" class="form-control" name="studentTime" id="age" placeholder="请输入学生年龄">
</div>
<div class="form-group">
<label for="classid">学生班级</label>
<input type="text" class="form-control" name="studentClassId" th:value="${classId}" hidden="hidden" id="classid" placeholder="请输入学生班级">
</div>
<button type="submit" class="btn btn-default">提交</button>
<button type="button" onclick="location.href='find'" class="btn btn-default">返回</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
</body>
</html>
常用注解
//逻辑删除
@TableLogic
//新增自动填充
@TableField(fill = FieldFill.INSERT)
//新增修改自动填充
@TableField(fill = FieldFill.INSERT_UPDATE)
//乐观锁
@Version
//格式时间 "yyyy-MM-dd HH:mm:ss"更加详细,但是input 中的 date 只精确到 年月日
@DateTimeFormat(pattern = "yyyy-MM-dd")
//处理与数据库名称不统一
@TableField(value = "student_time")
//网页时间格式显示
//th:text="${#dates.format(li.studentTime,'yyyy-MM-dd HH:mm')}"
//页面重定向
return "redirect:/";
常用注解
//逻辑删除
@TableLogic
//新增自动填充
@TableField(fill = FieldFill.INSERT)
//新增修改自动填充
@TableField(fill = FieldFill.INSERT_UPDATE)
//乐观锁
@Version
//格式时间 "yyyy-MM-dd HH:mm:ss"更加详细,但是input 中的 date 只精确到 年月日
@DateTimeFormat(pattern = "yyyy-MM-dd")
//处理与数据库名称不统一
@TableField(value = "student_time")
//网页时间格式显示
//th:text="${#dates.format(li.studentTime,'yyyy-MM-dd HH:mm')}"
//页面重定向
return "redirect:/";