springboot2.0版引入Thymeleaf模板引擎不需要配置Thymeleaf版本信息只需要引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
其次是在application.yml文件里配置:
spring:
thymeleaf:
mode: HTML5
# 避免页面缓存重启服务器,默认是true
cache: false
使用Thymeleaf注意事项
页面引入头文件:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
注意,Thymeleaf头文件不可以和xmlns:th="http://www.w3.org/1999/xhtml"合在一起使用,二者只能使用一个头文件,否则springboot全局异常拦截器返回界面会失败。
错误用法如下:
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
异常拦截器配置:
package com.lyj.blog.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* @program: springboot-lingxiblog
* @Date: 2020/3/16 22:26
* @Author: 凌兮
* @Description:
*/
@ControllerAdvice
public class ExceptionHandlerController {
//日志跟踪
private final Logger logger=LoggerFactory.getLogger(ExceptionHandlerController.class);
//开启全局异常捕捉
@ExceptionHandler(Exception.class)
public ModelAndView handlerException(HttpServletRequest request,Exception e){
logger.error("Request URL : {}, Exception : {}",request.getRequestURL(),e);
ModelAndView mav=new ModelAndView();
//返回界面信息
mav.addObject("url",request.getRequestURL());
mav.addObject("exception",e);
mav.setViewName("error/error");
return mav;
}
}
返回error界面可以在检查源代码显示异常,代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>错误</title>
</head>
<body>
<h1>错误</h1>
<div>
<div th:utext="'<!--'" th:remove="tag"></div>
<div th:utext="'Failed Request URL:'+${url}" th:remove="tag"></div>
</div>
<div>
<div th:utext="'Exception message:'+${exception.message}" th:remove="tag"></div>
<ul th:remove="tag">
<li th:each="item : ${exception.stackTrace}" th:remove="tag">
<span th:utext="${item}" th:remove="tag"></span>
</li>
<div th:utext="'-->'" th:remove="tag"></div>
</ul>
</div>
</body>
</html>
结果如图: