(1)Thymeleaf模板配置:
maven添加支持如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
application.properties添加如下配置:
# 定位模板的目录 spring.mvc.view.prefix=classpath:/templates/ # 给返回的页面添加后缀名 spring.mvc.view.suffix=.html
controller返回页面:
@GetMapping("/index") public String index(){ return "home"; //当浏览器输入/index时,会返回 /templates/home.html页面 }
注意:
spring boot默认开启了静态文件的配置,任何放在static文件夹下的资源都是静态文件。引用静态文件时以/或者前缀不加任何定位符,都会去static文件夹下查找。
Thymeleaf模版默认会使用templatess作为视图文件下
返回纯静态html,时下,比较流行的是前后端分离,前端做路由,前端的开发不使用模板。在这种情况下,使用模板就显得有些臃肿了。
spring boot返回静态页面的方式非常方便,首先需要移除maven的thymeleaf依赖。
非controller模式
这种模式不使用controller,将html和css,js同等对待。这种模式下,html中的如果不加/,则会定位到当前页面。
要看到返回静态页面,只需要将之前的home.html移到static文件夹下。并删除controller和注释掉application.properties中的配置即可。直接在浏览器中输入:http://localhost:8080/index.html。
controller模式
习惯上,我们还是多使用/index方式,而不是index.html方式。
为此还是需要controller。
# 定位页面的目录到static/下
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html
controller当然也是需要的,和之前一样:
@GetMapping("/index")
public String index(){
return "home"; //当浏览器输入/index时,会返回 /static/home.html的页面
}
到这里就可以了。不在需要额外配置。在浏览器中输入:http://localhost:8080/index就可以定位到static下的index.html页面了。