解决SpringMVC同时接收Json和Restful时Request里有Map的问题
现在正在做的项目要将旧系统实现微服务,用SpringBoot来做,有时候同一个Request就要同时接收来自ajax的Json数据和Restful的数据,如果里面还包含Map怎么办呢?最近就只想出了这种办法,仅供参考。如有错误请指正,谢谢。
代码
Json数据
{
"fieldMap":
{
"middleName":"1",
"mailingAddress":"2",
"mobilenumber":"3"
}
}
RestfulURL
//注意要让@ModelAttributeRequestDTO自动封装成Map的话要像下面的format。 http://localhost:8080/hello?fieldMap[middleName]=1&fieldMap[mailingAddress]=2&fieldMap[mobilenumber]=3
RequestDTO
publicclassRequestDTO{
privateHashMapfieldMap;
publicHashMapgetFieldMap(){
returnfieldMap;
}
publicvoidsetFieldMap(HashMapfieldMap){
this.fieldMap=fieldMap;
}
}
SpringMvc代码
//接收Json数据,consumes="application/json"来区分同一个请求是用json还是其他
@RequestMapping(method={RequestMethod.POST},
value={"/hello"},
consumes="application/json")
publicfinalvoidrequestByJson(
finalHttpServletRequesthttpRequest,
finalHttpServletResponsehttpResponse,
@RequestBodyfinalRequestDTOrequestDTO){
...
}
//接收Restful数据,@ModelAttribute将param配对成RequestDTO
@RequestMapping(method={RequestMethod.POST},
value={"/hello"})
publicfinalvoidrestfulRequest(
finalHttpServletRequesthttpRequest,
finalHttpServletResponsehttpResponse,
@ModelAttributefinalRequestDTOrequestDTO){
...
}
以上这篇解决SpringMVC同时接收Json和Restful时Request里有Map的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。