javaservlet-filtersspring-filter

To send custom response object and response code from filter


I have a requirement to send 401 response status code and a custom object response from filter code as below:

res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED)

Using above code I am able to send code but not sure how to send custom object as well with above code.


Solution

  • You can use below code snap to write bytes into response.

    response.getOutputStream().write(responseToSend);
    

    Below Filter used to write error in json format.

    public class TestFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException {
    
            if(ANY CONDITION){
                //ANY POJO CLASS
                ErrorResponse errorResponse = new ErrorResponse();
                errorResponse.setCode(401);
                errorResponse.setMessage("Unauthorized Access");
    
                byte[] responseToSend = restResponseBytes(errorResponse);
                ((HttpServletResponse) response).setHeader("Content-Type", "application/json");
                ((HttpServletResponse) response).setStatus(401);
                response.getOutputStream().write(responseToSend);
                return;
            }
    
            //ANY OTHER BUSINESS LOGIC
            chain.doFilter(request, response);
        }
    
        @Override
        public void destroy() {
    
        }
    
        private byte[] restResponseBytes(ErrorResponse eErrorResponse) throws IOException {
            String serialized = new ObjectMapper().writeValueAsString(eErrorResponse);
            return serialized.getBytes();
        }
    }