I am writing a REST based web service. I need to return all the responses as JSON format. I have an interceptor to validate my authentication parameters. On authentication failure scenario, I have to return the error response in JSON format.
Currently i am doing
response.setHeader("Content-Type","application/json"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "{\"error\":\"Missing Authentication Parameters\"}");
The response body is coming as below.
JBoss Web/2.1.3.GA - Error report
HTTP Status 401 - {"error":"Missing Authentication Parameters"}
type Status report
message {"error":"Missing Authentication Parameters"}
description This request requires HTTP authentication ({"error":"Missing Authentication Parameters"}).
JBoss Web/2.1.3.GA
I need just the JSON string in response. Please help me.
You should probably be using spring-security for this. If you want to do it by hand, an alternative to using
sendErroron the response is to use spring MVC's @ExceptionHandler along with content negotiation to return JSON.First define an error class*:
And an exception:
Then in your controller you throw an exception at the appropriate time, catch it with
@ExceptionHandlerand return aResponseEntitycontaining anErrorinstance and the appropriate error code.*use getters/setters to please the java convention gods