首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring Controller 獲取請求參數六大方式完整實戰指南

     編輯:Java 綜合教學

Spring Controller 獲取請求參數六大方式完整實戰指南

Spring MVC 提供多種靈活的參數綁定機制,適應不同業務場景。本文系統整理六大核心方式、適用條件、優缺點對比與最佳實務建議。

六大方式總覽對比

方式註解/類型適用 Content-TypeGET/POST優點缺點
1. 直接映射方法參數同名application/x-www-form-urlencodedGET/POST*最簡潔參數多時簽名冗長;POST 需特定 Content-Type
2. HttpServletRequest原生 API所有GET/POST完全控制、無限制樣板代碼多、耦合 Servlet API
3. 實體 Bean (Command Object)POJO 參數application/x-www-form-urlencoded
multipart/form-data
GET/POST物件導向、自動封裝、易驗證需屬性名完全匹配
4. @ModelAttribute標註參數application/x-www-form-urlencodedPOST明確語義、支援 Session 屬性預綁定POST 專用、略顯冗餘
5. @RequestParam標註參數綁定application/x-www-form-urlencoded
GET: 所有
GET/POST*參數名映射、必填控制、預設值JSON 請求體不支援
6. @RequestBody請求體反序列化application/json
application/xml
POST/PUT複雜對象圖、REST 標準需 Jackson/JAXB、GET 不適用

* POST 需 Content-Type: application/x-www-form-urlencoded

代碼實戰範例

1. 直接映射(最簡潔)

@GetMapping("/addUser1")
public String addUser1(String username, String password) {
    // URL: /addUser1?username=abc&password=123
    return "index";
}

2. HttpServletRequest(最原始)

@PostMapping("/addUser2")
public String addUser2(HttpServletRequest request) {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    return "index";
}

3. 實體 Bean 自動封裝(推薦表單場景)

@PostMapping("/addUser3")
public String addUser3(UserModel user) {
    // 自動調用 setUsername/setPassword
    return "index";
}

public class UserModel {
    private String username;
    private String password;
    // getter/setter
}

4. @ModelAttribute(語義明確)

@PostMapping("/addUser5")
public String addUser5(@ModelAttribute("user") UserModel user) {
    // 等同方式 3,但可配合 @SessionAttributes 實現表單向導
    return "index";
}

5. @RequestParam(精確控制)

@GetMapping("/addUser6")
public String addUser6(
    @RequestParam("username") String username,
    @RequestParam(value = "password", required = false, defaultValue = "123456") String password
) {
    // 必填檢查、重命名、預設值
    return "index";
}

6. @RequestBody(JSON/REST 標準)

@PostMapping("/addUser7")
public String addUser7(@RequestBody UserModel user) {
    // 請求體: {"username":"abc","password":"123"}
    // 需配置 HttpMessageConverter (Jackson)
    return "index";
}

進階技巧與避坑指南

參數驗證整合

@PostMapping("/user")
public ResponseEntity createUser(@Valid @RequestBody UserDTO dto, BindingResult result) {
    if (result.hasErrors()) {
        return ResponseEntity.badRequest().body(result.getAllErrors());
    }
    return ResponseEntity.ok(userService.create(dto));
}

Map/多值參數綁定

// 綁定所有參數到 Map
@GetMapping("/search")
public String search(@RequestParam Map params) { ... }

// 綁定同名多值參數
@GetMapping("/filter")
public String filter(@RequestParam("tags") List tags) { ... }

Content-Type 陷阱總結

Content-Type支援方式不支援方式
application/x-www-form-urlencoded1,2,3,4,56
multipart/form-data (檔案上傳)2,31,4,5,6
application/json2,61,3,4,5
application/xml2,61,3,4,5

最佳實務建議

  1. 表單提交:優先使用 實體 Bean (方式 3),配合 @Valid 驗證
  2. REST API:@RequestBody (方式 6) + JSON,語義清晰、支援複雜結構
  3. 簡單查詢/GET:@RequestParam (方式 5),明確必填/預設值
  4. 檔案上傳:MultipartFile + 實體 Bean,@RequestPart 區分檔案與元數據
  5. 避免 直接使用 HttpServletRequest(方式 2),除非需要訪問 Header/Cookie/Session 等原生資訊

總結

Spring MVC 的參數綁定機制極其靈活,核心原理是 HandlerMethodArgumentResolver 鏈。理解各方式的適用邊界與 Content-Type 依賴關係,能讓 Controller 代碼既簡潔又健壯,是 Spring 開發者的必修內功。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved