12.springboot: 使用thymeleaf

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,找了一个小时才发现错误。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容