之前也提及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视图模板同时使用呢。具体的论证在下一篇实践讲解。