springboot2.0版使用Thymeleaf及问题

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="'&lt;!--'" 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="'--&gt;'" th:remove="tag"></div>
    </ul>
</div>
</body>
</html>

结果如图:
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌兮~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值