2017-06-22 47 views
0

我正在尝试创建一个POST servlet,该请求应该使用JSON请求调用。以下应该工作,但不。可能缺少什么?如何在Spring Servlet中将JSON POST参数作为@RequestParam接受?

@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"

+1

使用@RequestBody参数,会给结果 –

+0

创建'@ GetController'和发送它作为一个GET查询字符串的作品,但我需要POST + JSON。 – membersound

+0

@PawanPandey如果我在两个参数上都使用'@ RequestBody',则会出现以下错误:'“无法创建响应:org.springframework.http.converter.HttpMessageNotReadableException:缺少必需的请求主体:public java.lang。字符串MyServlet.test(java.lang.String,java.lang.String [])“' – membersound

回答

4

一般我不POST方法传递的请求PARAM。取而代之的是,我使用的是DTO它通过在身体像:

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

然后,你需要创建ItemDTO与必要的字段一个POJO。

+0

没有其他的机会吗?如果可能的话,我想避免创建一个dto(因为我希望能够使用例如'@RequestParam(required = false,defaultValue =“some”)'在POST参数 – membersound

+1

上您可以使用hashmap但你需要使用'@ RequestBody'来接受post参数 –

+0

否则将json字符串化并传递post url的查询字符串然后在地图中作为@RequestParam得到 –

0

除了@stzoannos答案,如果你不想为json对象创建POJO,你可以使用google GSON库将json解析为JsonObject类,它允许通过get和set方法使用参数。

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