Springboot 集成 Thymeleaf 及常見錯誤


  Thymeleaf模板引擎是springboot中默認配置,與freemarker相似,可以完全取代jsp,在springboot中,它的默認路徑是src/main/resources/templates    靜態文件css, js 等文件默認路徑是src/main/resources/static,所有項目中如果沒有這個目錄需要手動加上了

首先我們要在pom.xml文件中添加依賴

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

  

引用之后我們就來測試一下, 在pom.xml中引入依賴之后。你完全可以不用配置(也秉承了springboot 約定優於配置)當然你如果需要自定義一些屬性,你可以在application.properties 中添加配置。

測試類@Controller

/**
 * @author pillarzhang
 * @date 2019-06-03
 */
@Controller
public class loginController {
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
}

  

Index,html 頁面如下

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<p style="color:red">hello world</p>
</body>
</html>

  

啟動項目,輸入http://localhost:8081/index 即可看到如下頁面

這就成功的集成了Thymeleaf。

 

注意:前面也說了,如果你不配置任何屬性依然可以使用,當然你也可以自己設置,在配置文件中application.properties 設置相應的屬性

spring.thymeleaf.prefix=classpath:/templates/  設置thymeleaf路徑默認為src/main/resources/templates
spring.thymeleaf.suffix=.html  設置thymeleaf模板后綴
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false  是否開啟緩存默認為true
spring.thymeleaf.mode=LEGACYHTML5  設置thymeleaf嚴格校驗
spring.thymeleaf.encoding=UTF-8    設置編碼

  

  1. 配置完成之后一定要注意路徑地址是否正確,
  2. 一定要用@Controller,如果使用@RestController,有可能返回return中的一串字符
  3. 方法前不要加@ResponseBody,加這個注釋相當於@RestController, 返回一串字符串同上
  4. 如果載application.properties重配置屬性,一定要注意是否書寫有誤,不能多空格否則有可能會報如下錯誤:

     

  至此,springboot集成thymeleaf 就完成了,雖然中間遇到了一些小問題,還好解決了。

 

  如有不當和錯誤之處,請指出,我們一起交流學習,共同進步!謝謝!


免責聲明!

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



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