AdSense

網頁

2021/5/20

Spring Boot Thymeleaf 簡單範例

Spring Boot搭配Thymeleaf模板簡單範例。

本篇參考官方教學Serving Web Content with Spring MVC

範例環境:

  • Java 8
  • Spring Boot 2.3.2
  • Thymeleaf 3
  • Maven 3

首先使用Eclipse STSIntelliJ IDEA CE建立一個Spring Boot專案。

在專案的pom.xml加入thymeleaf的依賴設定如下。

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

在專案的src/main/resources目錄新增application.properites並設定應用程式context path及port。所以專案在本機的url為http://localhost:8080/demo

application.properites

#context path
server.servlet.context-path=/demo
#port
server.port=8080

建立一個Controller DemoController及處理/hello請求的方法hello(),並導向thymeleaf模板頁面hello.html

DemoController

package com.abc.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class DemoController {

    @GetMapping("/hello")
    public String hello(
            @RequestParam(name = "name", required = false, defaultValue = "World") String name,
            Model model) {
        model.addAttribute("name", name); // set request attribute with key "name"
        return "hello"; // forward to hello.html
    }
}

在專案的src/main/resources/statics目錄建立應用程式的首頁index.html。此頁中的連結hello會導向DemoController.hello()

index.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Index</title>
</head>
<body>
    <p>Go to <a href="hello">hello.html</a></p>
</body>
</html>

在專案的src/main/resources/templates目錄建立thymeleaf模板hello.html,因為Thymeleaf預設讀取此目錄中的模板。Thymeleaf引擎會解析模板中th:text${name}並填入request attribute名稱為"name"的值,即DemoController.hello()model.addAttribute("name", name)name

th:text為thymeleaf標籤屬性,作用為把後面表示式解析結果取代所屬標籤的內容。
${...}為變數表示式(variable expression),使用OGNL語法取得環境中的變數值。

其它表示式參考「Thymeleaf 表示式類型」。

hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Hello Thymeleaf</title>
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'"/>
</body>
</html>


完成以上後啟動專案,在瀏覽器輸入http://localhost:8080/demo進入index.html然後點選hello.html連結即導向hello.html並在頁面顯示Hello, World!。

或直接在瀏覽器輸入http://localhost:8080/demo/hello?name=John,則頁面顯示Hello, John!。


參考github


如果覺得文章有幫助的話還幫忙點個Google廣告,感恩。


2 則留言:

Unknown 提到...

我照著做,除application.properties內的server.servlet.context-path=/demo沒有設定外,其餘都是依樣,結果
http://127.0.0.1:8080/ 不會導向 src/main/resources/statics/index.html
但是 http://127.0.0.1:8080/helo>name=john是OK的
請問,我有可能甚麼地方,沒注意到嗎?

Matt 提到...

@樓上 server.servlet.context-path是設定環境路徑,若您沒設定的話那首頁就是http://127.0.0.1:8080/。
建議您可以了解一下context path,參考https://matthung0807.blogspot.com/2017/11/java-context-path-servlet-path-path-info.html

AdSense