31-Spring请求传参数

一、get和post请求传参数

接收端解析参数值

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @GetMapping("/api/user")
    public String getUser(@RequestParam("name") String name, @RequestParam("age") int age) {
        // 处理接收到的参数
        return "Name: " + name + ", Age: " + age;
    }
}

在上述示例中,使用@RequestParam注解将接收到的参数绑定到方法的参数上。这样,当请求到达/api/user路径时,Spring会自动解析URL中的查询字符串,并将参数值绑定到对应的方法参数上。

例如,发送GET请求至http://localhost:8080/api/user?name=John&age=30,接收端的getUser方法将会被调用,且name参数值为 John ,age参数值为30。

二、post请求传pojo对象

在请求发送和接收POJO对象时,通常使用POST请求,并将POJO对象转换为JSON格式进行传输。发送端将POJO对象转换为JSON字符串,并将其作为请求体发送。接收端从请求体中获取JSON字符串,并将其解析为对应的POJO对象。

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestBody
public class UserController {
    @PostMapping("/api/user")
    public String createUser(User user) {
        // 处理接收到的POJO对象
        return "User created: " + user.getName() + ", Age - " + user.getAge();
    }
}

在上述示例中,使用Spring的@RequestBody注解将请求体中的JSON字符串转换为对应的POJO对象。当POST请求到达/api/user路径时,Spring会自动将请求体中的JSON字符串解析为User对象,并将其作为方法的参数传递。

三、pojo对象的嵌套传参数

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestBody
public class OrderController {
    @PostMapping("/api/order")
    public String createOrder(Order order) {
        // 处理接收到的POJO对象,包括嵌套的POJO对象
        return "Order created: " + order.getOrderId() + ", Customer - " + order.getCustomer().getName();
    }
}

四、数组传参

@RestController
@RequestBody
public class MyController {
    @PostMapping("/api/array")
    public String processArray(String[] numbers) {
        // 处理接收到的数组
        return "Received array length: " + numbers.length;
    }
}

五、集合传参

@RestController
@RequestBody
public class MyController {
    @PostMapping("/api/collection")
    public String processCollection(@RequestParam List<String> items) {
        // 处理接收到的集合
        return "Received collection size: " + items.size();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值