Reputation: 856
First, I am a new to Spring and this is my first attempt to write a REST based application using Spring.
I am planning to use Json both request parameters and in responses. This brings me to two questions.
Is there a way to globally set produces="application/json"
as default for all my mvc controllers responses.
If anyone sends a request and expects a result in other format than application/json
, I would like to return a error message. I guess this i a interceptors responsibility but understand how to set up the check.
Upvotes: 1
Views: 1617
Reputation: 36767
While there's no way to set produces
globally and, as Tomasz suggested it's usually easier to leave content negotiation to spring, it's also quite easy to implement the functionality as an interceptor.
Basically you need to return 415 status code on any request that doesn't have Accept
header with application/json
as value.
So first implement the interceptor:
public class WrongAcceptHeaderInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if (!"application/json".equals(request.getHeader("Accept"))) {
//you can change or omit the message
response.sendError(SC_UNSUPPORTED_MEDIA_TYPE, "Your error message");
// return false to skip further processing
return false;
}
}
}
and then register it in your context:
<mvc:interceptors>
<bean class="foo.bar.baz.WrongAcceptHeaderInterceptor" />
</mvc:interceptors>
Upvotes: 0
Reputation: 340733
It's actually even simpler. You just return Java object from your controller and Spring will figure out which format to use based on Accept
header:
@ResponseBody
public MyPojo noView(@RequestBody request) {
return new MyPojo();
}
The same is done for requests - Spring MVC will do its best to convert from request body to request
object. Once it is configured (e.g. you need jackson*.jar
on your CLASSPATH to handle JSON), it just works.
Also since you get XML for free, there is no point in restricting your endpoint to JSON. If user requests some other format, Spring will send appropriate error message for you (Bad request?)
Upvotes: 2