Brian
Brian

Reputation: 1989

How do I return a JSON response message and an HTTP error code from javax.servlet.filter doFilter method?

I have created a servlet filter for our application that processes REST requests. I have annotated the web.xml and created my filter. The filter works well, but only returns a JSON text message. I need to also return a 405 HTTP status code. When I perform my tests, and one fails, I have a simple PrintWriter that prints the error message:

public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse apiResponse = (HttpServletResponse) response;
        apiResponse.setContentType("application/json");
        htmlOut = apiResponse.getWriter();
        mainErrorObject = new JSONObject();
        if(true){
            htmlOut.println(mainErrorObject.toString());
        }
        htmlOut.close();
    }
}

So, like I said, how do I return both the JSON text message AND the HTTP error code?

Upvotes: 0

Views: 2142

Answers (1)

Swapnil
Swapnil

Reputation: 8328

ServletResponse implements HttpServletResponse and it has a setStatus method, which sets the status code for the response.

setStatus

void setStatus(int sc)

Sets the status code for this response. This method is used to set the return status code when there is no error (for example, for the status codes SC_OK or SC_MOVED_TEMPORARILY). If there is an error, and the caller wishes to invoke an error-page defined in the web application, the sendError method should be used instead. The container clears the buffer and sets the Location header, preserving cookies and other headers.

Upvotes: 1

Related Questions