Restful API SpringMVC多版本實現
阿新 • • 發佈:2019-02-08
專案要做多版本控制,於是百度了一下,發現有3種常用的實現方式。
1.直接在url中新增版本資訊,但是不符合restful要求
url : http://localhost:8080/multiversion/v1/print
2.在content type中新增
url: http://localhost:8080/multiversion/print
Content-Type:application/json; version=2.0
3.自定義http請求頭
url: http://localhost:8080/multiversion/print
version:v2
第二種沒百度到,就選擇了第三種,我們可以通過Ajax方法中的beforeSend
$.ajax({
type:"post",
url:"http://localhost:8080/multiversion/print,
dataType:"json",
data:{},
beforeSend:function(xhr){
xhr.setRequestHeader("version", "v2");
},
success:function(data) {
$("#sign").val(data);
}
})
這樣在controller中的@RequestMapping的屬性headers中寫明版本即可。
@RequestMapping(headers = "version=v1",value = "print",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
@ResponseBody
public ReturnResultUtil printV1(HttpServletRequest req) throws IOException {
String version = req.getHeader("version");
logger.info("this is "+ version);
Map map = new HashMap();
map.put("info","this is v1");
return new ReturnResultUtil(1,"列印成功",version);
}
@RequestMapping(headers = "version=v2",value = "print",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
@ResponseBody
public ReturnResultUtil printV2(HttpServletRequest req,String data) throws IOException {
String version = req.getHeader("version");
logger.info("this is "+ version);
Map map = new HashMap();
if(data == null || "".equals(data)){
return new ReturnResultUtil(0,"data不能為空");
}
map.put("info","this is v2");
map.put("params",data);
return new ReturnResultUtil(1,"列印成功",map);
}
SpringMVC註冊request handler時把headers也放進去了(可以看啟動日誌)。
雖然這樣各自版本分的很清楚,也便於維護管理,但是每個方法都要註明版本號,如果兩個版本只有很少的介面是不一樣的,就會有大量重複的程式碼。
所以也可以通過在方法內部獲取請求頭資訊,然後做不同的處理,對於不同版本執行相同方法的直接不做處理。
@RequestMapping(value = "print",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
@ResponseBody
public ReturnResultUtil printLog(HttpServletRequest req,String data) throws IOException {
Map map = new HashMap();
String version = req.getHeader("version");
logger.info("this is "+ version + " and params is " + data);
//v1
if("v1".equals(version)){
map.put("info","this is v1");
return new ReturnResultUtil(1,"列印成功",map);
//v2
}else if("v2".equals(version)){
if(data == null || "".equals(data)){
return new ReturnResultUtil(0,"data不能為空");
}
map.put("info","this is v2");
map.put("params",data);
return new ReturnResultUtil(1,"列印成功",map);
}
return new ReturnResultUtil(1,"列印成功",map);
}