微服务 SpringBoot 2.0(五):整合Thymeleaf模板引擎

我只认识Freemarker、Velocity、JSP,Thymeleaf是啥子 —— Java面试必修

引言

在web开发服务中,重要的莫过于前端界面,一个好的模板引擎能让前端的数据绑定更便捷。对于SEO而言,好的模板引擎也有着足够的优势,所以今天我们要讲解的是Thymeleaf模板引擎

在接下来的文章中,我在末尾处会公布源码,源码将托管在码云上

初识

工具

SpringBoot版本:2.0.4
开发工具:IDEA 2018
Maven:3.3 9
JDK:1.8

你可能用过Freemarker,用过Velocity,但连Thymeleaf都没有听说过,不要慌,我们一起来瞧瞧。

Thymeleaf是一款用于渲染XML、XHTML、HTML5内容的模板引擎。与Velocity,FreeMaker,JSP类似,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎,与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用,是不是猴塞雷啊。

官网:http://www.thymeleaf.org/

SpringBoot支持的模板引擎

  • FreeMarker
  • Groovy
  • Thymeleaf(官方推荐)
  • Mustache

JSP技术Spring Boot官方是不推荐的,原因如下:

  • tomcat只支持war的打包方式,不支持可执行的jar。
  • Jetty 嵌套的容器不支持jsp
  • Undertow
  • 创建自定义error.jsp页面不会覆盖错误处理的默认视图,而应该使用自定义错误页面

Thymeleaf是Spring Boot首要支持的模板引擎,当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。

Thymeleaf优点

  • Spring MVC中@Controller中的方法可以直接返回模板名称,接下来Thymeleaf模板引擎会自动进行渲染
  • 模板中的表达式支持Spring表达式语言(Spring EL)
  • 表单支持,并兼容Spring MVC的数据绑定与验证机制
  • 国际化支持

来观察一段代码

<table>
  <thead>
    <tr>
      <th th:text="#{msgs.headers.name}">Name</th>
      <th th:text="#{msgs.headers.price}">Price</th>
    </tr>
  </thead>
  <tbody>
    <tr th:each="prod: ${allProducts}">
      <td th:text="${prod.name}">Oranges</td>
      <td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td>
    </tr>
  </tbody>
</table>

是不是看起来还是很简单啊,对于开发人员来说,弄懂里面经常使用的几个标签应该就够了

动起来

构建一个简单的页面

一、引入依赖
<!--thymeleaf模板引擎,无需再引入web模块-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
 
maven依赖更新

引入该依赖后会自动引入web依赖,不需要再单独引入web依赖。

二、编写Controller
@Controller
@SpringBootApplication
public class ThymeleafDemo1Application {

    @RequestMapping("/thymeleaf1")
    public ModelAndView thymeleaf1(){

        List<DemoBean> demoBeans = new ArrayList<DemoBean>();
        DemoBean demoBean = new DemoBean();
        demoBean.setName("Java面试必修");
        demoBean.setUrl("www.itmsbx.com");
        demoBeans.add(demoBean);

        demoBean = new DemoBean();
        demoBean.setName("对象无忧");
        demoBean.setUrl("www.51object.com");
        demoBeans.add(demoBean);

        demoBean = new DemoBean();
        demoBean.setName("上海恒骊信息科技");
        demoBean.setUrl("www.henliy.com");
        demoBeans.add(demoBean);

        ModelAndView mav = new ModelAndView("/thymeleaf1");
        mav.addObject("demoBeans",demoBeans);
        mav.addObject("hint","想学习更多面试技巧和知识,请关注公众号:Java面试必修(itmsbx)");
        return mav;
    }

    public static void main(String[] args) {
        SpringApplication.run(ThymeleafDemo1Application.class, args);

    }
}
二、编写html

由于src/main/resources/templates目录是SpringBoot默认指定的映射目录,所以我们再resources下新建templates目录,然后再新建一个thymeleaf1.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 style="text-align: center;margin:0 auto;width: 1000px; ">
    <h2 th:text="${hint}"></h2>
    <table width="100%" border="1" cellspacing="1" cellpadding="0">
        <tr>
            <td>名称</td>
            <td>网址</td>
        </tr>
        <!--/*@thymesVar id="demoBeans" type=""*/-->
        <tr th:each="demo : ${demoBeans}">
            <td th:text="${demo.name}">对象无忧</td>
            <td><a th:href="${demo.url}" target="_blank">点我</a></td>
        </tr>
    </table>
</div>
</body>
</html>

注:上述代码,通过xmlns:th=”[http://www.thymeleaf.org](http://www.thymeleaf.org/)“命令空间,将静态页面转换为动态的视图,需要进行动态处理的元素将使用“th:”前缀。

三、运行查看

执行run方法,打开浏览器访问 http://localhost:8080/thymeleaf1,便可看到如下结果

 
运行结果
小结

一、新建带有SpringBoot注解的控制器类
二、在resources目录下创建templates目录
三、 在templates目录下创建.html模板文件
四、使用模板:
1. 模板文件头部使用 <html xmlns:th="http://www.thymeleaf.org">定义
2. html标签上使用 th:开头标识作为前缀
3. 访问数据使用${}
4.通过 @{}引入web静态文件<link rel="stylesheet" th:href="@{/css/jquery.min.css}"/>(暂未使用)

Thymeleaf的默认参数配置

在properties或yml中可以配置thymeleaf模板解析器属性,下面是部分yml格式的属性

  # THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf:
  #开启模板缓存(默认值:true)
  cache: true

  #Check that the template exists before rendering it.
  check-template: true

  #检查模板位置是否正确(默认值:true)
  check-template-location: true

  #开启MVC Thymeleaf视图解析(默认值:true)
  enabled: true

  #模板编码
  encoding: UTF-8

  #要被排除在解析之外的视图名称列表,用逗号分隔
  spring.thymeleaf.excluded-view-names: 

  #要运用于模板之上的模板模式。另见StandardTemplate-ModeHandlers(默认值:HTML5)
  mode: HTML5

  #在构建URL时添加到视图名称前的前缀(默认值:classpath:/templates/)
  prefix: classpath:/templates/

  #在构建URL时添加到视图名称后的后缀(默认值:.html)
  suffix: .html

  #Thymeleaf模板解析器在解析器链中的顺序。默认情况下,它排第一位。顺序从1开始,
  #只有在定义了额外的TemplateResolver Bean时才需要设置这个属性。
  template-resolver-order:

  #可解析的视图名称列表,用逗号分隔
  spring.thymeleaf.view-names:

总结

关于Thymeleaf模板引擎整合就到这里结束了,大家是不是觉得很简单呢,赶紧动手起来吧。关于更多模板的属性配置我将在Spring Boot 常用配置(properties、yml)这章给大家列出来

源码地址:

https://gitee.com/rjj1/SpringBootNote/tree/master/demo


作者有话说:喜欢的话就请移步Java面试必修网 www.itmsbx.com,请自备水,更多干、干、干货等着你

猜你喜欢

转载自www.cnblogs.com/itmsbx/p/9706000.html
今日推荐