I’m trying to serve an image in my application as a java.awt.BufferedImage object. When I attempt to perform a GET, here are the results:
- Accept:image/jpeg renders a valid picture
- Accept:*/* returns an HTTP 406
Here is the relevant part of my servlet-context.xml:
<beans:bean id="messageAdapter"
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<beans:property name="order" value="1" />
<beans:property name="messageConverters">
<beans:array>
<beans:bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
</beans:array>
</beans:property>
</beans:bean>
And here is my Controller:
@RequestMapping(value = "photo/{photoId:[0-9]+}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public BufferedImage getPhoto(
@PathVariable long photoId) {
return photoService.getPhoto(photoId);
}
MediaType.IMAGE_JPEG_VALUE is “image/jpeg”. It is my understanding that an accept header of */* would never generate a HTTP 406, which according to this page tells us that the caller doesn’t accept content of that type.
This is an issue because most browsers have “*/*” in their accept headers, and would not be able to view this image unless the user hard-coded the accept header.
Am I missing something here?
Thanks in advance.
Message converters are picky about the Accept header, and they have to be since they are applied to all handlers annotated with
@ResponseBody.A couple of ways you can get around this:
Option 1: Extend the BufferedImageHttpMessageConverter to handle
*/*as well, NOTE: this can have unintended consequences if you add other message-converters later on as all of a sudden, handlers you want to produce JSON starts producing images instead.Then use this instead of the normal BufferedImageHttpMessageConverter in your spring config.
Option 2: Create a filter or interceptor that is applied to your image requests and wrap the request in such a way the
Acceptheader looks likeimage/jpeginstead of*/*. This will “trick” spring into thinking that the client accepts jpeg and trigger the BufferedImageHttpMessageConverter.