SpringBoot返回html頁面


一般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"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM