So, let's have this simple controller:
@Controller
public class MyController {
private static final Logger logger = LoggerFactory.getLogger(MyController.class);
@RequestMapping(value="/entities", method = RequestMethod.GET)
public @ResponseBody ResultPojo getSomething() {
logger.info("getSometing");
return new ResultPojo();
}
}
...and the following context fragment:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Which basically means I want to be able to return nothing but json representations of the result bean, otherwise return 406.
If I send a GET request with accept=application/json
, everything works fine, a json representation is returned in the http response with the 200 Ok status.
If I send a GET request with accept=application/xml
, 406 is returned.
My problem in the second case is that even though 406 is returned eventually, the getSomething()
method is still called (which I can see in the log). While this is no big deal for GET methods, it can cause confusion for POST methods (the resource is altered, but 406 is returned).
Is there a simple way to tell SpringMVC to check the accept
header and return 406 before invoking the controller method? Or do I have to develop a custom http SpringMVC interceptor?
as far as I know there is no simpler method with SpringMVC. However, using standard JEE filters this is not very hard to do either. Just do something like:
and:
(didn't test the code, but it should be about right)