Spring GenericFilterBean getWriter()已被调用

时间:2018-06-26 11:31:55

标签: java spring

在运行时出现此异常:

Caused by: java.lang.IllegalStateException: `getWriter()` has already been called for this response

它在提供的令牌无效或过期时发生。到目前为止,一切都很好,但是通过响应的.getWriter()方法,我可以使用消息“无效或过期”进行响应 我该如何避免.getWriter()的回复,并同时显示此消息?

@Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
            throws IOException, ServletException, CustomException {
        HttpServletResponse response = (HttpServletResponse) res;
        String token = jwtTokenProvider.resolveToken((HttpServletRequest) req);

        boolean isTokenValid = jwtTokenProvider.validateToken(token);
        if (token != null && isTokenValid) {
            Authentication auth = token != null ? jwtTokenProvider.getAuthentication(token) : null;
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        if(token != null && !isTokenValid){
            ObjectMapper objectMapper = new ObjectMapper();
            response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(new CustomExceptionModel("Invalid or expired token!",HttpStatus.FORBIDDEN)));
        }
        filterChain.doFilter(req, res);
    }

当我使用getOutputStream()而不是getWriter()并将模型写成我得到的字节数

  

“语法错误”

作为回应。

0 个答案:

没有答案