SpringBoot整合Thymeleaf
摘自https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
一、创建SpringBoot项目
1、工具创建SpringBoot项目
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-B5PlMovR-1607158920949)(http://m.qpic.cn/psb?/V13x1ZYF1dFQtq/oLBANxXFzwb.gw1bvu.B1DmRIRb24ckYZIe26G.wfks!/b/dFIBAAAAAAAA&bo=qARCAwAAAAADF98!&rf=viewer_4)]
2、pom.xml
引入依赖
<!-- 支持非严格语法的neko -->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
完整版如下:
<dependencies>
<!-- spring web mvc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!-- mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- druid 数据源连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 支持非严格语法的neko -->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3、application.yml
#server config info
server:
port: 8080
spring:
#datasource connect info
datasource:
name: test
type: com.alibaba.druid.pool.DruidDataSource
druid:
url: jdbc:mysql://localhost:3306/maven_ssm?serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
filters: stat
initial-size: 1
min-idle: 1
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20
# mybatis config info
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.qfjy.bean
4、SpringBoot支持Thymeleaf
查看源代码:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0fW3svn1-1607158920955)(http://m.qpic.cn/psb?/V13x1ZYF1dFQtq/sPa36mIuPLXlKFvwx08puneL5xYKA1iAPCzYH1.v9vY!/b/dL8AAAAAAAAA&bo=zAX3AQAAAAADFw0!&rf=viewer_4)]
只需要将开发页面放到Thymeleaf /templates/***.html即可直接访问
5、yml文件中配置Thymeleaf
添加如下自定义配置:(其它默认即可)
cache: false #开发阶段建议关闭缓存
mode: LEGACYHTML5 #用非严格的HTML5 默认是HTML5
如果不想对标签进行严格的验证,使用spring.thymeleaf.mode=LEGCYHTML5去掉验证,同时需要引入NekoHTML包
spring:
thymeleaf:
encoding: UTF-8 #编码规范 默认
cache: false #开发阶段建议关闭缓存
prefix: classpath:/templates/
suffix: .html
mode: LEGACYHTML5 #用非严格的HTML5 默认是HTML5
servlet:
content-type: text/html
6、创建html页面
在 templates 目录下创建 index.html 文件,
修改 html 标签用于引入 thymeleaf 引擎,这样才可以在其他标签里使用 th:* 语法,声明如下:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns:th="http://www.thymeleaf.org">
代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
模版引擎主页的HTML页面
<p th:text="${msg}">信息显示</p>
</body>
</html>
7、controller
@RequestMapping("index")
@Controller
public class IndexController {
@RequestMapping("index")
public String index(Model model){
model.addAttribute("msg","我的第一个信息");
model.addAttribute("author","guoweixin");
return "index"; //基于约定优于配置,默认会到 /templates/ .html
}
}
8、访问请求即可
备注:SpringBoot使用thymeleaf作为视图展示,约定将模板文件放置在src/main/resource/templates目录下,静态资源放置在static目录下
小提示:
templates文件夹,是放置模板文件的,因此需要视图解析器来解析它。所以必须通过服务器内部进行访问,也就是要走控制器–服务–视图解析器这个流程才行。
如果想直接访问html页面,可放置到静态资源下/public….
二、使用Thymeleaf
1、引入 Thymeleaf
修改 html 标签用于引入 thymeleaf 引擎,这样才可以在其他标签里使用 th:* 语法,这是下面语法的前提。
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
三、完成增删改查功能
列表list.html:
<table align="center" width="800px" border="1">
<tr>
<td>编号</td>
<td>用户名</td>
<td>密码</td>
<td>状态</td>
<td>操作</td>
</tr>
<tr th:each="u,i:${list}">
<td th:text="${i.count}">编号</td>
<td th:text="${u.uname}">用户名</td>
<td th:text="${u.upass}">密码</td>
<td >
<div th:switch="${u.status}">
<span th:case="1">有效</span>
<span th:case="0">无效</span>
<span th:case="*">待定</span>
</div>
</td>
<td>
<a href="">添加</a>
<a href="">修改</a>
<a href="view.html" th:href="@{|/user/${u.id}|}">查询</a>
<a href="javascript:del(1)" th:href="|javascript:del('${u.id}')|">删除</a>
</td>
</tr>
</table>
ajax删除:
function del(id){
$.ajax({
type:"post",
// user/del?id=id
url:'[[@{/user/del}]]', //请求的URL要注意用@{}
data:{"id":id},
success:function(msg){
window.location.href="[[@{/user/all}]]" //请求的URL要注意用@{}
}
})
}
统一错误异常处理
@Controller
public class DemoController {
@RequestMapping("info")
public String info(){
System.out.println(1/0);
return "ok";
}
}
可以看到类似下面的报错页面,该页面就是Spring Boot提供的默认error映射页面。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Y25RxzVK-1607158920961)(img\1.png)]
统一异常处理
在resource/templates下添加error.html页面,
springBoot会自动找到该页面作为错误页面,适合内嵌Tomcat或者war方式。
在web/servlert/error下:
ErrorMvcAutoConfiguration类
SpringBoot错误视图提供了以下错误属性:
timestamp:错误发生时间;
status:HTTP状态码;
error:错误原因;
exception:异常的类名;
message:异常消息(如果这个错误是由异常引起的);
errors:BindingResult异常里的各种错误(如果这个错误是由异常引起的);
trace:异常跟踪信息(如果这个错误是由异常引起的);
path:错误发生时请求的URL路径。
状态码具体描述:
https://www.runoob.com/http/http-status-codes.html
SpringBoot使用的前端框架模板不同,页面的名称也有所不同:
实现Spring的View接口的Bean,其ID需要设置为error(由Spring的BeanNameViewResolver所解析);
如果配置了Thymeleaf,则需命名为error.html的Thymeleaf模板;
如果配置了FreeMarker,则需命名为error.ftl的FreeMarker模板;
如果配置了Velocity,则需命名为error.vm的Velocity模板;
如果是用JSP视图,则需命名为error.jsp的JSP模板。
在resource/templates/下添加error.html页面
显示全局显示的错误页面。
(error替换成对应的错误码,404、401、500等,还可以用4xx、5xx等),
springBoot会自动找到该页面作为错误页面,需要将该页面放到 templates/error/4xx.html 下
templates
error.html //默认全局错误页面
error //文件目录
4xx.html //对应错误码页面
5xx.html
ity,则需命名为error.vm的Velocity模板;
如果是用JSP视图,则需命名为error.jsp的JSP模板。
在resource/templates/下添加error.html页面
显示全局显示的错误页面。
(error替换成对应的错误码,404、401、500等,还可以用4xx、5xx等),
springBoot会自动找到该页面作为错误页面,需要将该页面放到 templates/error/4xx.html 下
templates
error.html //默认全局错误页面
error //文件目录
4xx.html //对应错误码页面
5xx.html