[英]Send a map as request param to a GET request in Spring Boot app
Basically I need to accept a map along with other request parameters in a GET request.基本上我需要在 GET 请求中接受 map 以及其他请求参数。
Controller: Controller:
@GetMapping
public Page<Users> search(@Valid final UsersParams params) {
return userService.search(params);
}
My params object looks like this:我的参数 object 看起来像这样:
public class UserParams {
private String age;
private String gender;
private MultiValuedMap<String, String> names;
}
So, if I pass a request with these param values:因此,如果我传递具有这些参数值的请求:
users?age=20&gender=Male&names={"john,doe","Harry,Potter","James,Bond"}
Is this even possible to pass a map in a request and make it work in a GET REST call?这甚至可以在请求中传递 map 并使其在 GET REST 调用中工作吗?
With whatever minute knowledge I have, the only other option I could think of is, instead of the map use a list with comma-separated values and do some deserialization hack.凭借我所掌握的任何知识,我能想到的唯一其他选择是,而不是 map 使用带有逗号分隔值的列表并进行一些反序列化黑客攻击。
The best way you can try is make this request a post request.您可以尝试的最佳方法是将此请求设为发布请求。 Then you can use as,
然后你可以使用作为,
Request Object请求对象
{
"age" : 20,
"gender" : "Male",
"names" : {
"john" : "doe"
}
}
DTO DTO
@AllArgsConstructor
@NoArgsConstructor
@Data
class UserParams {
String age;
String gender;
Map<String, String> names;
}
@PostMapping("/test2")
public void search2(@RequestBody UserParams params) {
log.info("This is the object we got", params);
}
If you want it to be GET than you can use like this,如果您希望它是 GET,那么您可以像这样使用它,
/test?age=20&gender=Male&john=doe&Harry=Potter
@GetMapping("/test")
public void search(UserParams params, @RequestParam Map<String, String> names) {
log.info("This is the object we got", params);
}
where you will get the age and gender inside UserParams and all the pair inside names Map, You need to ignore first two entries inside names requestparam as age and gender will also come inside this.您将在 UserParams 中获取年龄和性别以及名称 Map 中的所有配对,您需要忽略名称 requestparam 中的前两个条目,因为年龄和性别也会出现在其中。
You can keep only Map rather than Userparam object您只能保留 Map 而不是 Userparam 对象
Put server.tomcat.relaxed-query-chars=[,]
in application.properties
file将
server.tomcat.relaxed-query-chars=[,]
放入application.properties
文件
Then you can use a url like the one below to send params in the map然后你可以使用如下所示的 url 在 map 中发送参数
users?age=20&gender=Male&names[john]=doe&names[Harry]=Potter&names[James]=Bond
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.