Search code examples
xmlspringspring-mvckotlinrequest-mapping

SpringMVC RequestMapping: Adding .xml to controller path for xml response


/pets yields a json response. I'd like to use /pets.xml in order to yield an xml response, while maintaining @RequestMapping("pets") on the controller. I can use

@RequestMapping("/index") 
@RequestMapping("/index.xml") 

as a workaround, but that's not what I'm looking for.

@RestController
@RequestMapping("pets")
class PetController {
  /*code*/
  @RequestMapping(produces = arrayOf("application/json"))
    fun findPetsJson(): List<PetDto> {
      return petService.findAll()
  }
  // this results in /pets/.xml for the xml response. I'm aiming for /pets.xml
  @RequestMapping(".xml", produces = arrayOf("application/xml"))
    fun findPetsXml(): List<PetDto> {
      return petService.findAll()
    }
  }

Solution

  • By default the Spring MVC RequestMappingHandlerMapping will add multiple mappings for your @RequestMapping annotated methods (or classes). It will next to the configured one, add one ending with .* so that it will match extensions as well.

    So in your case /pets.xml is already supported by the /pets.* mapping which is created by default. Your produces now only limits the accepting requests based on the Accept request header.

    By default the file extension takes precedence over the Content-Type header.