Spring Boot入門——thymeleaf模板使用


使用步驟

1、在pom.xml中引入thymeleaf

    <!-- thymeleaf插件 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
        <version>1.5.3.RELEASE</version>
    </dependency>    

2、關閉thymeleaf緩存

  創建application.properties資源文件

<!-- 關閉thymeleaf緩存 -->
spring.thymeleaf.cache=false
spring.thymeleaf.check-template-location=true # Check that the templates location exists.
spring.thymeleaf.content-type=text/html # Content-Type value.
spring.thymeleaf.enabled=true # Enable MVC Thymeleaf view resolution.
spring.thymeleaf.encoding=UTF-8 # Template encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

3、編寫thymeleaf模板文件

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"  
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
    <h1 th:inlines="text">Hello</h1>
    <p th:text="${hello}"></p>
</body>
</html>

  :引入xmlns屬性和th標簽必不可少,否則無法正常執行

4、編寫模板請求controller

@Controller
public class ThymeleafController {

    @RequestMapping("index")
    public String indexHtml(Map<String, Object> map){
        map.put("hello", "this is a thymeleaf test");
        return "/NewFile";
    }
    
} 

5、運行結果

  

 6、thymeleaf默認使用2.0.0版本,設置使用3.0版本

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.7</java.version>
    <thymeleaf.version>3.0.6.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
  </properties>

 


免責聲明!

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



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