編寫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;
}
}
執行結果: