springboot 之themeleaf的使用

本文介绍了在SpringBoot项目中使用Thymeleaf遇到的问题及解决方案。首先,配置完成后访问接口出现Whitelabel Error Page,通过添加Thymeleaf依赖解决。其次,解决静态资源如CSS引入时出现404的问题,需使用`th:href="@{/css/common.css}"`正确引用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

themeleaf是springboot推荐的页面渲染方式

用法总结暂时参见此博客

问题:1配置好之后访问测试接口报错:

1 controller:

@Controller
@RequestMapping("/demo")
public class SampleController {
    @RequestMapping("/thymeleaf")
    public String thymeleaf(Model model){
        System.out.println("hello");
        model.addAttribute("name","yuanfei");
        return "hello";
    }
}

2 application.properties

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

3 目录截图:

4 启动MainApplication

访问  /demo/thymeleaf

控制台能打印输出 hello,但是页面上却是404,如下图

 

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

5 解决:添加thymeleaf依赖

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

6 启动,查看效果:

7 hello.html 页面代码:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" ></p>
</body>
</html>

问题2:引入静态资源,404

   1 静态资源位置 /static/css/common.css

 

其中 目录结构:common.css

2 html代码:

在idea中能按住ctrl+左键定位到css,但在浏览器中是404

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="/static/css/common.css" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" ></p>

</body>
</html>

3 解决:

由于使用themleaf,那么引入静态资源需要使用 th:href=@{“/css/common.css”}

 

修改后代码及效果:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" th:href="@{/css/common.css}" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" ></p>

</body>
</html>

4 测试访问:ok

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值