Spring boot 集成thymeleaf

Spring boot 集成thymeleaf

背景

自己通过Spring boot集成通义千问实现了一个智能问答系统。Spring boot集成通义千问已经完成,现在需要做一个简单的页面展示,作为一个八年没有摸过前端的后端开发人员,不得不又拿起了html和thymeleaf。

Spring boot 集成web和thymeleaf

Spring boot使用thymeleaf开发前端页面,首先Spring boot得是个web项目,也就是需要集成web功能,然后就需要支持thymeleaf。'

第一步添加依赖
xml 复制代码
       <!--spring boot 对web的支持-->
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--Spring boot 对thymeleaf的支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--Spring boot对lombok的支持-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

Spring boot添加了这两个依赖之后,就具备了thymeleaf的web能力了。

第二步验证thymeleaf

添加完依赖,我需要写个controller实验一下,代码如下

java 复制代码
@Controller
@RequestMapping("demo")
@Slf4j
public class DemoController {

    @RequestMapping("demo")
    public String demo(Model model){
        log.debug("demo ok");
        model.addAttribute("msg","hello thymeleaf");
        return "demo";
    }

}

controller写完之后,我需要写一个html实验一下,html位置在

html页面内容如下

html 复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>测试Thymeleaf</title>
</head>
<body>
  <h1>测试 Thymeleaf模板 </h1>
  <h4>获取数据: <span th:text="${msg}"></span></h4>
</body>
</html>

展示效果

把项目启动后,访问controller的地址,就可以跳转到html页面中,并且带去了controller中的数据

总结

Spring boot集成thymeleaf是比较简单的,虽然现在都是vue和前后端分离的开发模式,不过,有些小项目和小demo用thymeleaf做还是挺不错的。

相关推荐
罗超驿3 分钟前
Java数据结构_栈_算法题
java·数据结构·
谁在黄金彼岸4 分钟前
Spring Boot + WebFlux 全面使用指南
spring boot
希望永不加班8 分钟前
SpringBoot 主启动类解释:@SpringBootApplication 到底做了什么
java·spring boot·后端·spring
一只叫煤球的猫11 分钟前
为什么不用 RAG 做记忆系统 ——压缩上下文与 memory.md 的架构选择
人工智能·后端·ai编程
智能工业品检测-奇妙智能17 分钟前
国产化系统的性价比对比
人工智能·spring boot·后端·openclaw·奇妙智能
编码忘我28 分钟前
java强引用、软引用、弱引用、虚引用
后端
蝎子莱莱爱打怪36 分钟前
别再裸用 Claude Code 了!32 个亲测Skills + 8 个 MCP,开发效率直接拉满!
java·后端·claude
犯困的饭团39 分钟前
4_【自动化引擎Ansible Runner】将 Runner 嵌入灵魂 - Python API 编程
后端
AI茶水间管理员42 分钟前
爆火的OpenClaw到底强在哪?一文了解核心架构(附一条消息的全链路流程)
人工智能·后端
Java水解42 分钟前
Rust异步缓存系统的设计与实现
后端·rust