Spring Boot中获取请求参数的几种方式

发布于:2024-06-28 ⋅ 阅读:(142) ⋅ 点赞:(0)

前言

在构建现代 Web 应用时,处理来自客户端的请求参数是不可或缺的一部分。Spring Boot作为构建微服务应用的领先框架,提供了多种灵活高效的方式来获取请求参数,满足各种应用场景。

无论您是Spring Boot的初学者,还是希望更深入了解参数获取的最佳实践,本文都将为您提供宝贵的参考。

@RequestParam

查询参数(Query Parameters): 附加在 URL 问号(?)后面的参数,用于过滤、排序等;使用 @RequestParam 注解获取。

例如:http://localhost:8080/api/users?name=John&age=30 中的 name 和 age。

    @GetMapping("/users")
    public void getParam(@RequestParam("name") String name, @RequestParam("age") Integer age) {
        log.info("name = {},age = {}", name, age);
    }

@PathVariable

路径变量(Path Variables): URI 路径中的一部分,用作占位符,传递给后端 API;使用 @PathVariable 注解获取。

例如:http://localhost:8080/api/users/1 中的 1 可以是用户 ID。

    @GetMapping("/users/{id}")
    public void getParam(@PathVariable("id") Long id) {
        log.info("获取到用户id = {}", id);
    }

@MatrixVariable

矩阵变量(Matrix Variables): 较少使用,在 URI 路径中使用分号(;)分隔的参数。使用 @MatrixVariable 注解获取。

注意:SpringBoot默认禁用矩阵变量的功能,开启方式如下:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;

@Configuration
public class MyWebConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

例如:http://localhost:8080/api/users/123;name=zhangsan;age=18 中的name和age 参数。

 @GetMapping("/users/{id}")
    public void getParam(@PathVariable String id, @MatrixVariable(name = "name") String name, @MatrixVariable(name = "age") Integer age) {
        log.info("id = {},sort = {},order = {}", id, name, age);
    }

@RequestBody

请求体(Request Body): 常用于 POST、PUT 请求,将复杂数据结构放在请求体中传递。使用 @RequestBody 注解获取。

例如: 发送 JSON 格式的用户信息到 /api/users。

    @PostMapping("/users")
    public void getParam(@RequestBody List<UserInfo> userList) {
        log.info("userList = {}",userList);
    }

传参示例如下:

传参示例

@RequestHeader

请求头(Request Headers): HTTP 请求头中携带的参数,例如:认证信息等。使用 @RequestHeader 注解获取。
例如:获取Authorization 头信息。

   @GetMapping("/users")
    public void getParam(@RequestHeader("auth") String auth) {
        log.info("auth = {}",auth);
    }

传参示例如下:

传参示例

@CookieValue

Cookie: 存储在客户端的小型文本文件,用于维护会话状态等。使用 @CookieValue 注解获取。

    @GetMapping("/users")
    public void getParam(@CookieValue(name = "sessionId") String sessionId) {
        log.info("sessionId = {}",sessionId);
    }

传参示例如下:

传参示例