Spring MVC 如何从spring filter返回Json响应?

mjqavswn  于 2023-10-24  发布在  Spring
关注(0)|答案(1)|浏览(178)

在spring rest中,我需要从我的filter类的doFilter()发送authentication error。作为响应,我需要发送带有status,message和errorCode等字段的json。请建议如何实现这一点。我们没有使用spring Boot 。下面是Authentication error的示例响应:

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

doFilter()中,你正在验证令牌,如果它无效,我需要发送上面的示例响应。

mefy6pfw

mefy6pfw1#

假设您将Jackson的ObjectMapper公开为Spring bean,您可以对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);
    }
}

对于普通servlet Filter,解决方案大致相同:

@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() {

    }
}

上面的示例依赖于构造函数注入,并使用Lombok的@RequiredArgsConstructor生成一个构造函数,该构造函数接收标记为final的字段的值。
您还可以根据需要为任何POJO替换Map<String, Object>

相关问题