编写mock接口的过程中,合作方给的接口文档约定了所有post请求必须使用json格式传递参数,那么针对这样的约定该如何做呢?
Spring 3.X系列增加了新注解@RequestBody
它的作用:
i)该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析(将HTTP请求正文转换为适合的HttpMessageConverter对象,HttpMessageConverter接口,需要开启<mvc:annotation-driven />), 然后把相应的数据绑定到要返回的对象上;
ii)再把HttpMessageConverter返回的对象数据绑定到controller中方法的参数上。
POST模式下,使用@RequestBody绑定请求对象,Spring会帮你进行协议转换,将Json、Xml协议转换成你需要的对象。
这个接口的请求方式是:POST /vehicle
请求参数 字段名 类型 必选 描述 license_no string 是 车牌号 license_owner string 是 车主姓名 city_code number 是 投保城市代码执行代码:
package com.mockCommon.controller.mock.youbi; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.mockCommon.constant.LogConstant; import com.mockCommon.service.mock.youbi.impl.SearchCarModelMockServiceImpl; @Controller public class SearchCarModelMockController { @Autowired private SearchCarModelMockServiceImpl searchCarModelMockServiceImpl; @RequestMapping(value = "/vehicle", method = RequestMethod.POST) @ResponseBody public String searchCarModel(@RequestBody Map<String, Object> params){ LogConstant.runLog.info("[JiekouSearchCarModel]parameter license_no:" + params.get("license_no") + ", license_owner:" + params.get("license_owner") + ", city_code:" + params.get("city_code")); String result = null; if(params.get("license_no")==null || params.get("license_owner")==null|| params.get("city_code")==null){ return "传递参数不正确"; } result = searchCarModelMockServiceImpl.getResult(params.get("license_no").toString(), params.get("license_owner").toString(), params.get("city_code").toString()); return result; } }执行结果: