Springboot支持thymeleaf、freemarker、JSP,但是官方不建議使用JSP,因爲有些功能會受限制,這裏介紹thymeleaf和freemarker。
一、thymeleaf模板
thymeleaf模板的前端界面爲.html格式的文件,可以直接使用瀏覽器進行查看,方便進行樣式等方面的調試。
1、pom依賴添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
通過mvn dependency:tree查看maven關聯樹,發現thymeleaf自動依賴導入web包,因此,無需再導入web包。
2、application屬性配置
查看官方文檔的默認配置介紹如下:
這裏必須要注意的是,開發的時候要關閉模板緩存,不然修改界面文件後無法實時顯示。在application.properties文件中關閉模板緩存:
spring.thymeleaf.cache=false
關閉緩存後,修改html文件,可以直接Ctrl+F9編譯後,顯示最新的修改內容。
3、編寫界面
我的界面hello.html路徑爲:templates/template/hello.html,代碼:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
<!--/*@thymesVar id="name" type="java.lang.String"*/-->
<p th:text="'Hello, ' + ${name}" ></p>
</body>
</html>
4、編寫controller
package com.example.demo.template;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/html")
public class HtmlController {
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("name", "world");
return "template/hello";
}
}
運行訪問,如下:
thymeleaf具體使用參考
http://blog.csdn.net/z719725611/article/details/53908294
二、freemarker模板
1、pom依賴添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
注意:允許thymeleaf和freemarker同時存在
2、application屬性配置
查看官方文檔的默認配置介紹如下:
application.properties文件無需配置,使用默認配置即可
3、編寫界面
我的界面hello.ftl路徑爲:templates/ftl/hello.ftl,代碼:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
message:${message}
</body>
</html>
4、編寫controller
package com.example.demo.template;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
@Controller
@RequestMapping("/ftl")
public class FreemarkerController {
@RequestMapping("/hello")
public String hello(Map<String,Object> map) {
map.put("message", "hello,world");
return "ftl/hello";
}
}
接下來啓動運行即可。
freemarker具體使用參考
http://blog.csdn.net/fhx007/article/details/7902040/
http://blog.csdn.net/tang9140/article/details/39695653