java - Spring Boot 将 JSON 和简单属性传递给相同的映射

标签 java json spring spring-mvc spring-boot

我是 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/

相关文章:

java - 生产者/消费者 : no producer/consumer should block other producer/consumer

java - 严重: Exception while loading the app : EJB Container initialization error

c# - 在数据库中存储/检索 JSON 字符串,使其易于在代码中使用

javascript - 如何从innerHTML对象获取值?

java - Spring Security oauth2,为什么我的 auth/token 对 CLIENT 进行了身份验证但返回 404?

java - java.util.Timer 中的引用应该是最终的吗?

java - JSP过滤非法url直接访问

json - 将 datetime.datetime 对象序列化为 JSON

Spring env,我还应该在新项目中使用 Hystrix

java - CORS 不允许使用 POST 方法