目标
用模板来产生动态网页
要点
Thymeleaf模板语法
用Model传数据给模板
代码
1. POM Dependency
增加一个dependency thymeleaf
Group Id: org.springframework.boot
Artifact Id: spring-boot-starter-thymeleaf
Version: 2.0.0.RELEASE
2. Java code
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller; //new in 120
import org.springframework.ui.Model; //new in 120
@Controller
@EnableAutoConfiguration
public class example {
@RequestMapping("/greeting")
public String greeting(
@RequestParam(name="user_name", required = false) String userName, Long id, Model model){ //add Model in 120
model.addAttribute("user_name",userName); //new in 120
model.addAttribute("id",id);//new in 120
return "greeting"; //change in 120
}
public static void main(String args[]) throws Exception{
SpringApplication.run(example.class, args);
}
}
3. 模板文件,新增一个文件src/main/resources/templates/greeting.html

说明
1. 产生动态网页的基础是模板文件。这里用的是Thymeleaf,其主要优点是建立在自然模板的概念上,将其逻辑注入到模板文件中,不会影响模板被用作设计原型。Thymeleaf也从一开始就设计了Web标准 - 特别是HTML5。
2. 在这个例子中,用th:text属性来定义动态文本的内容。注意th:text=后面接用双引号括起来的字符串,变量用${变量名}表示。
3. 用Model把数据从control传到模板
4. 测试URL. http://localhost:8080/greeting?user_name=lishu&id=8
热部署(Hot Swapping)
Hot Swapping是指代码或者模板修改后,不需要stop & relaunch就能生效,这对提高开发调试效率很有帮助。
可以通过安装Spring Devtools来实施Hot Swapping. 在POM里增加依赖:

参考
1. 官网 | Serving Web Content with Spring MVC
2.Spring Boot (三):Thymeleaf 的使用
4. SpringBoot学习:maven使用spring-boot-devtools和springloaded进行热部署
网友评论