一般Controller返回數據或頁面,今天談一下返回頁面的場景。
一.不使用template
1. controller中定義對應的訪問路由及返回的頁面(使用Controller,不要使用RestController),如:
@GetMapping("/hello") public String test2() { return "hello"; }
2.在SpringBoot配置文件中配置SpringMVC
spring: mvc: view: prefix: / suffix: .html
3.html文件配置路徑。
靜態文件要放在SpringBoot默認的加載路徑下(SpringBoot中的src/main/resources/文件夾對應classpath:):
classpath:/META-INF/resources、classpath:/resources、classpath:/static、classpath:/public
二.使用thymeleaf
1.引入thymeleaf依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.html放在classpath:/templates下。如果html都是放在templates下,SpringBoot的配置文件不要配置,因為默認配置就是這個路徑。
3.如果要自定義需要在SpringBoot配置文件中自定義配置。
spring:
thymeleaf:
suffix: .html
prefix: classpath:/xx/xx/
如果有更深層的路徑,可以在controller的返回值拼上對應的html路徑。
如配置為:prefix: classpath:/templates/,現要返回templates/order/order.html,controller就要返回 "order/order"