SpringMVC快速入門之請求與響應

SpringMVC快速入門之請求與響應

    • 一、請求處理:獲取請求參數
      • 1.1 普通參數獲取(@RequestParam)
        • 1.1.1 基礎用法
        • 1.1.2 可選參數與默認值
      • 1.2 路徑變量(@PathVariable)
      • 1.3 表單數據綁定到對象
        • 1.3.1 定義實體類
        • 1.3.2 綁定對象參數
      • 1.4 獲取請求頭與Cookie(@RequestHeader、@CookieValue)
        • 1.4.1 獲取請求頭
        • 1.4.2 獲取Cookie
      • 1.5 獲取JSON請求體(@RequestBody)
        • 1.5.1 依賴準備
        • 1.5.2 接收JSON數據
    • 二、響應處理:返回結果給客戶端
      • 2.1 頁面跳轉(ModelAndView)
        • 2.1.1 返回邏輯視圖名(推薦)
        • 2.1.2 使用ModelAndView
      • 2.2 重定向與轉發
        • 2.2.1 重定向(redirect:)
        • 2.2.2 轉發(forward:)
      • 2.3 返回JSON數據(@ResponseBody)
        • 2.3.1 基礎用法
        • 2.3.2 @RestController簡化配置
    • 三、實戰案例:用戶注冊與查詢
      • 3.1 注冊頁面(register.jsp)
      • 3.2 結果頁面(result.jsp)
      • 3.3 Controller完整實現
      • 3.4 測試流程
    • 四、常見問題與避坑指南
      • 4.1 參數綁定失敗(400 Bad Request)
      • 4.2 JSON解析失敗(400 Bad Request)
      • 4.3 @ResponseBody返回406 Not Acceptable
    • 總結:請求與響應的核心要點

SpringMVC中請求(Request)與響應(Response)是核心交互流程:客戶端通過請求傳遞數據,服務器處理后通過響應返回結果,掌握請求參數的接收和響應結果的處理,是開發Web接口的基礎。

一、請求處理:獲取請求參數

SpringMVC提供了多種注解簡化請求參數的獲取,無需像原生Servlet那樣手動調用request.getParameter()

1.1 普通參數獲取(@RequestParam)

適用于獲取URL查詢參數(?name=張三&age=25)或表單提交的參數。

1.1.1 基礎用法
@Controller
@RequestMapping("/user")
public class UserController {/*** 獲取普通參數* URL示例:/user/query?name=張三&age=25*/@GetMapping("/query")public String queryUser(// @RequestParam:綁定參數(默認必填)@RequestParam String name,// 可指定參數名(若參數名與變量名一致,可省略@RequestParam)@RequestParam("age") Integer userAge,Model model) {model.addAttribute("message", "姓名:" + name + ",年齡:" + userAge);return "result"; // 跳轉結果頁面}
}
1.1.2 可選參數與默認值

若參數非必填,可通過required=false設置,或指定默認值:

/*** 可選參數與默認值* URL示例:/user/search?keyword=Spring(或無參數)*/
@GetMapping("/search")
public String search(// 可選參數(required=false)@RequestParam(required = false) String keyword,// 默認值(若參數為空,使用默認值)@RequestParam(defaultValue = "10") Integer size,Model model) {model.addAttribute("message", "關鍵詞:" + (keyword == null ? "無" : keyword) + ",每頁條數:" + size);return "result";
}

核心說明

  • 若參數名與方法參數名一致,@RequestParam可省略(如String name等價于@RequestParam String name);
  • 基本類型(int)需確保參數存在,否則會報錯,建議使用包裝類(Integer)并設置required=false

1.2 路徑變量(@PathVariable)

適用于REST風格的URL(如/user/1),從URL路徑中獲取參數。

/*** 路徑變量* URL示例:/user/1/detail*/
@GetMapping("/{id}/detail")
public String getUserDetail(// 從路徑中獲取id(與URL中的{id}對應)@PathVariable Integer id,Model model) {model.addAttribute("message", "查詢ID為" + id + "的用戶詳情");return "result";
}

進階用法:多路徑變量

/*** 多路徑變量* URL示例:/user/1/order/100*/
@GetMapping("/{userId}/order/{orderId}")
public String getOrder(@PathVariable("userId") Integer uId,@PathVariable Integer orderId, // 變量名與{orderId}一致,可省略valueModel model) {model.addAttribute("message", "用戶ID:" + uId + ",訂單ID:" + orderId);return "result";
}

1.3 表單數據綁定到對象

當參數較多時(如用戶注冊),可將參數自動綁定到Java對象。

1.3.1 定義實體類
package com.example.pojo;import lombok.Data;@Data // Lombok注解,自動生成getter/setter
public class User {private String username;private Integer age;private String email;
}
1.3.2 綁定對象參數
/*** 表單數據綁定到對象* 表單提交示例:username=張三&age=25&email=test@example.com*/
@PostMapping("/register")
public String registerUser(// 自動將參數綁定到User對象(參數名與對象屬性名一致)User user,Model model) {model.addAttribute("message", "注冊用戶:" + user.getUsername() + ",年齡:" + user.getAge() + ",郵箱:" + user.getEmail());return "result";
}

核心說明

  • 要求表單參數名或查詢參數名與對象的屬性名一致(如username對應user.getUsername());
  • 支持嵌套對象(如User包含Address對象,參數名需為address.city)。

1.4 獲取請求頭與Cookie(@RequestHeader、@CookieValue)

1.4.1 獲取請求頭
/*** 獲取請求頭*/
@GetMapping("/header")
public String getHeader(// 獲取User-Agent請求頭@RequestHeader("User-Agent") String userAgent,// 獲取Accept請求頭@RequestHeader("Accept") String accept,Model model) {model.addAttribute("message", "瀏覽器信息:" + userAgent + ",Accept:" + accept);return "result";
}
1.4.2 獲取Cookie
/*** 獲取Cookie*/
@GetMapping("/cookie")
public String getCookie(// 獲取名為JSESSIONID的Cookie值@CookieValue(value = "JSESSIONID", required = false) String sessionId,Model model) {model.addAttribute("message", "JSESSIONID:" + (sessionId == null ? "無" : sessionId));return "result";
}

1.5 獲取JSON請求體(@RequestBody)

適用于接收前端發送的JSON數據(如Ajax請求),需結合@ResponseBody使用。

1.5.1 依賴準備

確保添加Jackson依賴(用于JSON解析):

<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.13.3</version>
</dependency>
1.5.2 接收JSON數據
/*** 接收JSON請求體* 請求體示例:{"username":"張三","age":25}*/
@PostMapping("/json")
@ResponseBody // 返回JSON(而非跳轉頁面)
public User receiveJson(@RequestBody User user) {// 處理邏輯(如保存用戶)user.setUsername(user.getUsername() + "_processed"); // 修改用戶名return user; // 返回處理后的對象(自動轉為JSON)
}

測試方式
使用Postman發送POST請求:

  • URL:http://localhost:8080/user/json
  • 請求頭:Content-Type: application/json
  • 請求體:{"username":"張三","age":25}

響應結果(JSON):

{"username":"張三_processed","age":25,"email":null}

二、響應處理:返回結果給客戶端

SpringMVC的響應方式分為兩類:頁面跳轉(返回視圖)和數據響應(返回JSON、字符串等)。

2.1 頁面跳轉(ModelAndView)

通過返回邏輯視圖名或ModelAndView實現頁面跳轉,適用于傳統JSP開發。

2.1.1 返回邏輯視圖名(推薦)
/*** 返回邏輯視圖名(默認跳轉頁面)*/
@GetMapping("/toIndex")
public String toIndex(Model model) {model.addAttribute("title", "首頁"); // 向視圖傳遞數據return "index"; // 邏輯視圖名,由視圖解析器轉為/WEB-INF/views/index.jsp
}
2.1.2 使用ModelAndView
/*** 使用ModelAndView跳轉頁面*/
@GetMapping("/toDetail")
public ModelAndView toDetail() {ModelAndView mav = new ModelAndView();mav.setViewName("detail"); // 設置邏輯視圖名mav.addObject("id", 1); // 添加數據(等價于Model.addAttribute)mav.addObject("name", "商品詳情");return mav;
}

2.2 重定向與轉發

2.2.1 重定向(redirect:)

重定向會發起新的請求,地址欄URL會變化,之前的Model數據會丟失:

/*** 重定向*/
@GetMapping("/redirect")
public String redirect() {// 重定向到首頁(可跳轉至其他Controller接口)return "redirect:/toIndex";
}
2.2.2 轉發(forward:)

轉發是服務器內部跳轉,地址欄URL不變,Model數據可共享:

/*** 轉發*/
@GetMapping("/forward")
public String forward() {// 轉發到詳情頁(僅能跳轉至當前應用內的路徑)return "forward:/toDetail";
}

2.3 返回JSON數據(@ResponseBody)

適用于Ajax請求或前后端分離項目,通過@ResponseBody將對象轉為JSON返回。

2.3.1 基礎用法
@Controller
@RequestMapping("/api/user")
public class UserApiController {/*** 返回單個對象* URL:/api/user/1*/@GetMapping("/{id}")@ResponseBody // 將返回值轉為JSONpublic User getUser(@PathVariable Integer id) {// 模擬查詢數據庫User user = new User();user.setUsername("張三");user.setAge(25);user.setEmail("zhangsan@example.com");return user; // 自動轉為JSON}/*** 返回集合* URL:/api/user/list*/@GetMapping("/list")@ResponseBodypublic List<User> getUserList() {List<User> list = new ArrayList<>();list.add(new User("張三", 25, "zhangsan@example.com"));list.add(new User("李四", 28, "lisi@example.com"));return list; // 自動轉為JSON數組}/*** 返回自定義結果(統一響應格式)* URL:/api/user/login*/@PostMapping("/login")@ResponseBodypublic Result login(@RequestParam String username,@RequestParam String password) {if ("admin".equals(username) && "123456".equals(password)) {// 登錄成功return Result.success("登錄成功", new User(username, 0, null));} else {// 登錄失敗return Result.error("用戶名或密碼錯誤");}}
}// 統一響應結果類
@Data
class Result {private int code; // 狀態碼(200成功,400失敗)private String message; // 提示信息private Object data; // 數據// 成功響應public static Result success(String message, Object data) {Result result = new Result();result.code = 200;result.message = message;result.data = data;return result;}// 錯誤響應public static Result error(String message) {Result result = new Result();result.code = 400;result.message = message;return result;}
}

測試結果
訪問/api/user/1,響應JSON:

{"username":"張三","age":25,"email":"zhangsan@example.com"}

訪問/api/user/login?username=admin&password=123456,響應JSON:

{"code":200,"message":"登錄成功","data":{"username":"admin","age":0,"email":null}}
2.3.2 @RestController簡化配置

若控制器所有方法都返回JSON,可使用@RestController替代@Controller(自動為所有方法添加@ResponseBody):

// @RestController = @Controller + @ResponseBody
@RestController
@RequestMapping("/api/book")
public class BookApiController {// 無需添加@ResponseBody,自動返回JSON@GetMapping("/{id}")public Book getBook(@PathVariable Integer id) {return new Book(id, "SpringMVC教程", "技術書籍");}
}

三、實戰案例:用戶注冊與查詢

結合請求與響應的核心知識點,實現用戶注冊(表單提交)和查詢(JSON響應)功能。

3.1 注冊頁面(register.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>用戶注冊</title>
</head>
<body>
<form action="/user/register" method="post">用戶名:<input type="text" name="username"><br>年齡:<input type="number" name="age"><br>郵箱:<input type="email" name="email"><br><button type="submit">注冊</button>
</form>
</body>
</html>

3.2 結果頁面(result.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>結果頁</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>

3.3 Controller完整實現

@Controller
@RequestMapping("/user")
public class UserController {// 跳轉注冊頁面@GetMapping("/toRegister")public String toRegister() {return "register";}// 處理注冊(表單提交)@PostMapping("/register")public String register(User user, Model model) {// 模擬保存用戶(實際項目中調用Service)model.addAttribute("message", "注冊成功!用戶信息:" + user);return "result";}// 按條件查詢(返回JSON)@GetMapping("/api/query")@ResponseBodypublic Result query(@RequestParam(required = false) String username,@RequestParam(required = false) Integer minAge) {// 模擬查詢List<User> users = new ArrayList<>();users.add(new User("張三", 25, "zhangsan@example.com"));users.add(new User("李四", 30, "lisi@example.com"));return Result.success("查詢成功", users);}
}

3.4 測試流程

  1. 訪問/user/toRegister,填寫表單提交;
  2. 注冊成功后跳轉至結果頁,顯示用戶信息;
  3. 訪問/user/api/query?username=張三,獲取JSON格式的查詢結果。

四、常見問題與避坑指南

4.1 參數綁定失敗(400 Bad Request)

錯誤信息Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'

原因

  • 參數類型不匹配(如前端傳遞字符串,后端接收為Integer);
  • 缺少必填參數(@RequestParam默認必填)。

解決方案

  • 確保參數類型匹配(如年齡參數傳遞數字,而非字符串);
  • 非必填參數添加required=false
  • 若參數可能為空,使用包裝類(Integer)而非基本類型(int)。

4.2 JSON解析失敗(400 Bad Request)

錯誤信息HttpMessageNotReadableException: JSON parse error

原因

  • 請求頭未設置Content-Type: application/json
  • JSON格式錯誤(如缺少引號、逗號);
  • JSON字段與對象屬性不匹配(如拼寫錯誤)。

解決方案

  • 發送JSON請求時,務必設置Content-Type: application/json
  • 檢查JSON格式(可通過JSON校驗工具驗證);
  • 確保JSON字段名與對象屬性名一致(區分大小寫)。

4.3 @ResponseBody返回406 Not Acceptable

錯誤信息406 Not Acceptable

原因

  • 缺少Jackson依賴,無法將對象轉為JSON;
  • 請求頭Accept設置不當(如僅接受text/html,但返回JSON)。

解決方案

  • 添加Jackson依賴(jackson-databind);
  • 檢查請求頭Accept是否包含application/json(或不限制Accept)。

總結:請求與響應的核心要點

SpringMVC的請求與響應是前后端交互的核心:

  1. 請求處理

    • 普通參數用@RequestParam,路徑參數用@PathVariable
    • 多參數用對象綁定,JSON參數用@RequestBody
    • 靈活使用可選參數和默認值,避免參數缺失錯誤。
  2. 響應處理

    • 頁面跳轉返回邏輯視圖名,配合Model傳遞數據;
    • JSON響應用@ResponseBody@RestController
    • 重定向與轉發需區分使用場景(重定向適合外部鏈接,轉發適合內部跳轉)。
  3. 避坑關鍵

    • 參數綁定注意類型匹配和必填性;
    • JSON處理確保依賴正確和格式規范;
    • 前后端約定參數名和數據格式,減少溝通成本。

若這篇內容幫到你,動動手指支持下!關注不迷路,干貨持續輸出!
ヾ(′? ˋ)ノヾ(′? ˋ)ノヾ(′? ˋ)ノヾ(′? ˋ)ノヾ(′? ˋ)ノ

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/90109.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/90109.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/90109.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【Mysql】 Mysql zip解壓版 Win11 安裝備忘

1. 官網 MySQL :: MySQL Community Downloads 選擇 MySQL Community Server 選擇Archives 選擇 8.0版本 MySQL :: Download MySQL Community Server (Archived Versions) 1. 普通版本&#xff08;推薦&#xff09; 名稱&#xff1a;Windows (x86, 64-bit), ZIP Archive 文件…

Web3面試題

1.在使用 Ethers.js 對接 MetaMask 錢包時&#xff0c;如何檢測用戶賬戶切換的情況&#xff1f;請簡述實現思路。 答案&#xff1a;可通過監聽accountsChanged事件來檢測。當用戶切換賬戶時&#xff0c;MetaMask 會觸發該事件&#xff0c;在事件回調函數中可獲取新的賬戶地址&…

uni-app動態獲取屏幕邊界到安全區域距離的完整教程

目錄 一、什么是安全區域&#xff1f; 二、獲取安全區域距離的核心方法 三、JavaScript動態獲取安全區域距離 1. 核心API 2. 完整代碼示例 3. 關鍵點說明 四、CSS環境變量適配安全區域 1. 使用 env() 和 constant() 3. 注意事項 五、不同平臺的適配策略 1. H5 端 2…

ZKmall開源商城微服務架構實戰:Java 商城系統的模塊化拆分與通信之道

在電商業務高速增長的今天&#xff0c;傳統單體商城系統越來越力不從心 —— 代碼堆成一團、改一點牽一片、想加功能得大動干戈&#xff0c;根本扛不住高并發、多場景的業務需求。微服務架構卻能破這個局&#xff1a;把系統拆成一個個能獨立部署的小服務&#xff0c;每個服務專…

ROS 與 Ubuntu 版本的對應關系

ROS 作為一套用于構建機器人應用的開源框架&#xff0c;其開發和運行高度依賴 Ubuntu 等 Linux 發行版&#xff0c;尤其是 Ubuntu 因其廣泛的兼容性和社區支持&#xff0c;成為了 ROS 最主流的運行平臺。 一、ROS 與 Ubuntu 版本的對應關系&#xff08;截至 2025 年&#xff0c…

GPT-4o mini TTS:領先的文本轉語音技術

什么是 GPT-4o mini TTS&#xff1f; GPT-4o mini TTS 是 OpenAI 推出的全新一代文本轉語音&#xff08;TTS&#xff09;技術&#xff0c;能夠以自然、流暢的方式將普通文本轉換為語音。依托先進的神經網絡架構&#xff0c;GPT-4o mini TTS 在語音合成中避免了傳統 TTS 的生硬…

Git下載全攻略

目標讀者初學者或有經驗的開發者不同操作系統用戶&#xff08;Windows、macOS、Linux&#xff09;下載前的準備確認系統版本和位數&#xff08;32-bit/64-bit&#xff09;檢查網絡環境是否穩定確保有足夠的磁盤空間Windows系統下載Git訪問Git官方網站&#xff08;https://git-s…

ADAS域控軟件架構-網絡管理狀態與喚醒機制

1. 狀態介紹: Sleep Mode:總線睡眠模式,控制器不發送應用報文和網絡管理報文。 Pre-Sleep Mode:準備總線睡眠模式,控制器不發送應用報文和網絡管理報文。 Ready Sleep Mode:就緒睡眠模式,系統發送應用報文但是不發送網絡管理報文。 Normal Operation mode:正常工作模式…

pytest簡單使用和生成測試報告

目錄 1. 基本使用 1--安裝 2--pytest書寫規則 3--為pycharm設置 以 pytest的方式運行 4--setup和teardown 5--setup_class和teardown 2. pytest生成測試報告 基本使用 安裝 pytest文檔地址 pytest documentation pip install pytest點擊pycharm左邊的控制臺按鈕 輸入pip inst…

Spring Boot 第一天知識匯總

一、Spring Boot 是什么&#xff1f;簡單說&#xff0c;Spring Boot 是簡化 Spring 應用開發的框架 —— 它整合了整個 Spring 技術棧&#xff0c;提供了 “一站式” J2EE 開發解決方案。核心優點&#xff1a;快速創建獨立運行的 Spring 項目&#xff0c;無需繁瑣配置&#xff…

MySql主從部署

MySql主從部署 1、操作環境 硬件環境&#xff1a;香橙派5 aarch64架構 軟件環境&#xff1a;Ubuntu 22.04.3 LTS 軟件版本&#xff1a;mysql-8.0.42 操作方式&#xff1a;mysql_1,mysql_2容器 主節點&#xff1a;mysql_1 啟動命令&#xff1a;docker run --name mysql_master \…

Redis——Redis進階命令集詳解(下)

本文詳細介紹了Redis一些復雜命令的使用&#xff0c;包括Redis事務相關命令&#xff0c;如MULTI、EXEC、DISCARD 和 WATCH ,發布訂閱操作命令&#xff0c;如PUBLISH 、SUBSCRIBE 、PSUBSCRIBE ,BitMap操作命令&#xff0c;如SETBIT、GETBIT、BITCOUNT、BITOP&#xff0c;HyperL…

C#使用socket報錯 System.Net.Sockets.SocketException:“在其上下文中,該請求的地址無效。

bind: 在其上下文中&#xff0c;該請求的地址無效。問題定位 程序中運行socket服務端程序時&#xff0c;綁定的IP地址無效&#xff0c;即請求的IP地址在你的機子上找不到。原因有以下幾種可能&#xff1a; 1&#xff09;server端綁定的IP地址不是本機的IP地址。 2&#xff09;之…

計算機底層入門 05 匯編學習環境通用寄存器內存

2.3 匯編學習環境我們通過上一章筆記&#xff0c;得知 計算機好像 只會通過位運算 進行 數字的加法。 而機器語言的魅力就是 位運算&#xff0c;解析規則。它們也都是通過 電路 來進行實現的。這就是 計算機最底層的本質了&#xff01;&#xff01;&#xff01; 匯編語言 所謂的…

Java學習---Spring及其衍生(上)

在 Java 開發領域&#xff0c;Spring 生態占據著舉足輕重的地位。從最初的 Spring 框架到后來的 SpringBoot、SpringMVC 以及 SpringCloud&#xff0c;每一個組件都在不同的場景下發揮著重要作用。本文將深入探討這幾個核心組件&#xff0c;包括它們的定義、原理、作用、優缺點…

LVGL應用和部署(個人開發嵌入式linux產品)

【 聲明&#xff1a;版權所有&#xff0c;歡迎轉載&#xff0c;請勿用于商業用途。 聯系信箱&#xff1a;feixiaoxing 163.com】隨著經濟越來越走向常態化發展&#xff0c;將來的公司基本是兩個趨勢&#xff0c;一個是公司越做越大&#xff0c;越來越趨向于壟斷&#xff1b;另外…

CPU,減少晶體管翻轉次數的編碼

背景 以4比特為單位&#xff0c;共16個數。仔細思考狀態轉換過程中的晶體管翻轉次數。 0000 0001&#xff0c;1 0010&#xff0c;2 0011&#xff0c;1 0100&#xff0c;3 0101&#xff0c;1 0110&#xff0c;2 0111&#xff0c;1 1000&#xff0c;4 1001&#xff0c;1 1010&…

LLM 中的 溫度怎么控制隨機性的?

LLM 中的 溫度怎么控制隨機性的? 在LLM的解碼過程中,溫度(Temperature)通過調整token概率分布的“陡峭程度”來控制隨機性:溫度越低,概率分布越陡峭(高概率token的優勢越明顯),隨機性越低;溫度越高,分布越平緩(高低概率token的差異被縮小),隨機性越高。 溫度,…

freemodbus使用

文章目錄? **CubeMX配置**1. UART配置&#xff08;RS485通信&#xff09;2. Timer配置&#xff08;RTU字符間隔檢測&#xff09;3. GPIO配置&#xff08;RS485方向控制&#xff09;? **STM32F103 RS485 FreeModbus RTU 配置概覽****1?? CubeMX硬件配置****2?? FreeModb…

【Ansible】Ansible 管理 Elasticsearch 集群啟停

一、集群節點信息 通過 Ansible inventory 定義的集群節點分組如下&#xff1a;[es]&#xff08;Elasticsearch 節點&#xff09; 192.168.100.150192.168.100.151192.168.100.152[logstash]&#xff08;Logstash 節點&#xff09; 192.168.100.151[kibana]&#xff08;Kibana …