SpringBoot 集成thymeleaf

Thymeleaf介绍

(1)什么是模板技术?

由模板引擎将数据与模板页面合在一起,形成页面
在这里插入图片描述

(2)什么是thymeleaf?

SpringBoot并不推荐使用jsp,但是支持一些模板引擎技术,如:Freemarker,Thymeleaf,Mustache

(3)为什么选择Thymeleaf

可以完全替代jsp

(4)有什么特点

》动静结合,直接访问或者通过服务器访问
浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行
当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示
》开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
》多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
》与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别

springboot整合thymeleaf

SpringBoot会自动为Thymeleaf注册一个视图解析器:ThymeleafViewResolver
默认前缀:classpath:/templates/
默认后缀:.html
如果我们返回视图:users会指向到classpath:/templates/users.html;一般我们无需进行修改,默认即可。

controller

import com.lzq.demo_thymeleaf.domain.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class TestController {

    @RequestMapping(path = "test",method = {RequestMethod.GET,RequestMethod.POST})
    public  String toTest(ModelMap modelMap){
        modelMap.addAttribute("name","lzqlzq");
        List<Person> list = new ArrayList<>();
        for (int i = 0; i <3 ; i++) {
            Person p =new Person();
            p.setUsername("lzq"+i);
            p.setPassword("lzq123"+i);
            list.add(p);
        }
        modelMap.addAttribute("list",list);
        return "test";
    }

}

src/main/resources/templates/test.html
注意:把html 的名称空间,改成:xmlns:th="http://www.thymeleaf.org"会有语法提示

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:text="${name}">
    nihao
</div>
<table>
    <tr>
        <th>用户名</th>
        <th>密码</th>
    </tr>
    <tr th:each="person :${list}">
        <td th:text="${person.username}">lzq</td>
        <td th:text="${person.password}">123</td>
    </tr>
</table>
</body>
</html>

th-指令语法
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值