Spring @RequestMapping header with equals

这一生的挚爱 提交于 2019-12-24 14:06:30

问题


I want to use Springs @RequestMapping with the header attribute to detect an Accept header with the value application/json;version=1.*. The plan is to have another method mapped similarly for version 2 which will have the value application/json;version=2.*.

Spring seems to be ignoring the version value. I'm guessing it's treating the equals sign as another header attribute.

Is there a way around this?

Side notes:

  1. I can't update the Spring version to support the consumes attribute
  2. I can't change the format the request header will come in

回答1:


It seems that the spring requestmapping ignores media type parameters. You can work around this by manually routing the request to your preferred endpoint.

@RequestMapping(value = "/", headers = "Accept=application/json")
@ResponseBody
String request(@RequestHeader HttpHeaders headers){
    for(MediaType mediaType : headers.getAccept()){
        if(mediaType.isCompatibleWith(MediaType.APPLICATION_JSON)){
            if(mediaType.getParameter("version").startsWith("1.")){
                return v1();
            }else if(mediaType.getParameter("version").startsWith("2.")){
                return v2();
            }
        }
    }
    return "error";
}


来源:https://stackoverflow.com/questions/34425316/spring-requestmapping-header-with-equals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!