GVKun编程网logo

Thymeleaf无法检测spring-boot项目中的模板(springboot无法访问templates)

8

在这里,我们将给大家分享关于Thymeleaf无法检测spring-boot项目中的模板的知识,让您更了解springboot无法访问templates的本质,同时也会涉及到如何更有效地3.Sprin

在这里,我们将给大家分享关于Thymeleaf无法检测spring-boot项目中的模板的知识,让您更了解springboot无法访问templates的本质,同时也会涉及到如何更有效地3.SpringBoot整合Thymeleaf模板、Spring Boot (4) 静态页面和Thymeleaf模板、spring boot + thymeleaf 项目中html 文件不能使用#{}取值?、spring boot Thymeleaf 模板模板循环输出的问题的内容。

本文目录一览:

Thymeleaf无法检测spring-boot项目中的模板(springboot无法访问templates)

Thymeleaf无法检测spring-boot项目中的模板(springboot无法访问templates)

我的Spring Boot应用程序中具有以下项目结构,我想在其中使用Thymeleaf

projectName    -Gradle-Module1(Spring boot module)        -build        -src            -main            -resources                -templates                    index.html        build.gradle    -Gradle-Module2        ...    build.gradle    ...

但spring-boot找不到我的模板目录,并显示警告

Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)

PS:我正在使用 @EnableAutoConfiguration

在我的控制器代码中,我正在做类似的事情

@Controller@EnableAutoConfigurationpublic class BaseController {    @RequestMapping(value = "/")    public String index() {        return "index.html";    }}

index.html文件只是打印你好世界。

因此通常它应该在src/resources/templates/(我认为是相同的Gradle模块)内部查找,但是以某种方式无法找到它。

当我尝试访问时,localhost:8080 我得到以下错误信息Error resolving template "index.html",template might not exist or might not be accessible by any of the configuredTemplate Resolvers 我缺少什么吗?

任何指针表示赞赏。

谢谢。

答案1

小编典典

您必须按以下方式配置Thymeleaf:

@Configurationpublic class ThymeleafConfig {    @Bean    public SpringResourceTemplateResolver templateResolver() {        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();        templateResolver.setCacheable(false);        templateResolver.setPrefix("classpath:/templates/");        templateResolver.setSuffix(".html");        return templateResolver;    }    @Bean    public SpringTemplateEngine templateEngine() {        SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();        springTemplateEngine.addTemplateResolver(templateResolver());        return springTemplateEngine;    }    @Bean    public ThymeleafViewResolver viewResolver() {        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();        viewResolver.setTemplateEngine(templateEngine());        viewResolver.setOrder(1);        return viewResolver;    }}

Spring doc建议将@EnableAutoConfiguration注释添加到您的主@Configuration类。

似乎您的项目结构错误,典型的包层次结构为:

src  |- main      |- java      |- resources          |- static          |- templates  |- test

在这种情况下,您的模板将位于中src/main/resources/templates,而不是中src/resources/templates/

3.SpringBoot整合Thymeleaf模板

3.SpringBoot整合Thymeleaf模板

一、前言

SrpingBoot支持如JSPThymeleafFreeMarkerMustacheVelocity等各种模板引擎,同时还为开发者提供了自定义模板扩展的支持。

使用嵌入式Servlet容器时,请避免使用JSP,因为使用JSP打包后会存在一些限制。

SpringBoot使用上述模板,默认从src/main/resources/templates下加载。

 

二、thymeleaf介绍

Thymeleaf是现代化服务器端的Java模板引擎,不同与其它几种模板的是Thymeleaf的语法更加接近HTML,并且具有很高的扩展性。详细资料可以浏览官网。

 特点

  • 支持无网络环境下运行,由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。所以它可以让前端小姐姐在浏览器中查看页面的静态效果,又可以让程序员小哥哥在服务端查看带数据的动态页面效果。
  • 开箱即用,为Spring提供方言,可直接套用模板实现JSTL、 OGNL表达式效果,避免每天因套用模板而修改JSTL、 OGNL标签的困扰。同时开发人员可以扩展自定义的方言。
  • SpringBoot官方推荐模板,提供了可选集成模块(spring-boot-starter-thymeleaf),可以快速的实现表单绑定、属性编辑器、国际化等功能。

三、使用

3.1 首先要在pom.xml中添加对thymeleaf模板依赖

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-thymeleaf</artifactId>
4 </dependency>
5 <dependency>
6   <groupId>org.springframework.boot</groupId>
7   <artifactId>spring-boot-starter-web</artifactId>
8 </dependency>

 

3.2 添加完thymeleaf模板依赖的pom.xml文件内容如下

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5 
 6     <groupId>cn.kgc</groupId>
 7     <artifactId>springboot1</artifactId>
 8     <version>0.0.1-SNAPSHOT</version>
 9     <packaging>jar</packaging>
10 
11     <name>springboot1</name>
12     <description>我用的第一个maven工程</description>
13 
14 
15     <!--版本采用的是最新的 2.0.1.RELEASE
16     TODO 开发中请记得版本一定要选择 RELEASE ,因为是稳定版本且BUG少-->
17     <parent>
18         <groupId>org.springframework.boot</groupId>
19         <artifactId>spring-boot-starter-parent</artifactId>
20         <version>2.0.5.RELEASE</version>
21         <relativePath/> <!-- lookup parent from repository -->
22     </parent>
23 
24     <properties>
25         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
26         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
27         <java.version>1.8</java.version>
28     </properties>
29 
30     <dependencies>
31 
32         <!--模块(spring-boot-starter-thymeleaf),可以快速的实现表单绑定、属性编辑器、国际化等功能。-->
33         <dependency>
34             <groupId>org.springframework.boot</groupId>
35             <artifactId>spring-boot-starter-thymeleaf</artifactId>
36         </dependency>
37         <!-- 默认就内嵌了Tomcat 容器,如需要更换容器也极其简单-->
38         <dependency>
39             <groupId>org.springframework.boot</groupId>
40             <artifactId>spring-boot-starter-web</artifactId>
41         </dependency>
42         <!-- 测试包,当我们使用 mvn package 的时候该包并不会被打入,因为它的生命周期只在 test 之内-->
43         <dependency>
44             <groupId>org.springframework.boot</groupId>
45             <artifactId>spring-boot-starter-test</artifactId>
46             <scope>test</scope>
47         </dependency>
48         <!--该依赖可以不添加,但是在 IDEA 和 STS 中不会有属性提示,
49         没有提示的配置就跟你用记事本写代码一样苦逼,出个问题弄哭你去-->
50         <dependency>
51             <groupId>org.springframework.boot</groupId>
52             <artifactId>spring-boot-configuration-processor</artifactId>
53             <optional>true</optional>
54         </dependency>
55     </dependencies>
56 
57     <build>
58         <plugins>
59             <!-- 编译插件 -->
60             <plugin>
61                 <groupId>org.springframework.boot</groupId>
62                 <artifactId>spring-boot-maven-plugin</artifactId>
63             </plugin>
64         </plugins>
65     </build>
66 
67 
68 </project>

 

3.3  创建ThymeleafController.java

创建一个ThymeleafController用来映射HTTP请求与页面的跳转,下面写了两种方式,第一种比较直观和优雅,第二种相对普遍且代码较少,且迎合从struts2跳坑的朋友们…

Spring4.3以后为简化@RequestMapping(method = RequestMethod.XXX)的写法,故而将其做了一层包装,也就是现在的GetMappingPostMappingPutMappingDeleteMappingPatchMapping

 1 package cn.kgc.controller;
 2 import org.springframework.stereotype.Controller;
 3 import org.springframework.web.bind.annotation.GetMapping;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.servlet.ModelAndView;
 6 import javax.servlet.http.HttpServletRequest;
 7 /**
 8  * ThymeleafController用来映射HTTP请求与页面的跳转
 9  */
10 @Controller
11 @RequestMapping
12 public class ThymeleafController {
13     /**
14      * 方法1:返回ModelAndView对象,
15      * 将视图名称封装到该对象的viewName属性中
16      * 将页面所需要的数据封装到该对象的addObject对象中
17      * @return
18      */
19     @GetMapping("/index.do")
20     public ModelAndView index() {
21         ModelAndView view = new ModelAndView();
22         // 设置跳转的视图 默认映射到 src/main/resources/templates/{viewName}.html
23         view.setViewName("index");
24         // 设置属性
25         view.addObject("title", "我的第一个ThymeleafWEB页面");
26         view.addObject("desc", "欢迎进入课工场学习");
27         Teacher teacher=new Teacher(1,"Holly","964918306","北大青鸟-南京中博软件学院-课工场");
28         view.addObject("teacher", teacher);
29         return view;
30     }
31 
32     @GetMapping("/index1")
33     public String index1(HttpServletRequest request) {
34         // TODO 与上面的写法不同,但是结果一致。
35         // 设置属性
36         Teacher teacher=new Teacher(1,"Holly","964918306","北大青鸟-南京中博软件学院-课工场");
37         request.setAttribute("teacher", teacher);
38         request.setAttribute("title", "我的第一个ThymeleafWEB页面");
39         request.setAttribute("desc", "欢迎进入课工场学习");
40         // 返回的 index 默认映射到 src/main/resources/templates/xxxx.html
41         return "index";
42     }
43 
44     class Teacher {
45         private int tid;
46         private String tname;
47         private String qq;
48         private String address;
49 
50         public Teacher() {
51         }
52 
53         public Teacher(int tid, String tname, String qq, String address) {
54             this.tid = tid;
55             this.tname = tname;
56             this.qq = qq;
57             this.address = address;
58         }
59 
60         public int getTid() {
61             return tid;
62         }
63 
64         public void setTid(int tid) {
65             this.tid = tid;
66         }
67 
68         public String getTname() {
69             return tname;
70         }
71 
72         public void setTname(String tname) {
73             this.tname = tname;
74         }
75 
76         public String getQq() {
77             return qq;
78         }
79 
80         public void setQq(String qq) {
81             this.qq = qq;
82         }
83 
84         public String getAddress() {
85             return address;
86         }
87 
88         public void setAddress(String address) {
89             this.address = address;
90         }
91     }
92 }

 

3.4 创建index.html的模板文件

在src/main/resources/templates目录下创建一个名index.html的模板文件,可以看到thymeleaf是通过在标签中添加额外属性动态绑定数据的

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml"
 3       xmlns:th="http://www.thymeleaf.org">
 4 <head>
 5     <meta charset="UTF-8">
 6     <!-- 可以看到 thymeleaf 是通过在标签里添加额外属性来绑定动态数据的 -->
 7     <!--/*@thymesVar id="title" type=""*/-->
 8     <title th:text="${title}">Title</title>
 9     <!-- 在/resources/static/js目录下创建一个hello.js 用如下语法依赖即可-->
10     <script type="text/javascript" th:src="@{/js/hello.js}"></script>
11 </head>
12 <body>
13 <h1 th:text="${desc}">Hello World</h1>
14 <h2>=====作者信息=====</h2>
15 <p th:text="${teacher.tid}"></p>
16 <p th:text="${teacher.tname}"></p>
17 <p th:text="${teacher.qq}"></p>
18 <p th:text="${teacher.address}"></p>
19 </body>
20 </html>

停一下,在你的机器上看到的是报错的情况,如下图所示,但是页面却可以展示数据,这个我们稍加配置就可以解决错误问题

我们在idea中设置一下就ok

 

 

 

 

 

 3.5 静态效果:  运行index.html既可以看到如下的静态效果

 

 

 3.5 动态效果:  

在浏览器输入:http://localhost:9090/springboot1/index.do可以看到渲染后的效果,真正意义上的动静分离了

 

总结:

 Thymeleaf参考手册:https://blog.csdn.net/zrk1000/article/details/72667478

 

参考文章出处:

  • 本文作者:唐亚峰
  • 本文链接:http://blog.battcn.com/2018/04/28/springboot/v2-web-thymeleaf/
  • 版权声明:本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0许可协议。转载请注明出处!

 

Spring Boot (4) 静态页面和Thymeleaf模板

Spring Boot (4) 静态页面和Thymeleaf模板

静态页面

  spring boot项目只有src目录,没有webapp目录,会将静态访问(html/图片等)映射到其自动配置的静态目录,如下

    /static

    /public  

    /resources

    /META-INF/resources

  在resources建立一个static目录和index.html静态文件,访问地址就是 http://localhost:8080/index.html

 

动态页面

  动态页面需要先请求服务器,访问后台应用程序,然后再转向到页面,比如访问jsp,spring boot建议不要使用jsp,默认使用Thymeleaf来做动态页面。

  在pom.xml中添加Thymeleaf组件

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

  TemplatesController.java

@Controller //返回的是页面所以用简单的controller
public class TemplatesController {
    @GetMapping("/templates")
    String test(HttpServletRequest request) {
        request.setAttribute("key", "hello world");
        //跳转到templates/index.html动态页面,templates目录是spring boot 默认配置的动态页面路径
        return "index";
    }
}

  templates/index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<span th:text="${key}"></span>
</body>
</html>

  访问http://localhost:8088/dev/templates

 

这是一个最基本的像页面传递参数,templates标签和jsp标签一样,也可以实现条件判断,循环等各种功能,建议使用静态html+rest代替动态页面。

 

遍历数据:

@GetMapping("/template")
    String template(HttpServletRequest request){
        request.setAttribute("key",bookName + bookAuthor);

        request.setAttribute("list", Arrays.asList("a","b","c","d","e"));

        return "index";
    }
遍历
<table>
    <tr th:each="item : ${list}">
        <td th:text="${item}"></td>
    </tr>
</table>

 

数据判断:

<tr th:each="item : ${list}">
        <td th:text="${item}" th:if="${item == ''a''}"></td>
    </tr>

等于a才显示出来

<table th:if="${list != null && list.size() > 0}">

有数据才遍历

 

在javascript中访问model数据

<script>
    var a = ''[[${key}]]'';
    alert(a);
</script>

 

spring boot + thymeleaf 项目中html 文件不能使用#{}取值?

spring boot + thymeleaf 项目中html 文件不能使用#{}取值?

spring boot + thymeleaf 项目中html 文件不能使用#{}取值?idea报错不能这样取么?有大佬知道为什么?

spring boot Thymeleaf 模板模板循环输出的问题

spring boot Thymeleaf 模板模板循环输出的问题

 

有人知道 这个便签应该怎么写么。。。第二行数据输出的时候没有换行 应该怎么改!求帮助!!!

关于Thymeleaf无法检测spring-boot项目中的模板springboot无法访问templates的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于3.SpringBoot整合Thymeleaf模板、Spring Boot (4) 静态页面和Thymeleaf模板、spring boot + thymeleaf 项目中html 文件不能使用#{}取值?、spring boot Thymeleaf 模板模板循环输出的问题等相关内容,可以在本站寻找。

本文标签: