我使用 Spring Initializr 使用 Maven 創建了一個 Spring Boot 演示應用程式(這幾乎是我第一次使用 Spring)。它可以作業,但由于某種原因,除了index.html. 如果我是對的,那是因為 中的配置application.properties,但我只是不知道,我在那里添加了什么。
我的專案的來源結構:
src
main
java
irimi
springbootdemo
SpringBootDemoApplication.java
SpringBootDemoApplicationController.java
resources
static
index.html
templates
test-form.html
test-page.jsp
application.properties
我嘗試在 中添加不同的前綴和后綴application.properties,但沒有任何效果。舉個例子:
spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.html
再次,index.html完美打開。
也許,在這里展示我的依賴也會很好:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
這是一個錯誤頁面:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Jan 15 11:49:12 MSK 2022
There was an unexpected error (type=Not Found, status=404).
No message available
如果我的錯誤真的在application.properties,我放了什么?
uj5u.com熱心網友回復:
帶模板的默認渲染
如果您使用默認的“/resources/templates”來渲染視圖。Spring Boot 僅包括對以下模板引擎的自動配置支持:
- 自由標記
- 時髦的
- 百里香葉
- 速度
例子:
步驟1:
要使用 thymeleaf,您應該使用 gradle 和 maven Gradle 添加依賴項:
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '2.5.4'
或馬文:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.5.4</version>
</dependency>
Step2: 使用屬性檔案添加以下代碼
(Optional)spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
支持 MVC
默認情況下,此處理程式提供來自類路徑上的任何 /static、/public、/resources 和 /META-INF/resources 目錄的靜態內容。由于 src/main/resources 通常默認位于類路徑中,因此我們可以將這些目錄中的任何一個放在那里。
只有靜態檔案夾可用于呈現視圖。您可以使用下面的代碼和屬性檔案進行自定義。默認情況下,Spring Boot 將提供來自名為 /static(或 /public 或 /resources 或 /META-INF/resources)的檔案夾中的靜態內容類路徑或來自 ServletContext 的根。它使用 Spring MVC 中的 ResourceHttpRequestHandler,因此您可以通過添加自己的 WebMvcConfigurerAdapter 并覆寫 addResourceHandlers 方法來修改該行為。
spring.mvc.static-path-pattern=/content/**
spring.web.resources.static-locations=classpath:/files/,classpath:/static-files
更多資訊訪問
https://docs.spring.io/spring-boot/docs/1.1.5.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-static-content
https://www.baeldung.com/spring-mvc-static-resources
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414600.html
標籤:
