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

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

引言

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

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

初识

工具

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

你可能用过Freemarker,用过Velocity,但连Thymeleaf都没有据说过,不要慌,咱们一块儿来瞧瞧。git

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

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

SpringBoot支持的模板引擎

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

JSP技术Spring Boot官方是不推荐的,缘由以下:spring

  • 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>

 

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

动起来

构建一个简单的页面

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

 

 
maven依赖更新

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

2、编写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);

    }
}

 

2、编写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:”前缀。

3、运行查看

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

 
运行结果
小结

1、新建带有SpringBoot注解的控制器类
2、在resources目录下建立templates目录
3、 在templates目录下建立.html模板文件
4、使用模板:
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,请自备水,更多干、干、干货等着你

相关文章
相关标签/搜索