在Spring中基于请求体将相同的URL映射到不同的方法 [英] Mapping the same url to different methods based on request body in spring
问题描述
我想知道是否可以将相同的URL映射到 RestController
类中的不同方法,仅基于请求正文。例如:
I want to know if it's possible to map the same URL to different methods in the RestController
class, based only in the request body. For example:
@RequestMapping(value="/delete", method=RequestMethod.POST )
public void delete(@RequestBody String id) {
//do something
}
@RequestMapping(value="/delete", method=RequestMethod.POST )
public void delete(@RequestBody Book book) {
//do something
}
请求正文将始终是JSON有效负载。如果它是 {id:foo}
我想要调用第一个方法。如果请求正文是:
The request body will always be a JSON payload. if it's {"id":"foo"}
I want the first method to be called. If the request body is:
{
"title":"Spring Guide",
"author":"John Doe"
}
我希望调用第二种方法。这可能吗?
I want the second method to be called. Is this possible?
推荐答案
无法仅通过有效负载进行区分。
There is no way to differentiate only by payload.
基于我在这里做的测试以及M. Deinum和Ali Dehghani的回答,我认为最好的方法是为每个案例设置不同的网址。所以要通过id删除 / books / {id}
,并使用对象的JSON删除 / books
正文删除传递对象。感谢所有评论。
Based on the tests I did here and M. Deinum and Ali Dehghani's response I think the best way to do this is to have different urls for each case. So a /books/{id}
to delete by the id, and a /books
with the object's JSON in the body to delete passing the object. Thanks for all that commented.
这篇关于在Spring中基于请求体将相同的URL映射到不同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!