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?
response.setStatus(405)
– Alex Salauyou