1. 程式人生 > 其它 >Spring boot 學習(一) thymeleaf使用

Spring boot 學習(一) thymeleaf使用

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

引入thyme leaf starter

springboot已經自動配置好了

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.
class) @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class }) @AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class }) public class ThymeleafAutoConfiguration {}

自動配好了thymeleaf

  1. 所有的值都自動配在了
  2. 配置好了模板引擎
  3. 配置好了

  4. 接下來、只需開發頁面就行

  5. 在thymeleaf中配置了
@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";

使用時,需要給html的標頭檔案新增,就會有th的提示內容

xmlns:th="http://www.thymeleaf.org"
package com.sp.Controller;


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

@Controller
public class ThymeleafController {

    @GetMapping("/thymeleaf")
    public String thymeleaf(Model model) {
//         model中放的資料會自動放入請求域中,類似於呼叫了request.setAttribute()
        model.addAttribute("msg","你好!!!!");
        model.addAttribute("link","http://www.baidu.com");  //link,值為http://www.baidu.com
return "successful"; } }   //返回到successful.html頁面

關於@{link} 和${link}

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${msg}">aaaaaaaaaaaaaaaaaaaaaaaa</h1>
<!--修改當前標籤的文字值-->
<h2>
    <a href="" th:href="${link}">連線1:直接訪問${link}裡的地址值訪問連線為:www.baidu.com</a><br>
    <a href="" th:href="@{link}">連線2:拼接@{link}裡的內容和本地伺服器訪問連線為:localhost:8080/world/link</a>

</h2>
</body>
</html>

因為加了字首,所以訪問時需要加上/world 在yaml中添加了配置資訊

server:
  servlet:
    context-path: /world
#      設定伺服器訪問路徑