SpringBoot的前后端聯(lián)調(diào):表單提交、AJAX登錄與狀態(tài)管理、以及JSON數(shù)據(jù)交互
作為 Spring Boot 初學(xué)者,理解后端接口的編寫和前端頁面的交互至關(guān)重要。本文將通過三個經(jīng)典的 Web 案例——表單提交、AJAX 登錄與狀態(tài)管理、以及 JSON 數(shù)據(jù)交互——帶您掌握前后端聯(lián)調(diào)的核心技巧和 Spring Boot 的關(guān)鍵注解。
本文通過三個Web案例(表單提交、AJax異步交互與狀態(tài)管理、JSON數(shù)據(jù)傳輸與REST式接口)演示SpringBoot的前后端聯(lián)調(diào),案例一展示表單提交的與參數(shù)綁定,案例二展示AJ異步交互與Session狀態(tài)管理,案例三演示JSON數(shù)據(jù)傳輸與REST式接口,每個案例詳述了后端注解與前端代碼,解析了聯(lián)調(diào)重點,通過這些案例,讀者能能學(xué)到如何在實際項目中實現(xiàn)前后端有效溝通
1. 案例一:表單提交與參數(shù)綁定(計算求和)
本案例展示最基礎(chǔ)、最傳統(tǒng)的 Web 交互方式:HTML 表單提交。
1.1 后端代碼:CalcController.java
使用 @RestController 簡化接口編寫,并通過方法參數(shù)接收表單數(shù)據(jù)。
package cn.overthinker.springboot;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/calc")
@RestController
public class CalcController {
/**
* 求和接口:通過方法參數(shù)名自動接收前端表單提交的 num1 和 num2
*/
@RequestMapping("/sum")
public String sum(Integer num1, Integer num2) {
// 使用 Integer 包裝類進行非空判斷,避免空指針異常
if(num1 == null || num2 == null) {
return "請求非法:請輸入兩個數(shù)字!";
}
// 計算并返回結(jié)果
return "計算結(jié)果為:" + (num1 + num2);
}
}
1.2 前端代碼:calc.html


?? HTML 代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="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>
<div class="calculator-container">
<h1>簡單求和計算器</h1>
<form action="/calc/sum" method="post">
數(shù)字1:<input name="num1" type="text" placeholder="請輸入數(shù)字1"><br>
數(shù)字2:<input name="num2" type="text" placeholder="請輸入數(shù)字2"><br>
<input type="submit" value=" 點擊相加 ">
</form>
</div>
</body>
</html>
1.3 聯(lián)調(diào)重點解析:參數(shù)綁定
- 前端 Form 的
name屬性:前端<input name="num1">中的name必須與后端方法的參數(shù)名Integer num1完全一致。 - 后端自動類型轉(zhuǎn)換:Spring Boot 會自動將 HTTP 請求中的字符串參數(shù)轉(zhuǎn)換為 Java 方法所需的
Integer類型。
2. 案例二:AJAX 異步交互與 Session 狀態(tài)管理(用戶登錄)
本案例引入 AJAX 實現(xiàn)無刷新登錄,并利用 Session 在服務(wù)器端保存用戶狀態(tài)。
2.1 后端代碼:UserController.java和Person.java
UserController.java(核心邏輯)
package cn.overthinker.springboot;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/user")
@RestController
public class UserController {
/**
* 登錄接口:使用 HttpSession 存儲用戶信息
*/
@PostMapping("/login")
public boolean login(String userName, String password, HttpSession session) {
if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
return false;
}
// 硬編碼校驗(實際項目應(yīng)查詢數(shù)據(jù)庫)
if("admin".equals(userName) && "123456".equals(password)) {
// **核心知識點:登錄成功后,將用戶名存入 Session**
session.setAttribute("loginUser", userName);
return true;
}
return false;
}
/**
* 獲取當(dāng)前登錄用戶接口:從 Session 中讀取用戶信息
*/
@GetMapping("/getLoginUser")
public String getLoginUser(HttpServletRequest request) {
// request.getSession(false):如果 Session 不存在,則不創(chuàng)建
HttpSession session = request.getSession(false);
if(session != null) {
String loginUser = (String) session.getAttribute("loginUser");
return loginUser;
}
return "";
}
}
Person.java(實體類)
雖然未直接用于登錄,但作為 JavaBean 演示參數(shù)綁定基礎(chǔ)。
package cn.overthinker.springboot;
// 略:包含 name, password, age 屬性及其 Getter/Setter 和 toString 方法
public class Person {
// ... 屬性、Getter/Setter、toString ...
}
2.2 前端代碼:login.html和index.html


使用 jQuery AJAX 進行異步登錄,用戶體驗更好。
login.html(登錄頁面)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="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>
<div class="login-box">
<h1>用戶登錄</h1>
用戶名:<input name="userName" type="text" id="userName" placeholder="請輸入用戶名"><br>
密碼:<input name="password" type="password" id="password" placeholder="請輸入密碼"><br>
<input type="button" value="登錄" onclick="login()">
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
function login() {
$.ajax({
url: "/user/login",
type: "post",
// 核心聯(lián)調(diào):通過 AJAX 傳遞參數(shù)
data: {
userName: $("#userName").val(),
password: $("#password").val()
},
success: function (result) {
if (result) {
// 登錄成功,跳轉(zhuǎn)到首頁
location.href = "/index.html";
} else {
alert("用戶名或密碼錯誤");
}
}
});
}
</script>
</body>
</html>
index.html(首頁 - 獲取登錄信息)
<!doctype html>
<html lang="en">
<head>
<meta charset="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>
<div class="welcome">歡迎回來,登錄人: <span id="loginUser"></span></div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
// 頁面加載后立即發(fā)起 AJAX 請求獲取 Session 中的登錄信息
$.ajax({
url: "user/getLoginUser",
type: "get",
success: function (userName) {
// 將后端返回的用戶名顯示在頁面上
$("#loginUser").text(userName || "(未登錄)");
}
});
</script>
</body>
</html>
2.3 聯(lián)調(diào)重點解析:AJAX 與 Session
- AJAX (Asynchronous JavaScript and XML):允許前端在不刷新頁面的情況下,與后端進行數(shù)據(jù)交換。在
login.html中,我們使用 jQuery 的$.ajax實現(xiàn)異步請求。 - Session 機制:Session 是服務(wù)器端用來存儲用戶狀態(tài)信息的機制。
- 當(dāng)用戶登錄成功后,
session.setAttribute("loginUser", userName);在服務(wù)器上創(chuàng)建或關(guān)聯(lián)一個 Session,并存入數(shù)據(jù)。 - 瀏覽器通過 Cookie 自動攜帶一個
Session ID給服務(wù)器。 - 在
index.html請求/user/getLoginUser時,服務(wù)器通過瀏覽器傳來的Session ID找到對應(yīng)的 Session,從而取出存儲的loginUser信息,實現(xiàn)了狀態(tài)保持。
- 當(dāng)用戶登錄成功后,
3. 案例三:JSON 數(shù)據(jù)傳輸與 RESTful 接口(留言板)
本案例是現(xiàn)代 Web 開發(fā)最常用的方式:前后端通過 JSON 格式進行數(shù)據(jù)交互,后端使用 RESTful 風(fēng)格的接口。
3.1 后端代碼:MessageController.java和MesseageInfo.java
MessageController.java(核心邏輯)
package cn.overthinker.springboot;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RequestMapping("/Message")
@RestController
public class MessageController {
// 存儲留言的列表(模擬數(shù)據(jù)庫存儲)
private List<MesseageInfo> messeageInfoList = new ArrayList<>();
/**
* 發(fā)布留言接口:使用 @RequestBody 接收 JSON 數(shù)據(jù)
*/
@PostMapping("/publish")
public Boolean publish(@RequestBody MesseageInfo messeageInfo) {
// 參數(shù)校驗
if(!StringUtils.hasLength(messeageInfo.getFrom())
|| !StringUtils.hasLength(messeageInfo.getTo())
|| !StringUtils.hasLength(messeageInfo.getMessage())) {
return false;
}
messeageInfoList.add(messeageInfo);
return true;
}
/**
* 獲取留言列表接口:返回 JSON 數(shù)組
*/
@GetMapping("/getList")
public List<MesseageInfo> getList() {
return messeageInfoList;
}
}
MesseageInfo.java(數(shù)據(jù)傳輸對象 DTO)
使用 Lombok 的 @Data 注解自動生成 Getter/Setter。
package cn.overthinker.springboot;
import lombok.Data;
@Data // Lombok 注解,自動生成 Getter/Setter, toString, equals等方法
public class MesseageInfo {
private String from;
private String to;
private String message; // 注意:前端傳的字段名是 message
}
3.2 前端代碼:message.html

前端使用 AJAX 發(fā)送 JSON 格式的數(shù)據(jù)。
?? HTML 代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="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>
<div class="container">
<h1>留言板</h1>
<p class="grey">輸入后點擊提交,信息將顯示在下方</p>
<div class="row">
<span>誰:</span> <input type="text" id="from" placeholder="你的名字">
</div>
<div class="row">
<span>對誰:</span> <input type="text" id="to" placeholder="你想對誰說">
</div>
<div class="row">
<span>說什么:</span> <input type="text" id="say" placeholder="你的留言內(nèi)容">
</div>
<input type="button" value="提交留言" id="submit" onclick="submit()">
<div class="message-list">
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
// 頁面加載時自動獲取并展示所有留言
function loadMessages() {
$.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();
function submit() {
var from = $('#from').val();
var to = $('#to').val();
var say = $('#say').val();
if (from == '' || to == '' || say == '') { return; }
// 核心聯(lián)調(diào):發(fā)送 JSON 數(shù)據(jù)
$.ajax({
type: "post",
url: "/Message/publish",
// 1. 設(shè)置 Content-Type 為 application/json
contentType: "application/json",
// 2. 使用 JSON.stringify 將 JS 對象轉(zhuǎn)換為 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 聯(lián)調(diào)重點解析:@RequestBody與 JSON
@RequestBody:這是 Spring Boot 接收 JSON 數(shù)據(jù)的關(guān)鍵注解。它告訴 Spring MVC:請將 HTTP 請求體(Request Body)中的 JSON 字符串解析,并自動映射到方法參數(shù)MesseageInfo messeageInfo對象中。- 前端
contentType: "application/json":前端必須設(shè)置此頭信息,告訴服務(wù)器發(fā)送的是 JSON 格式數(shù)據(jù)。 - 前端
JSON.stringify(...):JavaScript 的內(nèi)置方法,用于將一個 JS 對象(如{from: 'A', to: 'B', message: 'Hello'})轉(zhuǎn)換為后端能夠識別的 JSON 字符串。 - JSON 字段匹配:前端 JSON 中的鍵(Key)必須與后端 DTO (
MesseageInfo) 中的屬性名(Field Name)保持一致(例如:message對應(yīng)private String message;)。
4. 總結(jié):前后端聯(lián)調(diào)模式對比
| 聯(lián)調(diào)模式 | 案例 | 核心機制 | 后端注解/參數(shù)接收 | 優(yōu)點 | 缺點 |
|---|---|---|---|---|---|
| Form 表單提交 | 求和計算器 | 瀏覽器直接跳轉(zhuǎn)/刷新頁面 | 方法參數(shù)名匹配 | 簡單、無需 JavaScript | 用戶體驗差、無法精細控制 |
| AJAX (Query String) | 登錄系統(tǒng) (GET/POST) | 異步通信(無刷新) | 方法參數(shù)名匹配 | 用戶體驗好、可局部更新 | 僅適用于少量簡單數(shù)據(jù) |
| AJAX (JSON) | 留言板 | 異步通信(無刷新) | @RequestBody 接收 DTO | 傳輸復(fù)雜結(jié)構(gòu)數(shù)據(jù)、最常用 | 需要配置 Content-Type 和 JSON.stringify |
到此這篇關(guān)于SpringBoot的前后端聯(lián)調(diào):表單提交、AJAX登錄與狀態(tài)管理、以及JSON數(shù)據(jù)交互的文章就介紹到這了,更多相關(guān)SpringBoot的后端接口和前端頁面的交互內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中FileWriter的用法及wirte()重載方法詳解
這篇文章主要介紹了Java中FileWriter的用法及wirte()重載方法詳解,FileWriter是Java編程語言中的一個類,用于將字符寫入文件,它提供了一種簡單而方便的方式來創(chuàng)建、打開和寫入文件,通過使用FileWriter,我們可以將字符數(shù)據(jù)寫入文本文件,需要的朋友可以參考下2023-10-10
Java中List轉(zhuǎn)Map的幾種具體實現(xiàn)方式和特點
這篇文章主要介紹了幾種常用的List轉(zhuǎn)Map的方式,包括使用for循環(huán)遍歷、Java8StreamAPI、ApacheCommonsCollections和GoogleGuava,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2025-01-01
jboss( WildFly)上運行 springboot程序的步驟詳解
這篇文章主要介紹了jboss( WildFly)上運行 springboot程序的步驟詳解,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02
SpringBoot實現(xiàn)多種來源的Zip多層目錄打包下載
這篇文章主要為大家詳細介紹了SpringBoot如何實現(xiàn)多種來源的?Zip?多層目錄打包下載,包括本地文件和HTTP混合,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-04-04
Mybatis-plus3.4.3下使用lambdaQuery報錯解決
最近在使用lambdaQuery().eq(CommonUser::getOpenId, openId).one()進行查詢報錯,本文主要介紹了Mybatis-plus3.4.3下使用lambdaQuery報錯解決,具有一定的參考價值,感興趣的可以了解一下2024-07-07
springboot項目實現(xiàn)多數(shù)據(jù)源配置使用dynamic-datasource-spring-boot-starter

