欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot+Thymeleaf(html5)使用

程序员文章站 2022-05-01 22:05:30
...

SpringBoot+Thymeleaf的使用其实很简单,加依赖,加配置,写html5,然后就可以了,但是其中有遇到一些坑,所以记下来,以备后期查询。

一、在pom.xml里添加依赖

 

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

二、在配置文件(application.yml或者application.properties)里添加配置,此处贴出的是application.yml的代码。

spring:
 thymeleaf:
  #模板的模式,支持 HTML, XML TEXT JAVASCRIPT
  mode: html5
  #编码 可不用配置
  encoding: UTF-8
  #内容类别,可不用配置
  content-type: text/html
  #开发配置为false,避免修改模板还要重启服务器
  cache: false
  #配置模板路径,默认是templates,可以不用配置
  prefix: classpath:/templates/
  suffix: .html

此处有一点需要注意:prefix:classpath:/templates/,如果前缀这里最后有/,那在Controller返回的视图名里就不需要在前面加/。否则会报template might not exist or might not be accessible by any of the configured的错误。详细配置方案如下:

    方法1:

         application.yml最后有/

spring:
prefix: classpath:/templates/

        Controller返回的时前面不需要添加/

@Controller
@RequestMapping("/first")
public class FirstController {
    @RequestMapping("/test")
    public String hello(Model model) {
        String name = "xiaosha";
        model.addAttribute("name", name);
        return "test";
    }
}

方法2:

    application.yml最后没有/

spring:
  prefix: classpath:/templates

        Controller返回的时前面需要添加/ 

@Controller
@RequestMapping("/first")
public class FirstController {
    /**
     * 测试视图解析器
     */
    @RequestMapping("/test")
    public String hello(Model model) {
        String name = "xiaosha";
        model.addAttribute("name", name);
        return "test";
    }

}

 

三、编写html文件、「<html xmlns:th="http://www.thymeleaf.org">」不能少

SpringBoot+Thymeleaf(html5)使用

<!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>3333</p>
<input th:value="${name}"/>
</body>
</html>

四、编辑Controller

切记不可用@RestController、因为它是@[email protected]的合集,若用它,返回的就是JSON数据,而不是view。

@Controller
@RequestMapping("/first")
public class FirstController {
    /**
     * 测试视图解析器
     */
    @RequestMapping("/test")
    public String hello(Model model) {
        String name = "xiaosha";
        model.addAttribute("name", name);
        return "test";
    }

}

五、访问,正常显示

SpringBoot+Thymeleaf(html5)使用