一、SpringBoot支持的模板引擎
1、Thymeleaf(官方推荐)
2、FreeMarker
3、Groovy
4、mustache
SpringBoot为什么不推荐使用JSP呢?
1、JSP对页面的侵入性较强。
2、web容器版本的的管理问题。
二、关于thymeleaf
做到了前后端的完美分离
三、实现MVC
不同的包存放的文件如下图所示:
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、编写controller
/*
* Copyright (c) 2018 solidwang. All Rights Reserved
*/
package com.solid4j.controller;
import com.solid4j.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
/**
* @author: solidwang
* @date:2018/4/19 上午10:35
*/
@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {
@RequestMapping("")
public ModelAndView index(){
List<User> userList = new ArrayList<User>();
User user1 = new User("solidwang", "[email protected]");
User user2 = new User("jobs", "[email protected]");
userList.add(user1);
userList.add(user2);
ModelAndView modelAndView = new ModelAndView("/index");
modelAndView.addObject("userList", userList);
return modelAndView;
}
}
3、模板文件(index.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>learn Resources</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>
<h1>Thymeleaf测试</h1>
<table border="1" cellspacing="1" cellpadding="0">
<tr>
<td>姓名</td>
<td>passport</td>
</tr>
<tr th:each="user : ${userList}">
<td th:text="${user.username}">solidwang</td>
<td th:text="${user.passport}">[email protected]</td>
</tr>
</table>
</div>
</body>
</html>
4、测试结果如下:
5、注意事项
如果要模板页面实时刷新,需要配置application.properties文件,spring.thymeleaf.cache=false,如果依然没有生效,可以对html文件进行一次编译即可。
#thymeleaf start spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 #开发时关闭缓存,不然没法看到实时页面 spring.thymeleaf.cache=false #thymeleaf end