SpringBoot+Thymeleaf实现数据渲染

Thymeleaf简介

1.是什么

Thymeleaf是spring boot推荐使用的模板语法,它可以完全替代 JSP 。 从代码层次上讲:Thymeleaf是一个java类库,它是一个xml/xhtml/html5的模板引擎,可以作为mvc的web应用的view层。

2.优点

开箱即用,它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言; Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。 有网无网的情况下模版页面都可以执行,美工的页面拿来就可以用,相对jsp减少了额外的标签,页面也更加简洁。

3.常用标签

属性 作用 优先级(数字越小,优先级越高) th:text 设置当前元素的文本内容 7 th:value 设置当前元素的value值,类似修改指定html标签属性的还有th:src,th:href 6 th:each 遍历循环元素,和th:text或th:value一起使用 2 th:if 条件判断 3

4.标准表达式语法

语法 含义 ${…} 变量表达式(最常用) @{…} 链接表达式 #{…} 消息表达式 ~{…} 代码块表达式 *{…} 选择变量表达式

SpringBoot+Thymeleaf交互

1.交互代码

在controller中绑定数据,并将数据返回到指定页面

@Controller
@RequestMapping("/mapImage/mapImage")
public class MapImageController extends BaseController
{
          
   
    private String prefix = "mapImage/mapImage";

    @Autowired
    private MapImageController Service MzMapImageService;

    @Autowired
    private CommunitymanageService CommunitymanageService;
    
    @GetMapping()
    @ApiOperation("查询社区")
    public String mapImage(ModelMap model)
    {
          
   
        List<Communitymanage> list = CommunitymanageService.queryCommunityInfo();
        model.put("list", list);
        return prefix + "/mapImage";
    }
}

在mapImage.html页面中,通过thymeleaf的语法将数据渲染

<html lang="zh" xmlns:th="http://www.thymeleaf.org">

<div>
	<p class="contentTitle">社区信息</p>
	<p th:each="list:${list}" th:text="${list.communityname}")></p>
</div>

2.关键代码解析

经验分享 程序员 微信小程序 职场和发展