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

前言

在构建现代 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);
    }

传参示例如下:

传参示例

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小Java开发者

“是一种鼓励,你懂的”

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值