22
Июл
2021

Правильно -ли использовать в методе по несколько раз метод doFilter() для того ,чтобы изменять тело ответа?

Пример кода

@Slf4j
@Order(3)
@WebFilter(TOKEN_ENDPOINT_URL)
public final class Helper implements Filter {

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

    ContentCachingRequestWrapper reqWrapper = new ContentCachingRequestWrapper((HttpServletRequest) servletRequest);
    ContentCachingResponseWrapper resWrapper = new ContentCachingResponseWrapper((HttpServletResponse) servletResponse);
    
    filterChain.doFilter(reqWrapper, resWrapper);
    int status = resWrapper.getStatus();

    if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        ResponseDto ResponseDto = new ResponseDto();
        ResponseDto.setError_description("No connection to server.");
        ResponseDto.setError("server_error");

        resWrapper.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
        byte[] responseToSend = restResponseBytes(ResponseDto);
        resWrapper.getResponse().getOutputStream().write(responseToSend);
        return;
    } else {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

    private byte[] restResponseBytes(ResponseDto eErrorResponse) throws IOException {
        String serialized = new ObjectMapper().writeValueAsString(eErrorResponse);
        return serialized.getBytes();
    }
}

Источник: https://ru.stackoverflow.com/questions/1307849/%D0%9F%D1%80%D0%B0%D0%B2%D0%B8%D0%BB%D1%8C%D0%BD%D0%BE-%D0%BB%D0%B8-%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C-%D0%B2-%D0%BC%D0%B5%D1%82%D0%BE%D0%B4%D0%B5-%D0%BF%D0%BE-%D0%BD%D0%B5%D1%81%D0%BA%D0%BE%D0%BB%D1%8C%D0%BA%D0%BE-%D1%80%D0%B0%D0%B7-%D0%BC%D0%B5%D1%82%D0%BE%D0%B4-dofilter-%D0%B4%D0%BB%D1%8F-%D1%82%D0%BE%D0%B3%D0%BE

Тебе может это понравится...

Добавить комментарий