Spring Boot+Thymeleaf进行Web开发

在Java Web项目开发中,我们通常使用JSP页面来做客户端界面的开发,但是JSP在内嵌的Servlet容器中运行有一些问题,内嵌的Tomcat、Jetty不支持以jar形式运行JSP,所以Spring Boot中提供了很多模板引擎,包括FreeMarker、Groovy、Thymeleaf、Velocity、Mustache,而Spring Boot推荐使用Thymeleaf,本文也是主要记叙使用Thymeleaf进行Web开发的方法。

什么是模板引擎?

在Web开发中,我们使用模板引擎支持的页面文件类型进行界面开发,并且通常我们可以在页面文件中使用一些动态的标签在实现数据的动态绑定,在程序运行时,模板引擎会按照路径找到我们构建的页面文件并读取,然后处理这些动态绑定的数据,处理完成后返回最终需要展示的页面,最终Web程序将这个页面展示给用户。

在这个过程中,模板引擎的作用可以简单概述:

访问模板 => 按照模板进行数据绑定等操作 => 返回页面

使用Spring Boot+Thymeleaf进行Web开发

本文所使用的Spring Boot版本为2.0.0.Release

一、引入必须的启动器

spring-boot-starter-thymeleaf启动器中已经将Spring MVC的视图解析器配置为Thymeleaf了,所以不需要我们再手动配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
二、构建Thymeleaf需要的模板

Thymeleaf支持直接使用html作为模板,在Maven项目中它默认的模板文件访问路径是src/main/resources/templates。

暂时不清楚Thymeleaf默认的静态文件路径,可以设置Spring的静态资源位置,然后Thymeleaf就可以使用该路径获取到项目的静态资源文件,对于maven工程,此处的classpath对应的是src/main/resources。

spring.resources.static-locations=classpath:/statics/
  • study.html
<!DOCTYPE html>
<!--要使用的Thymeleaf提供的动态标签,需要引入thymeleaf的标签库-->
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">           
        <title>Insert title here</title>
    </head>
    <body>
        hello world.<br>
        <!--访问model中的数据并进行文本拼接-->
        <label>my name is [[${map.name}]]</label><br>
        <!--访问model中的数据,并将当前元素的text初始化为该值-->
        <label th:text="${map.name}"></label>
        <ul>
            <!--循环遍历初始化数据-->
            <li th:each="fruit:${fruits}">
                <span th:text="${fruit}"></span>
            </li>
        </ul>
    </body>
    <!--引入js-->
    <script type="text/javascript" src="/js/study.js"></script>
	<script type="text/javascript" src="/layui-v2.4.3/layui/layui.js"></script>
</html>

还有很多的Thymeleaf标签,可以在网上查询,使用方法都类似。

三、构建Controller
@RequestMapping("/method2")
public ModelAndView studyMethod2(HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("study");//初始化ModelAndView
    Map<String, Object> map = new HashMap<>();
    map.put("name", "marry");
    List<String> arr = new ArrayList<>();
    arr.add("apple");
    arr.add("pear");
    arr.add("banana");
    //向ModelAndView添加数据,这些数据就是模板引擎用来向页面绑定的数据
    mav.addObject("fruits", arr);
    mav.addObject("map", map);
    return mav;
}
四、最终呈现的页面:

在这里插入图片描述

五、禁用模板以及静态资源的缓存,以便调试
spring.thymeleaf.cache=false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值