栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

解决SpringMVC同时接收Json和Restful时Request里有Map的问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解决SpringMVC同时接收Json和Restful时Request里有Map的问题

现在正在做的项目要将旧系统实现微服务,用 SpringBoot 来做,有时候同一个 Request 就要同时接收来自 ajax 的 Json 数据和 Restful 的数据,如果里面还包含 Map 怎么办呢? 最近就只想出了这种办法,仅供参考。如有错误请指正,谢谢。

代码

Json 数据

{
 "fieldMap": 
 {
  "middleName": "1",
  "mailingAddress": "2",
  "mobilenumber": "3" 
 }
}

Restful URL

//注意要让 @ModelAttribute RequestDTO 自动封装成 Map 的话要像下面的format。
http://localhost:8080/hello?fieldMap[middleName]=1&fieldMap[mailingAddress]=2&fieldMap[mobilenumber]=3

Request DTO

public class RequestDTO {

 private HashMap fieldMap;

 public HashMap getFieldMap() {
  return fieldMap;
 }
 public void setFieldMap(HashMap fieldMap) {
  this.fieldMap = fieldMap;
 }
}

Spring Mvc 代码

//接收 Json 数据, consumes = "application/json" 来区分同一个请求是用json还是其他
@RequestMapping(method = { RequestMethod.POST },
   value = { "/hello" }, 
   consumes = "application/json")
public final void requestByJson(
  final HttpServletRequest httpRequest,
  final HttpServletResponse httpResponse,
  @RequestBody final RequestDTO requestDTO) {

 ...
}

//接收 Restful 数据, @ModelAttribute 将param配对成 RequestDTO
@RequestMapping(method = { RequestMethod.POST },
   value = { "/hello" })
public final void restfulRequest(
  final HttpServletRequest httpRequest, 
  final HttpServletResponse httpResponse,
  @ModelAttribute final RequestDTO requestDTO ){

 ...

 }

以上这篇解决SpringMVC同时接收Json和Restful时Request里有Map的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/140294.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号