使用默认thymeleaf作为视图模板

之前也提及springboot不推荐使用jsp,默认使用thymeleaf。本次的实践案例直接在异常处理的基础上实现。

1、添加thymeleaf依赖,在POM文件中添加如下依赖:
<!-- thymeleaf依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、定义异常页面:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>统一异常处理</title>
</head>
<body>
<h1>Error Handler</h1>
<div th:text="${url}"></div>
<div th:text="${exception.message}"></div>
</body>
</html>
该页面的路径默认为

路径来源参照源码:ThymeleafProperties、ThymeleafTemplateAvailabilityProvider均可

3、在之前的welcome控制类中添加异常处理方法:
/**
* 捕获类内所有的异常
* @param ex
* @return
*/
@ExceptionHandler
public ModelAndView exceptionHandelByThymeleaf(Exception ex,HttpServletRequest req){
ModelAndView mav=new ModelAndView();
mav.setViewName("error");
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
return mav;
}

4、此时系统默认采用的即为thymeleaf模板,一旦出现异常会在2中定义的目录下找到对应error.html页面:


5、那么我们直接访问异常页面,是否也可以呢,首先通过地址 http://localhost:8083/error.html请求:

后发现采用http://localhost:8083/error也是一样的结果

6、其中的报错信息很明显提示请求域中没有对应的exception对象,那么我们调整error.html页面:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>统一异常处理</title>
</head>
<body>
<h1>Error Handler</h1>
<!-- <div th:text="${url}"></div>
<div th:text="${exception.message}"></div> -->
</body>
</html>

此时直接请求发现仍然是上5步中的错误页面,尝试重启服务。

7、直接请求error页面地址:



此次重启服务验证说明此部署路径下的html页面需要重启后方可进行重新加载。与WEB-INF有些差异,之前的jsp页面能够直接修改直接加载。

8、此时我们仍然保留之前配置的jsp视图解析器的bean,尝试jsp页面的跳转:

控制台信息:
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "welcome", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335) ~[thymeleaf-spring4-2.1.5.RELEASE.jar:2.1.5.RELEASE]
说明没有找到之前

如果我们取消本次1中添加的依赖,再次请求:

此次请求成功,那么我们是否真的无法将thymeleaf与jsp视图模板同时使用呢。具体的论证在下一篇实践讲解。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值