springboot与模版引擎thymeleaf的使用

761 阅读1分钟
  • thymeleadf
    Thymeleaf是一个适用于Web和独立环境的现代服务器端Java模板引擎,能够处理HTML,XML,JavaScript,CSS甚至纯文本。
  1. 目录结构

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

@Controller
@RequestMapping("/demo")
public class SampleController {

    @RequestMapping("/thymeleaf")
    public String thymeleaf(Model model){
        model.addAttribute("name","dongJu");
        return "hello";
    }
}
  1. springboot启动类MainApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainApplication {

    public static void main(String[] args) throws Exception{
        SpringApplication.run(MainApplication.class,args);
    }
}
  1. pom.xml文件依赖
 <!--springBoot整合web依赖-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!--springBoot整合thymeleaf依赖-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <!--添加此依赖用于浏览器解析html文件-->
    <dependency>
      <groupId>net.sourceforge.nekohtml</groupId>
      <artifactId>nekohtml</artifactId>
      <version>1.9.22</version>
    </dependency>

5.application.properties文件配置

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
# 属性配置用于浏览器解析html文件
spring.thymeleaf.content-type=text/html 
# 开发环境中关闭缓存便于测试
spring.thymeleaf.cache=false 
spring.thymeleaf.mode =LEGACYHTML5
  1. hello.html文件
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello!, ' + ${name} " > </p>
</body>
</html>

7.结果展示

  1. 注意事项

笔者在学习过程中碰到了浏览器解析html失败的问题(debug能进入到controller层但页面显示404),后来查阅粗略得知原因是:springboot默认使用Thymeleaf2.X版本,这个版本无法识别html5中常见的自闭合标签。按照笔者的方式配置maven和properties文件即可。

  1. 基础环境搭建(初学者观看) 9.1 使用IDEA构建一个maven项目
  2. 按照1中的目录结构依次创建各个文件。