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做还是挺不错的。

相关推荐
身如柳絮随风扬6 分钟前
Lambda、方法引用与Stream流完全指南
java·开发语言
程序员飞哥8 分钟前
到底Java 适不适合做 AI 呢?
后端·程序员·全栈
yaoyouzhong12 分钟前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
姗姗的鱼尾喵42 分钟前
Spring/SpringBoot 面试高频(含IOC/AOP/事务)
java·spring boot·面试
Mr_Xuhhh1 小时前
从理论到实践:深入理解算法的时间与空间复杂度
java·开发语言·算法
望眼欲穿的程序猿1 小时前
Vscode Clangd 无法索引 C++17 或者以上标准
java·c++·vscode
带刺的坐椅1 小时前
Spring-AI 与 Solon-AI 深度对比分析报告
java·spring·ai·llm·solon·spring-ai·solon-ai
码事漫谈1 小时前
AI提效,到底能强到什么程度?
前端·后端
IT_陈寒2 小时前
React hooks依赖数组这个坑差点把我埋了
前端·人工智能·后端
爱码少年2 小时前
JAVA获取客户端真实IP地址经典写法与Lambda写法对比
java