SpringBoot 之 靜態資源路徑、顯示首頁、錯誤頁


靜態資源路徑

靜態資源支持放在以下路徑中,訪問優先級從上到下:

classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/  # 默認路徑
classpath:/public/

其中 classpath 為 src/main/resources 目錄。

請求地址為:http://localhost:8080/xx.js

首頁

文件位置:

classpath:/static/favicon.ico
classpath:/templates/index.html

導入 thymeleaf 模板引擎依賴:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
    </dependency>
</dependencies>

定義請求控制器:

@Controller
public class IndexController {
    @RequestMapping({"/", "/index.html"})
    public String index(Model model){
        model.addAttribute("msg", "Hello, Thymeleaf!");
        return "index";
    }
}

加入模板內容顯示首頁:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>index page</title>
</head>
<body>
	<h1>首頁</h1>
	<div th:text="${msg}"></div>
</body>
</html>

錯誤頁

文件位置:

classpath:/templates/error/404.html
classpath:/templates/error/4xx.html
classpath:/templates/error/500.html
classpath:/templates/error/5xx.html


免責聲明!

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



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