一、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();
}
}