Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

java - Mapping the same url to different methods based on request body in spring

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
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no way to differentiate only by payload.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...