玩转springboot:thymeleaf模板引擎入门程序

本人花费半年的时间总结的《Java面试指南》已拿腾讯等大厂offer,已开源在github ,欢迎star!

本文GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了6个月总结的一线大厂Java面试总结,本人已拿大厂offer,欢迎star

原文链接:blog.ouyangsihai.cn >> 玩转springboot:thymeleaf模板引擎入门程序

一、前言

常用的模板引擎有:JSP、Velocity、Freemarker、Thymeleaf

但是,Springboot默认是不支持JSP的,默认使用thymeleaf模板引擎。而且,语法更简单,功能更强大,所以这里介绍一下springboot使用Thymeleaf的实例以及遇到的问题。

二、配置application.properties文件


#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/ 
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

spring.thymeleaf.prefix:设置模板的位置
spring.thymeleaf.suffix:设置模板后缀

说明一下,这些配置不是必须的,如果配置了会覆盖默认的。

在开发时建议将spring.thymeleaf.cache设置为false,否则会有缓存,导致页面没法及时看到更新后的效果。
比如你修改了一个文件,已经update到tomcat,但刷新页面还是之前的页面,就是因为缓存引起的。

三、在pom.xml中添加thymeleaf的依赖


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

四、controller测试


/**
 * @author 欧阳思海
 * @date 2018/7/25 9:42
 */
@Controller
public class HelloController {

    @RequestMapping(value = "/test")
    public ModelAndView test(ModelAndView mv) {
        mv.setViewName("/test");
        mv.addObject("title","欢迎使用Thymeleaf!");
        return mv;
    }
}

五、编写thymeleaf模板页面

注意:
spring-boot项目静态文件目录:/src/java/resources/static
spring-boot项目模板文件目录:/src/java/resources/templates
所以test.html文件在/src/java/resources/templates下。


<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello, ' + ${title}" /><br/>

</body>
</html>

六、运行效果

在浏览器输入http://localhost:8080/test

这里写图片描述

这个只是thymeleaf模板的入门程序,更多的看下篇文章,具体讲解thymeleaf模板的语法。

本人花费半年的时间总结的《Java面试指南》已拿腾讯等大厂offer,已开源在github ,欢迎star!

本文GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了6个月总结的一线大厂Java面试总结,本人已拿大厂offer,欢迎star

原文链接:blog.ouyangsihai.cn >> 玩转springboot:thymeleaf模板引擎入门程序


 上一篇
springmvc最简单易懂教程:RESTful支持详解 springmvc最简单易懂教程:RESTful支持详解
RESTful支持1.1 需求RESTful方式商品修改、商品查询。 1.2 添加DispatcherServlet的rest配置<servlet> <servlet-name>springmvc-servlet-re
下一篇 
玩转springboot:入门程序 玩转springboot:入门程序
Spring Boot 入门一、Spring Boot 简介官网英文: Spring Boot makes it easy to create stand-alone, production-grade Spring based Appl