Popular Posts

Thursday, March 3, 2016

Disabling Default Spring File Extension Response Mapper


The other day I was trying to implement a file download functionality, which takes the filename as a path variable and returns you the uploaded file metadata. In my case file extension was not matching the response type and Spring was throwing this exception below:

 org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation  

The problem was that Spring treats the part after the dot in the url as a file extension and was trying to determine the matching response type and didn't find any matching converter, which result in throwing the above exception.

To solve we can simply disabled the default suffix-based content negotiation and can use the produce annotation to tell Spring what response type should be used.

Code:

1:  @Configuration  
2:  public class ContentNegotiationConfig extends WebMvcConfigurerAdapter {  
3:    @Override  
4:    public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {  
5:      // Turn off suffix-based content negotiation  
6:      configurer.favorPathExtension(false);  
7:    }  
8:  }  

Note: It is important to use the configuration annotation so this property can be set before starting the spring container.

No comments: