Diana
Diana

Reputation: 1615

How to return response as Json from spring filter?

In spring rest, I need to send authentication error from doFilter() of my filter class. In response, I need to send json with fields like status, message, and errorCode. Kindly suggest how to achieve this. We are not using spring boot. Below is the sample response of the Authentication error:

{   
    "responseCode":" Error code",
    "responseMessage": "Some Error message",
    "responseStatus":"Fail"
}

Inside doFilter(), U am validating the token, if it's not valid I need to send the above sample response.

Upvotes: 7

Views: 18112

Answers (1)

cassiomolin
cassiomolin

Reputation: 130867

Assuming you have Jackson's ObjectMapper exposed as a Spring bean, you could use the following for a OncePerRequestFilter:

@Component
@RequiredArgsConstructor
public class MyFilter extends OncePerRequestFilter {

    private final ObjectMapper mapper;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws IOException {

        Map<String, Object> errorDetails = new HashMap<>();
        errorDetails.put("message", "Invalid token");

        httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

        mapper.writeValue(httpServletResponse.getWriter(), errorDetails);
    }
}

For a plain servlet Filter, the solution would be much the same:

@Component
@RequiredArgsConstructor
public class MyFilter implements Filter {

    private final ObjectMapper mapper;

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException {

        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        Map<String, Object> errorDetails = new HashMap<>();
        errorDetails.put("message", "Invalid token");

        httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

        mapper.writeValue(httpServletResponse.getWriter(), errorDetails);
    }

    @Override
    public void destroy() {

    }
}

The above examples rely on constructor injection and use Lombok's @RequiredArgsConstructor to generate a constructor that receives values for the fields marked with final.

You also could replace the Map<String, Object> for any arbitrary POJO, according to your needs.

Upvotes: 31

Related Questions