1、当我们想把前端页面加入到项目中时,springboot提供了一种前端页面模板,我们在resources文件夹下新建templates文件夹,将HTML5文件写入。
2、在做这个之前,我们需要把thymeleaf的相关依赖加入compile(‘org.springframework.boot:spring-boot-starter-thymeleaf’)我用的gradle,加入相关包即可。
3、然后在配置文件里面加入配置项
#thymeleaf
spring.mvc.static-path-pattern=/static/**
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.cache=false
这里要格外注意spring.thymeleaf.prefix=classpath:/templates/配置项,最好可以粘贴,自己写可能大致路径有问题,导致访问不到页面。
4、注意些return的时候只要写templates文件夹下面的路径就好了,不需要再多写,多写的话,会找不到那个html文件,还有不要在HTML前面加/,对于路径要求非常严格,写错就访问不到,还有就是不要写@RestController,请求接口时会直接返回字符串了,而不是页面,写@Controller即可,不要写@ResponseBody。
@GetMapping("/test")
fun test(model: Model):String{
model.addAttribute("name","ddddd")
return "html/hello"
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
name:<!--/*@thymesVar id="name" type="java.lang.String"*/-->
<span th:text="${name}"></span>
</body>
</html>
这个是我的项目大致结构,可以参考下。