基于 Spring Boot 的 Web 三大核心交互案例精讲

基于 Spring Boot 的 Web 三大核心交互案例精讲
—知识点专栏——JavaEE专栏—


作为 Spring Boot 初学者,理解后端接口的编写和前端页面的交互至关重要。本文将通过三个经典的 Web 案例——表单提交、AJAX 登录与状态管理、以及 JSON 数据交互——带您掌握前后端联调的核心技巧和 Spring Boot 的关键注解。

1. 案例一:表单提交与参数绑定(计算求和)

本案例展示最基础、最传统的 Web 交互方式:HTML 表单提交。

1.1 后端代码:CalcController.java

使用 @RestController 简化接口编写,并通过方法参数接收表单数据。

packagecn.overthinker.springboot;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RequestMapping("/calc")@RestControllerpublicclassCalcController{/** * 求和接口:通过方法参数名自动接收前端表单提交的 num1 和 num2 */@RequestMapping("/sum")publicStringsum(Integer num1,Integer num2){// 使用 Integer 包装类进行非空判断,避免空指针异常if(num1 ==null|| num2 ==null){return"请求非法:请输入两个数字!";}// 计算并返回结果return"计算结果为:"+(num1 + num2);}}

1.2 前端代码:calc.html

在这里插入图片描述


在这里插入图片描述
📋 HTML 代码
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>简单求和计算器</title><style>body{font-family: sans-serif;background-color: #f4f7f6;display: flex;justify-content: center;align-items: center;min-height: 100vh;margin: 0;}.calculator-container{background-color: #ffffff;padding: 40px;border-radius: 12px;box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);width: 300px;text-align: center;}h1{color: #333;margin-bottom: 30px;font-size: 24px;border-bottom: 2px solid #5cb85c;display: inline-block;padding-bottom: 5px;}input[type="text"]{width: 100%;padding: 10px;margin-bottom: 10px;border: 1px solid #ccc;border-radius: 6px;box-sizing: border-box;}input[type="submit"]{background-color: #5cb85c;color: white;padding: 12px 20px;border: none;border-radius: 6px;cursor: pointer;font-size: 16px;margin-top: 20px;width: 100%;transition: background-color 0.3s ease;}input[type="submit"]:hover{background-color: #4cae4c;}</style></head><body><divclass="calculator-container"><h1>简单求和计算器</h1><formaction="/calc/sum"method="post"> 数字1:<inputname="num1"type="text"placeholder="请输入数字1"><br> 数字2:<inputname="num2"type="text"placeholder="请输入数字2"><br><inputtype="submit"value=" 点击相加 "></form></div></body></html>

1.3 联调重点解析:参数绑定

  • 前端 Form 的 name 属性:前端 <input name="num1"> 中的 name 必须与后端方法的参数名 Integer num1完全一致
  • 后端自动类型转换:Spring Boot 会自动将 HTTP 请求中的字符串参数转换为 Java 方法所需的 Integer 类型。

2. 案例二:AJAX 异步交互与 Session 状态管理(用户登录)

本案例引入 AJAX 实现无刷新登录,并利用 Session 在服务器端保存用户状态。

2.1 后端代码:UserController.javaPerson.java

UserController.java (核心逻辑)
packagecn.overthinker.springboot;importjakarta.servlet.http.HttpServletRequest;importjakarta.servlet.http.HttpSession;importorg.springframework.util.StringUtils;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RequestMapping("/user")@RestControllerpublicclassUserController{/** * 登录接口:使用 HttpSession 存储用户信息 */@PostMapping("/login")publicbooleanlogin(String userName,String password,HttpSession session){if(!StringUtils.hasLength(userName)||!StringUtils.hasLength(password)){returnfalse;}// 硬编码校验(实际项目应查询数据库)if("admin".equals(userName)&&"123456".equals(password)){// **核心知识点:登录成功后,将用户名存入 Session** session.setAttribute("loginUser", userName);returntrue;}returnfalse;}/** * 获取当前登录用户接口:从 Session 中读取用户信息 */@GetMapping("/getLoginUser")publicStringgetLoginUser(HttpServletRequest request){// request.getSession(false):如果 Session 不存在,则不创建HttpSession session = request.getSession(false);if(session !=null){String loginUser =(String) session.getAttribute("loginUser");return loginUser;}return"";}}
Person.java (实体类)

虽然未直接用于登录,但作为 JavaBean 演示参数绑定基础。

packagecn.overthinker.springboot;// 略:包含 name, password, age 属性及其 Getter/Setter 和 toString 方法publicclassPerson{// ... 属性、Getter/Setter、toString ...}

2.2 前端代码:login.htmlindex.html

在这里插入图片描述


在这里插入图片描述

使用 jQuery AJAX 进行异步登录,用户体验更好。

login.html (登录页面)
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>用户登录</title><style>body{font-family: sans-serif;background-color: #e8eff1;display: flex;justify-content: center;align-items: center;min-height: 100vh;margin: 0;}.login-box{background-color: #fff;padding: 40px;border-radius: 8px;box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);width: 280px;text-align: center;}h1{color: #3c8dbc;margin-bottom: 25px;}input[type="text"], input[type="password"]{width: 100%;padding: 10px;margin-bottom: 15px;border: 1px solid #ccc;border-radius: 4px;box-sizing: border-box;}input[type="button"]{background-color: #3c8dbc;color: white;padding: 10px 15px;border: none;border-radius: 4px;cursor: pointer;font-size: 16px;width: 100%;transition: background-color 0.3s;}input[type="button"]:hover{background-color: #367fa9;}</style></head><body><divclass="login-box"><h1>用户登录</h1> 用户名:<inputname="userName"type="text"id="userName"placeholder="请输入用户名"><br> 密码:<inputname="password"type="password"id="password"placeholder="请输入密码"><br><inputtype="button"value="登录"onclick="login()"></div><scriptsrc="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script><script>functionlogin(){ $.ajax({ url:"/user/login", type:"post",// 核心联调:通过 AJAX 传递参数 data:{ userName:$("#userName").val(), password:$("#password").val()},success:function(result){if(result){// 登录成功,跳转到首页 location.href ="/index.html";}else{alert("用户名或密码错误");}}});}</script></body></html>
index.html (首页 - 获取登录信息)
<!doctypehtml><htmllang="en"><head><metacharset="UTF-8"><title>用户登录首页</title><style>body{font-family: sans-serif;background-color: #f0f4f7;padding: 50px;}.welcome{font-size: 24px;color: #333;}#loginUser{color: #d9534f;font-weight: bold;}</style></head><body><divclass="welcome">欢迎回来,登录人: <spanid="loginUser"></span></div><scriptsrc="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script><script>// 页面加载后立即发起 AJAX 请求获取 Session 中的登录信息 $.ajax({ url:"user/getLoginUser", type:"get",success:function(userName){// 将后端返回的用户名显示在页面上$("#loginUser").text(userName ||"(未登录)");}});</script></body></html>

2.3 联调重点解析:AJAX 与 Session

  • AJAX (Asynchronous JavaScript and XML):允许前端在不刷新页面的情况下,与后端进行数据交换。在 login.html 中,我们使用 jQuery 的 $.ajax 实现异步请求。
  • Session 机制:Session 是服务器端用来存储用户状态信息的机制。
    • 当用户登录成功后,session.setAttribute("loginUser", userName); 在服务器上创建或关联一个 Session,并存入数据。
    • 浏览器通过 Cookie 自动携带一个 Session ID 给服务器。
    • index.html 请求 /user/getLoginUser 时,服务器通过浏览器传来的 Session ID 找到对应的 Session,从而取出存储的 loginUser 信息,实现了状态保持。

3. 案例三:JSON 数据传输与 RESTful 接口(留言板)

本案例是现代 Web 开发最常用的方式:前后端通过 JSON 格式进行数据交互,后端使用 RESTful 风格的接口。

3.1 后端代码:MessageController.javaMesseageInfo.java

MessageController.java (核心逻辑)
packagecn.overthinker.springboot;importorg.springframework.util.StringUtils;importorg.springframework.web.bind.annotation.*;importjava.util.ArrayList;importjava.util.List;@RequestMapping("/Message")@RestControllerpublicclassMessageController{// 存储留言的列表(模拟数据库存储)privateList<MesseageInfo> messeageInfoList =newArrayList<>();/** * 发布留言接口:使用 @RequestBody 接收 JSON 数据 */@PostMapping("/publish")publicBooleanpublish(@RequestBodyMesseageInfo messeageInfo){// 参数校验if(!StringUtils.hasLength(messeageInfo.getFrom())||!StringUtils.hasLength(messeageInfo.getTo())||!StringUtils.hasLength(messeageInfo.getMessage())){returnfalse;} messeageInfoList.add(messeageInfo);returntrue;}/** * 获取留言列表接口:返回 JSON 数组 */@GetMapping("/getList")publicList<MesseageInfo>getList(){return messeageInfoList;}}
MesseageInfo.java (数据传输对象 DTO)

使用 Lombok 的 @Data 注解自动生成 Getter/Setter。

packagecn.overthinker.springboot;importlombok.Data;@Data// Lombok 注解,自动生成 Getter/Setter, toString, equals等方法publicclassMesseageInfo{privateString from;privateStringto;privateString message;// 注意:前端传的字段名是 message}

3.2 前端代码:message.html

在这里插入图片描述

前端使用 AJAX 发送 JSON 格式的数据。

📋 HTML 代码
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>留言板</title><style>body{font-family: sans-serif;background-color: #f0f7f4;padding: 20px;}.container{width: 400px;margin: 20px auto;background-color: #fff;padding: 25px;border-radius: 10px;box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);text-align: center;}h1{color: #387063;margin-bottom: 5px;}.grey{color: #888;margin-bottom: 20px;}.row{display: flex;justify-content: space-between;align-items: center;height: 40px;margin-bottom: 10px;}.row span{width: 70px;text-align: left;color: #555;font-weight: bold;}.row input{flex-grow: 1;height: 35px;padding: 5px 10px;border: 1px solid #ddd;border-radius: 4px;}#submit{width: 100%;height: 45px;background-color: #387063;color: white;border: none;border-radius: 5px;margin-top: 20px;font-size: 18px;cursor: pointer;transition: background-color 0.3s;}#submit:hover{background-color: #2b574d;}.message-list div{text-align: left;padding: 8px 0;border-bottom: 1px dashed #eee;color: #333;}</style></head><body><divclass="container"><h1>留言板</h1><pclass="grey">输入后点击提交,信息将显示在下方</p><divclass="row"><span>谁:</span><inputtype="text"id="from"placeholder="你的名字"></div><divclass="row"><span>对谁:</span><inputtype="text"id="to"placeholder="你想对谁说"></div><divclass="row"><span>说什么:</span><inputtype="text"id="say"placeholder="你的留言内容"></div><inputtype="button"value="提交留言"id="submit"onclick="submit()"><divclass="message-list"></div></div><scriptsrc="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script><script>// 页面加载时自动获取并展示所有留言functionloadMessages(){ $.ajax({ type:"get", url:"/Message/getList",success:function(messages){$(".message-list").empty();// 清空旧列表for(let msg of messages){let divE ="<div>"+ msg.from +" 对 "+ msg.to +" 说: "+ msg.message +"</div>";$(".message-list").append(divE);}}});}// 初始化加载loadMessages();functionsubmit(){varfrom=$('#from').val();var to =$('#to').val();var say =$('#say').val();if(from==''|| to ==''|| say ==''){return;}// 核心联调:发送 JSON 数据 $.ajax({ type:"post", url:"/Message/publish",// 1. 设置 Content-Type 为 application/json contentType:"application/json",// 2. 使用 JSON.stringify 将 JS 对象转换为 JSON 字符串 data:JSON.stringify({from:from, to: to,// 注意:前端字段名为 message,与后端 DTO 匹配 message: say }),success:function(result){if(result){// 提交成功后重新加载列表loadMessages();// 清空输入框$('#from').val("");$('#to').val("");$('#say').val("");}else{alert("添加留言失败,请检查输入");}}});}</script></body></html>

3.3 联调重点解析:@RequestBody 与 JSON

  • @RequestBody:这是 Spring Boot 接收 JSON 数据的关键注解。它告诉 Spring MVC:请将 HTTP 请求体(Request Body)中的 JSON 字符串解析,并自动映射到方法参数 MesseageInfo messeageInfo 对象中。
  • 前端 contentType: "application/json":前端必须设置此头信息,告诉服务器发送的是 JSON 格式数据。
  • 前端 JSON.stringify(...):JavaScript 的内置方法,用于将一个 JS 对象(如 {from: 'A', to: 'B', message: 'Hello'})转换为后端能够识别的 JSON 字符串。
  • JSON 字段匹配:前端 JSON 中的键(Key)必须与后端 DTO (MesseageInfo) 中的属性名(Field Name)保持一致(例如:message 对应 private String message;)。

4. 总结:前后端联调模式对比

联调模式案例核心机制后端注解/参数接收优点缺点
Form 表单提交求和计算器浏览器直接跳转/刷新页面方法参数名匹配简单、无需 JavaScript用户体验差、无法精细控制
AJAX (Query String)登录系统 (GET/POST)异步通信(无刷新)方法参数名匹配用户体验好、可局部更新仅适用于少量简单数据
AJAX (JSON)留言板异步通信(无刷新)@RequestBody 接收 DTO传输复杂结构数据、最常用需要配置 Content-TypeJSON.stringify

若你在学习过程中遇到其他问题,或有好的学习经验分享,欢迎在评论区留言!一起交流进步🌟

在这里插入图片描述

Read more

Docker 部署 OpenClaw 踩坑实录:Web UI 访问、飞书配对及自定义模型配置

最近在使用 Docker 部署 OpenClaw 时遇到了一些典型的环境与配置问题。为了方便大家排查,我将这几个核心问题的表现、解决思路以及如何接入公司自己配置的大模型节点进行了梳理。 一、问题一:安装成功但 Web UI 无法访问 1. 现象描述 * 终端提示安装成功,但在浏览器中访问http://127.0.0.1:18789 时,页面提示连接被重置。 * 使用具体的局域网 IP(如192.168.5.30:18789)访问时,同样提示无法连接或无法访问此网站。 2. 原因分析 * 在排除了代理服务器和系统防火墙的干扰后,根本原因在于 OpenClaw 核心网关的跨域访问(CORS)安全机制。 * 系统默认包含白名单配置,它的作用是告诉 OpenClaw 的核心网关:“只有从这些特定的网址(域名或IP)打开的控制台网页,才被允许连接我并下发控制指令”

Qwen3-32B镜像免配置实战:Clawdbot Web平台CPU/GPU混合部署指南

Qwen3-32B镜像免配置实战:Clawdbot Web平台CPU/GPU混合部署指南 1. 为什么你需要这个部署方案 你是不是也遇到过这样的问题:想快速用上Qwen3-32B这样强大的大模型,但一看到“编译环境”“CUDA版本”“模型分片”“显存分配”这些词就头皮发麻?更别说还要自己搭Web界面、配反向代理、调端口转发——光是看文档就花掉半天,真正跑起来可能要折腾两三天。 这次我们不走老路。Clawdbot Web平台提供了一套真正意义上的免配置混合部署方案:它能自动识别你机器上的CPU和GPU资源,智能分配Qwen3-32B的推理负载,不需要你手动改config、不用写Docker Compose、也不用查NVIDIA驱动兼容表。你只需要一条命令,5分钟内就能在浏览器里和320亿参数的大模型对话。 这不是概念演示,而是已在实际业务中稳定运行的生产级方案。背后的关键在于——它把Ollama的轻量API服务、Clawdbot的前端交互层、以及一个精巧的内部代理网关,打包成了一个开箱即用的镜像。你甚至不需要知道Ollama是什么,只要会复制粘贴命令,就能拥有自己的私有Qwen

目前最流行的 Rust Web 框架是什么?全面对比与选型建议(2026最新版)

Rust 这几年在后端领域的热度持续攀升,从系统编程语言逐渐扩展到 Web 开发领域。很多开发者在学习或选型时都会问: 目前最流行的 Rust Web 框架到底是谁? 今天我们就从生态成熟度、GitHub Star 数量、社区活跃度、性能表现和企业使用情况几个维度,系统分析当前主流 Rust Web 框架。 一、当前最流行的 Rust Web 框架 综合社区活跃度和实际使用情况来看: 目前最流行的 Rust Web 框架是 —— Axum 当然,Actix Web 仍然拥有大量历史用户,而 Rocket 在易用性方面也非常出色。 下面逐个介绍。 🥇 一线框架:Axum(当前热度最高) Axum 是什么? Axum 是基于 Tokio 异步运行时和 Tower 生态构建的现代

从零开始:在本地搭建一个带知识库的 AI 助手(Ollama + Open WebUI)

从零开始:在本地搭建一个带知识库的 AI 助手(Ollama + Open WebUI)

一文讲清楚:要选哪些工具、需要什么环境、整体架构长什么样,以及一步步实现到能用的程度。 一、为什么要在本地搭一个 AI 助手? 过去一年,大模型从“新奇玩意儿”迅速变成“日常生产力工具”。但如果你只用网页版 ChatGPT / 文心一言 / 通义千问,会碰到几个很现实的问题: * 数据隐私:公司内部文档、个人笔记、聊天记录,你敢全部塞到线上吗? * 网络依赖:在飞机上、高铁里,或者公司内网严格管控时,在线 AI 直接“失联”。 * 额度与费用:免费额度有限,稍微重度一点就要付费,而且你也不知道自己的数据会不会被拿去训练。 本地部署一套 “AI + 知识库” 的好处就非常直观: 1. 数据完全不出本地,满足隐私合规要求。 2. 断网也能用,随时随地调取你的“第二大脑”。 3. 可定制:可以给团队搭一个“