themeleaf是springboot推荐的页面渲染方式
用法总结暂时参见此博客
问题:1配置好之后访问测试接口报错:
1 controller:
@Controller
@RequestMapping("/demo")
public class SampleController {
@RequestMapping("/thymeleaf")
public String thymeleaf(Model model){
System.out.println("hello");
model.addAttribute("name","yuanfei");
return "hello";
}
}
2 application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
3 目录截图:
4 启动MainApplication
访问 /demo/thymeleaf
控制台能打印输出 hello,但是页面上却是404,如下图
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
5 解决:添加thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
6 启动,查看效果:
7 hello.html 页面代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" ></p>
</body>
</html>
问题2:引入静态资源,404
1 静态资源位置 /static/css/common.css
其中 目录结构:common.css
2 html代码:
在idea中能按住ctrl+左键定位到css,但在浏览器中是404
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="/static/css/common.css" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" ></p>
</body>
</html>
3 解决:
由于使用themleaf,那么引入静态资源需要使用 th:href=@{“/css/common.css”}
修改后代码及效果:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" th:href="@{/css/common.css}" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" ></p>
</body>
</html>
4 测试访问:ok