1. 程式人生 > 其它 >springboot--- 七、靜態資源和模板引擎

springboot--- 七、靜態資源和模板引擎

七、靜態資源和模板引擎

7.1、 靜態資源對映

By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext.

7.1.1、預設對映

官方文件告訴我們 Spring Boot 對於靜態資源的對映目錄是 /static , /public , /resources 以及 /META-INF/resource。除此之外其實還映射了 /webjars/**

classpath:/META-INF/resources/webjars

很明顯此處是自動配置實現的,通過檢視原始碼分析這段配置。

而對於網站圖示,Spring Boot 也已經配置了預設位置,可以在看到。

// path: org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
    SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
    mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", // 圖表
            faviconRequestHandler()));
    return mapping;
}

@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
    ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
    requestHandler.setLocations(resolveFaviconLocations());
    return requestHandler;
}

private List<Resource> resolveFaviconLocations() {
    String[] staticLocations = getResourceLocations(
            this.resourceProperties.getStaticLocations());
    List<Resource> locations = new ArrayList<>(staticLocations.length + 1);
    Arrays.stream(staticLocations).map(this.resourceLoader::getResource)
            .forEach(locations::add);
    locations.add(new ClassPathResource("/"));
    return Collections.unmodifiableList(locations);
}

根據 Spring Boot 預設的靜態資源對映規則,可以直接把需要的靜態資源放在響應的資料夾下然後直接引用即可。

而放在 Public 資料夾下的 HTML 頁面也可以直接訪問。

7.1.2、webjars

webjars 的思想是把靜態資源打包到 Jar 包中,然後使用 JVM 構建工具進行管理,如 maven , Gradle 等。

使用 webjars 第一步需要進入依賴,如要使用 bootstrap。

 <!-- Web Jars 靜態資原始檔 -->
 <dependency>
     <groupId>org.webjars</groupId>
     <artifactId>bootstrap</artifactId>
     <version>4.1.3</version>
</dependency>

引入之後檢視 bootstrap 資源。

由於 Springboot 映射了 /webjars/**classpath:/META-INF/resources/webjars. 因此可以直接在檔案中引用 webjars 的靜態資源。

<!-- Bootstrap core CSS -->
<link href="/webjars/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<script src="/webjars/bootstrap/4.1.3/js/bootstrap.min.js"></script>

7.2、模板引擎

Spring MVC 支援各種模版技術,如 Thymeleaf , FreeMarker , JSP 等。而Thyemeleaf 原型即頁面的特性或許更符合 Spring Boot 快速開發的思想而被官方推薦。

Thymeleaf 是適用於 Web 開發的服務端 Java 模版引擎,Thymeleaf 為開發工作流程帶來優雅自然的模版,由於其非侵入的特性,可以讓頁面不管是在靜態原型下還是用作模版引擎時都有良好的頁面展現。

<table>
  <thead>
    <tr>
      <th th:text="#{msgs.headers.name}">Name</th>
      <th th:text="#{msgs.headers.price}">Price</th>
    </tr>
  </thead>
  <tbody>
    <tr th:each="prod: ${allProducts}">
      <td th:text="${prod.name}">Oranges</td>
      <td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td>
    </tr>
  </tbody>
</table>

7.2.1、引入thymeleaf

  • 方式一:建立專案時新增thymeleaf模組。

  • 方式二:引入依賴

<!-- thymeleaf 模版-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

原理是一樣的,為了下載jar包

7.2.2、使用thymeleaf

根據 Spring Boot 自動配置原理,先看一下 Thymeleaf 的配置類,從中可以看出 Thymeleaf 的相關配置。我們可以知道 預設存放目錄是 templates 資料夾,檔案字尾為 .html 且開啟了快取。

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

    private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

    public static final String DEFAULT_PREFIX = "classpath:/templates/";

    public static final String DEFAULT_SUFFIX = ".html";
    /**
     * Whether to enable template caching.
     */
    private boolean cache = true;

為了在開發中編寫模版檔案時不用重啟,可以在配置中關閉快取。

# 關閉模版快取
spring.thymeleaf.cache=false
# 如果需要進行其他的配置,可以參考配置類:ThymeleafProperties
# org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties

controller類:

@Controller
public class TestController {

    @GetMapping("/t1")
    public String test(Model model){
        model.addAttribute("msg","<h1>hellospringbootweb</h1>");
        model.addAttribute("username", Arrays.asList("malongfei","user"));
        return "test";
    }

test.html檔案:

<!DOCTYPE html>
<!-- 要匯入標頭檔案-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
<h1>test</h1>
<div th:text="${msg}">使用text屬性轉義直接輸出字串</div>
<div th:utext="${msg}">使用utext不轉義</div>
<br>
<hr>
<!--遍歷array陣列元素 相當於foreach-->
<h1 th:each="users:${username}" th:text="${users}"></h1>
</body>
</html>

結果:

參考文獻:Springboot 系列(五)Spring Boot web 開發之靜態資源和模版引擎 | 易學教程 (e-learn.cn)