Spring Boot入门教程3-2、使用Spring Boot+Thymeleaf模板引擎开发Web应用

2017-09-05 11612 阅读 Java
所属系列:Spring Boot 入门教程 查看完整系列

一、前言

为什么要使用模板引擎?

在最早的Java Web应用中,最为广泛使用的就是JSP,但是JSP已经是陈旧的技术了,ken.io觉得JSP主要有三个问题:
1、视图代码不能与Java代码完全分离,如果再JSP页面写Java代码维护成本高
2、无法实现页面继承工程,实现模板页的方式蹩脚
3、由于一些已知问题,Spring Boot官方不建议,比如:Spring Boot+JSP打成jar包会有问题

所以,ken.io选择了较为流行的Thymeleaf,本文我们介绍Spring Boot+Thymeleaf的基本使用

本项目构建基于:https://ken.io/note/springboot-course-basic-helloworld

二、操作步骤

1、引入Thymeleaf

在pom.xml文件的dependencies引入


  <dependencies>

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


  </dependencies>

2、创建Thymeleaf模板

  • 创建模板文件夹

在resources文件夹下新建templates文件夹,作为模板根目录
完整路径:src/main/resources/templates

为什么文件夹名字一定要叫templates?
答:Spring Boot就是这么约定的,如果有需要,可以通过配置application.yml修改

spring:
  thymeleaf:
    prefix: classpath:/templates/
  • 在templates新建welcome.html文件

html就是Thymeleaf模板文件后缀,可以通过配置application.yml修改

<!DOCTYPE html>

<html>

<head>
    <title>Welcome - ken.io</title>
</head>

<body>

</body>

</html>

Thymeleaf的语法跟Freemarker差异比较大,因为Thymeleaf所有的语法都依赖于HTML标签。

<p th:text="${message}"></p>

表示将controller返回的message对象以文本形式输出到标签内
相对来说,ken.io更喜欢Fremarker的语法

3、创建Welcome访问入口

在HomeController中增加函数

    @RequestMapping("/")
    @ResponseBody
    String index() {
        return "Hello World!";
    }

    @RequestMapping("/welcome")
    ModelAndView welcome(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("welcome");
        modelAndView.addObject("message","Welcome to Spring Boot & Thymeleaf");
        return modelAndView;
    }

对比index函数,主要发生了以下几个变化:
1、去掉@ResponseBody注解,如果使用该注解,返回结果会直接输出,而不是使用模板引擎渲染
2、使用ModelAndView对象,指定视图名&添加视图对象

对于setViewName函数,如果视图的路径是templates/home/index.ftl
那么使用方式应该是:

modelAndView.setViewName("home/index");

4、启动&访问

启动项目&访问
访问:http://localhost:8080/welcome:

Welcome to Spring Boot & Thymeleaf

三、备注

1、Thymeleaf 常用配置

配置项 说明
spring.thymeleaf.prefix 模板根目录,例如:classpath:/templates/
spring.thymeleaf.cache 是否启用缓存(true false)
spring.thymeleaf.encoding 字符编码
spring.thymeleaf.content-type 内容类型,例如:text/html
spring.thymeleaf.suffix 模板文件后缀,默认为.html

2、附录

  • 本文参考:

https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-template-engines

https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/htmlsingle/#boot-features-jsp-limitations

  • 示例代码地址

https://github.com/ken-io/springboot-course/tree/master/chapter-03-02

  • 相关阅读

Thymeleaf母版页示例:https://ken.io/note/thymeleaf-skill-layout