Search code examples
javaspringheaderrequest-mapping

Spring @RequestMapping header with equals


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

Solution

  • 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";
    }