简体   繁体   中英

How to specify a fallback request mapping in Spring Boot

We have an endpoint which can return different responses depending on the Accept header. In particular, it can return zip files, video files, or audio files.

Mapping 1:

@RequestMapping(value = "endpoint",
        method = RequestMethod.GET,
        produces = {"video/*", "audio/*"})

Mappping 2:

@RequestMapping(value = "endpoint",
        method = RequestMethod.GET, produces = {"application/zip", "*/*"})

This setup will take an Accept: video/* and go to mapping 1 (which is what we want). But, Accept: video/mp4 results in an java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path exception.

I would have expected that video/mp4 more closely matches mapping 1 and loads that. Indeed that is exactly what we do want.

We can remove the */* and then Accept: video/mp4 does go to mapping 1. However, we do need the */* to go to Mapping 2.

Why doesn't Accept: video/mp4 match Mapping 1 since this is a closer match?

Can we configure this endpoint to have a default method if no other accept header more closely matches? Then we could have mapping 1 only declare that it produces application/zip .

We are using Spring Boot 1.5.3.

Why not remove produces all together and generate the Content-Type within the method and also have an if condition to test the Accepts request header? You could call two different methods depending on the request header.

@RequestMapping(value = "endpoint", method = RequestMethod.GET)
public void doIt(HttpServletRequest request, HttpServletResponse response) {
  if (request.getHeader("Accept").matches("application/zip"))
    doZip();
  else
    doVideo();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM