Restful API SpringMVC多版本實現

項目要做多版本控制,於是百度了一下,發現有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);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章