SpringBoot学习——springboot整合Thymeleaf框架

版权声明:转载请注明来源 https://blog.csdn.net/qq_24598601/article/details/89188553

一、pom 文件引入Thymeleaf

  在原 SpringBoot 项目中的 POM 文件中加入 Thymeleaf 坐标,如果不知道坐标可以从 Maven 中央库查询 http://mvnrepository.com/。当然,如果项目没有使用 Maven ,那就需要导入 Thymeleaf 的Jar ,包括有 thymeleaf-spring5.jar ,和 thymeleaf-extras-java8time.jar

<!-- 引入thymeleaf的依赖包. -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

二、Controller

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
* @Description springboot整合Thymeleaf
* @author 欧阳
* @since 2019年4月10日 下午5:20:49
* @version V1.0
*/
@Controller
public class IndexThymeleafController {
	
	@RequestMapping("/indexThymeleaf")
	public String indexThymeleaf(Model model) {
		
		model.addAttribute("title", "springboot整合Thymeleaf");
		
		return "indexThymeleaf";
	}
}

  注意:使用注解 @Controller 而不要使用 @RestController ,否则会将返回的视图名解析成字符串返回到页面。如果使用 @RestController 注解,则需要返回 ModelAndView

三、application.properties 配置

  在 application.properties 文件中添加下面配置:

### Thymeleaf  Configuration
spring.thymeleaf.cache=true
spring.thymeleaf.enable-spring-el-compiler=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html; charset=utf-8
spring.thymeleaf.check-template-location=true
spring.thymeleaf.check-template=true
spring.thymeleaf.suffix=.ftl

  上面的配置使用 application.yml 文件配置如下:

### Thymeleaf Configuration
spring:
  thymeleaf:
    cache: true
    enable-spring-el-compiler: true
    encoding: UTF-8
    suffix: .html
    check-template-location: true
    check-template: true
    servlet:
      content-type: text/html; charset=utf-8
 

  其实也可以不用添加配置,大部分用到的框架已经默认打开了,这里只是为了演示如果需要配置则按需配置,例如:如果模板需要用到 EL 表达式,则需要将spring.thymeleaf.enable-spring-el-compiler配置为 true(支持)因为spring的 EL 表达式默认是 false(不支持)。

四、HTML 文件

  当使用 Thymeleaf 模板引擎时,默认的模板配置路径为:src/main/resources/templates ,下面是使用默认的模板配置路径新建文件 indexThymeleaf.html ,其的主要代码如下所示。关于 Thymeleaf 的语法请参考文章 SpringBoot学习——Thymeleaf教程详解

<body>
	<h3 th:text="${title}"></h3>
</body>

五、整合后结果

  浏览器访问地址:http://localhost:8080/indexThymeleaf ,后效果图如下:
springboot整合Thymeleaf

猜你喜欢

转载自blog.csdn.net/qq_24598601/article/details/89188553