SpringBoot下使用thymeleaf模板访问html,图片报错404无法加载显示问题

今天在做SpringBoot项目开发的时候,因为很久都没用过thymeleaf模板了,现在大部分项目都是前后端分离项目,前端使用VUE等框架,很少使用到后端的thymeleaf模板引擎。使用过程中遇到了通过Controller 找到视图页面后图片找不到问题。

  1. 先是在百度上,百度了一下网友的解决办法,包括配置yml等,但是都没用什么作用。我的thymeleaf yml配置如下:

spring:
thymeleaf:
cache: false
encoding: UTF-8
mode: HTML5
prefix: classpath:/templates/
enabled: true
suffix: .html
content-type: text/html
check-template: true
check-template-location: true

  1. 报错信息如下:
    在这里插入图片描述
  2. 解决办法:
    1.首先确保你的图片的URL引用地址是正确的。
    2.确保你的配置中没有拦截静态资源和图片
    3 .检查target文件,去静态资源文件夹下边查看是否将静态资源文件编译到target对应文件夹下。如果没有,配置pom.xml
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
                <include>**/*.yml</include>
                <include>**/*.properties</include>
                <include>**/*.ico</include>
                <include>**/*.sql</include>
                <include>**/*.css</include>
                <include>**/*.jpg</include>
                <include>**/*.png</include>
                <include>**/*.js</include>
                <include>**/*.html</include>
            </includes>
            <filtering>true</filtering>
        </resource>
使用Spring Boot框架时,我们可以使用Thymeleaf模板引擎来渲染HTML页面Thymeleaf是一种面向服务器的模板引擎,它可以用来构建与Web标准兼容的HTML5页面。 在Spring Boot中,我们首先需要在pom.xml文件中添加Thymeleaf依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 在Spring Boot应用程序中,我们需要配置Thymeleaf的视图解析器。可以在application.properties文件中添加以下属性: ``` spring.thymeleaf.enabled=true spring.thymeleaf.cache=false ``` 可以看到,我们打开了Thymeleaf的缓存机制,以便更方便地测试HTML页面的更改。然后,我们需要在我们的Spring Boot应用程序中创建一个控制器,以便为HTML页面提供服务: ``` @Controller public class MyController { @GetMapping("/") public String index(Model model) { model.addAttribute("message", "Hello, Thymeleaf!"); return "index"; } } ``` 在上面的控制器中,我们使用@GetMapping注释来将应用程序映射到“/”路径。然后,我们将一个消息添加到Model中,以便将其传递给Thymeleaf视图。最后,我们返回视图名称“index”,这将是我们要渲染的HTML页面。 在Thymeleaf模板中,我们可以使用th:text属性来将消息添加到HTML页面中: ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Hello, Thymeleaf</title> </head> <body> <h1 th:text="${message}">Hello, World!</h1> </body> </html> ``` 在上面的示例中,我们使用th:text属性来向页面添加消息。可以看到,我们使用Thymeleaf的EL表达式来获取控制器中传递的消息。 使用了这些步骤后,当我们访问应用程序的根目录时,会渲染index.html页面,并将消息“Hello, Thymeleaf!”添加到页面中。这就是如何在Spring Boot应用程序中使用Thymeleaf模板引擎来渲染HTML页面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值