Thymeleaf 是一个流行的模板引擎。它是基于HTML,以HTML标签为基础的模板数据展示。关于Thymeleaf的知识,大家可以移步官网---
https://www.thymeleaf.org
spring boot 官方是非常推荐Thymeleaf作为前端数据展示的。但好像感觉有点像高级版的jsp。感觉好像是专门让后端使用的,因为和前端的vue等相比属实有点距离啊。不过也它有点就是不改变原生的html。建立在原生的html之上。这一点可能是推荐的原因吧。
spring boot 是如何集成thymeleaf呢?
首先 我们需要搭建一个spring boot web项目。
选择Spring Initializr进行spring boot web项目初始化。
勾选spring web 搭建web项目。
选择模板引擎,
这里我们可以看到 spring boot 还支持freemarker等别的模板引擎。
好了 下面我们这个项目就搭建成功了,整体目录结构如下。
我们可以打开pom 文件 看到thymeleaf的依赖。这里是我自己配的版本号。
然后我们就开始进行愉快的开发时间了,话不多说,直接上代码
首先,创建一个controller,
@Controller
@RequestMapping("index")
public class IndexController {
@Autowired
private IUserService iUserService;
@RequestMapping("/list")
public String list(Model model){
User user = new User();
List<String> userNames = new ArrayList<>();
userNames.add("2");
userNames.add("3");
userNames.add("4");
user.setUserNames(userNames);
List<User> users = iUserService.selectList(user);
model.addAttribute("userList",users);
return "index";
}
}
这段代码是一个简单的返回视图的代码,熟悉spring mvc 的话大家应该对这个很熟悉。返回一个index视图,那么问题来了 thymeleaf是如何集成到spring boot里呢,答案马上揭晓;
thymeleaf一般放在resource的templates目录下面,spring boot是默认匹配这个目录下的模板的。打开index.html
圈1的位置就是是必须要加的默认属性。类似我们spring配置文件一样引入的命名空间,thymeleaf也需要引入命名空间。
圈2的地方就是thymeleaf的一些语法了。th:each就是循环遍历。${userList}就是我们在controller写入request域的数据集合。
${}是不是很熟悉,基本前端框架都是这个套路。
好了 让我们启动项目 实验一把。
完美