TeNNoX
TeNNoX

Reputation: 2075

Spring - disable path extension truncation / content negotiation

In SpringBoot v2.1.3, when setting up a @RequestMapping like this:

@GetMapping("/assets/{name}")
public AssetInfo assetInfo(@PathVariable("name") String name) {
  return getAssetInfo(name);
}

a query to /assets/image123.jpg would cause:

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
    at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:219)

because it assumes the produced Content-Type must be image/jpeg.

Upvotes: 1

Views: 885

Answers (2)

TeNNoX
TeNNoX

Reputation: 2075

You can disable this in a WebMvcConfigurer - which will solve the problem of content negotiation - but Spring still excludes the extension from the PathVariable (id = "image123"). This can be disabled using setUseSuffixPatternMatch:

@EnableWebMvc
@Configuration
public class SpringConfigurationForMVC extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false);
    }
}

Upvotes: 4

Bruno Bossola
Bruno Bossola

Reputation: 1378

Thanks! Just adding to the answer from TeNNox the missing bits for an easier copy&paste :) I would have added a comment but you cannot write multiline code there.

@EnableWebMvc
@Configuration
public class SpringConfigurationForMVC extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false);
    }
}

Upvotes: 0

Related Questions