繁体   English   中英

Spring MVC将json或编码参数映射到@RequestParam

[英]Spring MVC map json or encoded parameters to @RequestParam

我有一个使用此方法的Spring控制器:

@RequestMapping(value="/testUrl", method = RequestMethod.POST, 
    consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public @ResponseBody String method(@RequestParam String propertyId, @RequestParam String comments) {...}

我希望这能够处理

"propertyId=123&comments=something"

和json等价物:

{"propertyId":"123","comments":"comment"}

仅目前,表单URL编码(第一个请求主体)有效。 使这两种方法都起作用的最佳方法是什么?

您可以使用@RequestParam像处理第一个一样处理url参数 使用@RequestBody处理请求的主体 ,然后将要解析的值设置为包装类,例如

public @ResponseBody String handleMyDTO(@RequestParam String propertyId, @RequestParam String comment, @RequestBody MyDTO dto){//impl goes here}

MyDTO在哪里

public class MyDTO {
     //use @JsonPropery("my_custom_prop_name") if you want to use a     //different name to map the field into json
     private String propertyId;
     private String comment;
     //getters setters default constructor
}

注意 @RequestBody可以同时使用@Valid批注进行验证

如果要向控制器发送表单内容,则可能需要使用@ModelAttribute MyDTO dto而不是@RequestParam字段来完成

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM