Springboot 集成 Thymeleaf 及常見錯誤

  Thymeleaf模板引擎是springboot中默認配置,與freemarker類似,能夠徹底取代jsp,在springboot中,它的默認路徑是src/main/resources/templates    靜態文件css, js 等文件默認路徑是src/main/resources/static,全部項目中若是沒有這個目錄須要手動加上了css

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

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

引用以後咱們就來測試一下, 在pom.xml中引入依賴以後。你徹底能夠不用配置(也秉承了springboot 約定優於配置)固然你若是須要自定義一些屬性,你能夠在application.properties 中添加配置。spring

測試類@Controller緩存

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

Index,html 頁面以下springboot

<!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 便可看到以下頁面bash

這就成功的集成了Thymeleaf。app

注意:前面也說了,若是你不配置任何屬性依然能夠使用,固然你也能夠本身設置,在配置文件中application.properties 設置相應的屬性jsp

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. 配置完成以後必定要注意路徑地址是否正確,spring-boot

  2. 必定要用@Controller,若是使用@RestController,有可能返回return中的一串字符 測試

  3. 方法前不要加@ResponseBody,加這個註釋至關於@RestController, 返回一串字符串同上

  4. 若是載application.properties重配置屬性,必定要注意是否書寫有誤,不能多空格不然有可能會報以下錯誤:

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

相關文章
相關標籤/搜索