spring mvc如何修改请求头和请求体

业务

创建优惠券

spring mvc controller

@RequestMapping(method = RequestMethod.POST)
public Result<String> create(@Valid @RequestBody CouponModel model) 

但此时默认只支持Content-Type: application/json

而客户端同事要求支持Content-Type: application/x-www-form-urlencoded, 但似乎没办法同时支持application/jsonapplication/x-www-form-urlencoded?

能实现什么Spring接口使得能在进入Controller方法前将application/x-www-form-urlencoded的请求转成application/json的形式吗?

阅读 11.1k
3 个回答
两个方法,映射不同的Content-Type.参数绑定的方式分别使用@ModelAttribute和@RequestBody. 这种需求不常见

@PostMapping(value = "/testContentType", consumes = "application/x-www-form-urlencoded")
public String testContentType1(@ModelAttribute DTO invokeDTO) {
    return "1";
}

@PostMapping(value = "/testContentType", consumes = "application/json")
public String testContentType2(@RequestBody DTO invokeDTO) {
    return "2";
}

记得Request Mapping里有指定content type的参数

新手上路,请多包涵

可以这么写:
@RequestMapping(method = RequestMethod.POST, consumes={"application/json","application/x-www-form-urlencoded"})
这样的话这个mapping只支持这两个content-type类型的post请求。
另外也可以使用String[] headers这个参数(很容易猜到是过滤请求头,可以设置任何请求头为你只想要的),写法如下:
headers = {"content-type=application/json","content-type=application/x-www-form-urlencoded"},当然最好还是使用第一个,因为consumes就是为这个目的设计的.
来源:Spring FrameWork Reference Documentation Section 22.3.2 Mapping Requests With @RequestMapping ---Consumable Media Types
http://docs.spring.io/spring/...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进