(8)spring boot使用thymeleaf模板引擎


1. 項目結構



2. 在pom.xml文件中添加thymeleaf依賴


<!-- 添加thymeleaf依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3. 在application.properties中添加thymeleaf配置


#spring.thymeleaf.prefix=classpath:/templates/
#spring.thymeleaf.suffix=.html
#spring.thymeleaf.mode=HTML5
#;charset=<encoding> is added
#spring.thymeleaf.content-type=text/html
#設置thymeleaf的緩存是否關閉,開發階段建議關閉
spring.thymeleaf.cache=false

4. 在src/main/resources/templates/添加hello.html,內容如下:


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
Hello,<span th:text="${nameKey}"></span>
</body>
</html>

5. 編寫TemplatesController


package com.lanhuigu;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 註意: [email protected],[email protected],用的是spring MVC邏輯,
* 在spring MVC中,需要在spring mvc配置的視圖解析器中指定視圖文件位置,spring boot使用
* thymeleaf等於將視圖地址默認在src/main/resources/templates下瞭
*/
@Controller
@RequestMapping("/templates")
public class TemplatesController {

@RequestMapping("/helloHtml")
public String helloHtml(Map<String,Object> map) {
map.put("nameKey", "Thymeleaf");
return "hello";
}
}

6. 編寫啟動類App


package com.lanhuigu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* Hello world!
* 啟動類
*/
@SpringBootApplication
public class App {

public static void main( String[] args ) {
/*System.out.println( "Hello World!" );*/
SpringApplication.run(App.class, args);
}
}

7. 啟動服務訪問,默認端口8080


0 個評論

要回覆文章請先登錄註冊