如何发送List对象作为参数来获取控制器
例如:
@GetMapping("/demo")
public List<Student> m1(List<Employee> account)
{
}
public Employee
{
String id;
String name;
}
如何调用网络客户端: 我尝试过类似
Employee e = new Employee("1","tarun");
Employee e1 = new Employee("2","run");
List<Employee> a = new ArrayList<>();
a.add(e);
a.add(e1);
webclient
.get()
.uri(x->x.path("/demo")
.queryParam("account",a)
.build())
.accept(json)
.retrieve()
.bodyToMono(new parameterizedtypereference<List<Student>>(){});
当我尝试像上面那样出现错误时,任何人都可以帮我如何使用 webclient 调用上述 m1 方法,我需要传递 m1 方法的列表。`
首先,确保在项目中包含 Spring WebFlux 和 WebClient 必要的依赖项。
如果您想使用 WebClient 将 List 对象作为参数发送到 @GetMapping 控制器方法,您可以使用
bodyValue()
。
首先你
Employee
类应该是可序列化的
public class Employee {
private String id;
private String name;
// Constructor, getters, setters, etc.
}
您的控制器方法也几乎没有变化。
@GetMapping("/demo")
public List<Student> m1(@RequestBody List<Employee> account) {
// Your implementation
}
这就是您如何使用 WebClient 调用此方法,
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.http.MediaType;
// ...
Employee e = new Employee("1", "tarun");
Employee e1 = new Employee("2", "run");
List<Employee> a = new ArrayList<>();
a.add(e);
a.add(e1);
List<Student> result = WebClient.create()
.post()
.uri("/demo")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(a)
.retrieve()
.bodyToFlux(Student.class)
.collectList()
.block(); // block() is used here for simplicity, consider using subscribe() in a real application
// 'result' now contains the response from the server