Restful API SpringMVC多版本实现

来源:互联网 发布:php扩展加密 编辑:程序博客网 时间:2024/05/24 07:38

项目要做多版本控制,于是百度了一下,发现有3种常用的实现方式。

1.直接在url中添加版本信息,但是不符合restful要求

url : http://localhost:8080/multiversion/v1/print

2.在content type中添加

url: http://localhost:8080/multiversion/printContent-Type:application/json; version=2.0

3.自定义http请求头

url: http://localhost:8080/multiversion/printversion: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")@ResponseBodypublic 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")@ResponseBodypublic 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);    }
原创粉丝点击