【问题标题】:How to accept JSON POST parameters as @RequestParam in Spring Servlet?如何在 Spring Servlet 中接受 JSON POST 参数作为 @RequestParam?
【发布时间】:2017-11-25 10:22:43
【问题描述】:

我正在尝试创建一个POST servlet,应该使用JSON 请求调用它。以下应该有效,但无效。可能缺少什么?

@RestController
public class MyServlet {
    @PostMapping("/")
    public String test(@RequestParam String name, @RequestParam String[] params) {
        return "name was: " + name;
    }
}

JSON POST:

{
   "name": "test",
   "params": [
      "first", "snd"
   ]
}

结果:名称始终为空。为什么?

"Response could not be created: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'name' is not present"

【问题讨论】:

  • 使用@RequestBody 参数来给出结果
  • 创建一个 @GetController 并将其作为获取查询字符串发送是可行的,但我需要 POST + JSON。
  • @PawanPandey 如果我在两个参数上都使用@RequestBody,我会得到一个错误:"Response could not be created: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String MyServlet.test(java.lang.String,java.lang.String[])"
  • 有一个像 mydata{name;params[];} 这样的 pojo 类,并在控制器中编写 test(@RequestBody mydata) 并检查请求标头中的内容类型是否为 application/json

标签: java json spring spring-mvc


【解决方案1】:

除了@stzoannos 回答,如果您不想为json 对象创建POJO,您可以使用google GSON 库将json 解析为JsonObject 类,它允许通过与get 和set 方法相同的参数来工作。

JsonObject jsonObj = new JsonParser().parse(json).getAsJsonObject();
return "name is: " + jsonObj.get("name").getAsString();

【讨论】:

    【解决方案2】:

    一般来说,我不会在 POST 方法中传递请求参数。相反,我使用 DTO 在正文中传递它:

    @RequestMapping(value = "/items", method = RequestMethod.POST)
        public void addItem(@RequestBody ItemDTO itemDTO) 
    

    然后,您需要将 ItemDTO 创建为具有必要字段的 POJO。

    【讨论】:

    • 没有其他机会吗?如果可能的话,我想避免创建一个 dto(因为我希望能够在 POST 参数上使用例如 @RequestParam(required = false, defaultValue = "some")
    • 你可以使用hashmap来做,但是你需要使用@RequestBody来接受post参数。
    • 或者将 json 字符串化并传入 post url 的查询字符串,然后在地图中以 @RequestParam 的形式获取
    • 好的,作为替代方案,可以只使用@RequestBody Map mapmap.get("format"); map.get("params")。如果只有少数参数作为json传递,这样比较合适,所以这里不需要DTO。
    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 2022-08-20
    • 1970-01-01
    • 2019-01-21
    • 2014-04-01
    • 2022-01-13
    • 2015-09-17
    • 1970-01-01
    相关资源
    最近更新 更多