美文网首页
12.springboot: 使用thymeleaf

12.springboot: 使用thymeleaf

作者: AiPuff | 来源:发表于2017-02-12 23:08 被阅读213次
Paste_Image.png

1、在pom.xml中引入thymeleaf

在pom.xml加入thymeleaf的依赖:

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

2、如何关闭thymeleaf缓存

########################################################
###THYMELEAF (ThymeleafAutoConfiguration)
########################################################
#spring.thymeleaf.prefix=classpath:/templates/
#spring.thymeleaf.suffix=.html
#spring.thymeleaf.mode=HTML5
#spring.thymeleaf.encoding=UTF-8
# ;charset=<encoding> is added
#spring.thymeleaf.content-type=text/html 
# set to false for hot refresh
spring.thymeleaf.cache=false 

3、编写模板文件.html

编写模板文件src/main/resouces/templates/hello.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h1 th:inline="text">Hello.v.2</h1>
        <p th:text="${hello}"></p>
    </body>
</html>

4、编写访问模板文件controller

@Controller
public class TemplateController {
    
    /**
     * 返回html模板.
     */
    @RequestMapping("/helloHtml")
    public String helloHtml(Map<String,Object> map){
        map.put("hello","from TemplateController.helloHtml");
        return "/helloHtml";
    }
    
}

注意:在thymeleaf3.0之前,所有的标签都需要闭合,3.0之后不强制要求闭合

如果页面只返回字符串,并不挑战到指定页面,请检查是否是:@Controller,如果用@RestController来标注就无法正常页面。

假如也用@Controller标注了,可总提示404,即springboot controller能访问到但无法跳转到静态页面,这个时候检查路径是否正确,src/main/resouces/templates,我就不小心写的是sec/main/resouces/templates,找了一个小时才发现错误。。。

相关文章

网友评论

      本文标题:12.springboot: 使用thymeleaf

      本文链接:https://www.haomeiwen.com/subject/jrhzittx.html