我是 Spring Boot 新手,我希望对 JSON 和简单请求参数有相同的请求映射方法,例如:
@RequestMapping(value = "/start")
public String startPostProcess(@RequestParam(value = "url",
required = false,
defaultValue = "https://goo.gl") String url,
@RequestParam(value = "word",
required = false,
defaultValue = "Search") String word,
@RequestBody String hereGoesJSON) {
//Do some stuff
}
所以,当请求带有参数时,只有@RequestParam有效,其他情况我们将使用@RequestBody注解。
localhost:8080/start?url=htts://google.com&word=Luck
或者也许我能够编写这样的方法,用于接受任何参数:
@RequestMapping(value = "/start")
public String startPostProcess(@RequestBody String anyParam) {
//Parse this anyParam
}
?
我在 spring 文档中没有找到这个技巧,所以我将不胜感激任何指向它的链接。
最佳答案
好的,我已经解决了这个问题:D
我只需要 2 个具有相同映射并显式指定 RequestMethod 类型的方法:
@RequestMapping(value = "/start")
public String startPostProcess(@RequestParam(value = "url",
required = false,
defaultValue = "https://goo.gl") String url,
@RequestParam(value = "word",
required = false,
defaultValue = "Search") String word) throws InterruptedException {
//Do some stuff
}
@RequestMapping(value = "/start", method = RequestMethod.POST, consumes = "application/json")
public String startJsonProcess(@RequestBody String body) {
//Do another stuff with RequestBody
}
UPD:添加了“consumes =”application/json”。它有助于区分简单的POST请求和JSON POST请求。
关于java - Spring Boot 将 JSON 和简单属性传递给相同的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33719900/