Servlet过滤器修改标头值,servlet请求包装器无法正常工作

时间:2016-07-16 22:30:41

标签: spring servlet-filters

我正在尝试更改请求中的Content-Type标头,并在它到达我的Spring rest控制器之前将其更改为“application / json”。我创建了一个servlet请求包装器来更改值,但是当请求到达控制器时它仍然是“text / plain”。日志记录显示在更改doFilter();

之前标题值已更改

这是我的类扩展HttpServletRequestWrapper

NaN

这是我的过滤器:

class HttpServletRequestWritableWrapper extends HttpServletRequestWrapper {
private final Logger logger = org.slf4j.LoggerFactory.getLogger(HttpServletRequestWritableWrapper.class);
private final ByteArrayInputStream decryptedBody;

HttpServletRequestWritableWrapper(HttpServletRequest request, byte[] decryptedData) {
    super(request);
    decryptedBody = new ByteArrayInputStream(decryptedData);
}



@Override
public String getHeader(String name) {
    String headerValue = super.getHeader(name);
    if("Accept".equalsIgnoreCase(name))
    {
        logger.debug("Accept header changing :");
        return headerValue.replaceAll(
                MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE
        );
    }
    else if ("Content-Type".equalsIgnoreCase(name))
    {
        logger.debug("Content type change: ");
        return headerValue.replaceAll(MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE);
    }
    return headerValue;
}

@Override
public Enumeration<String> getHeaderNames() {
    return super.getHeaderNames();
}

@Override
public String getContentType() {
    String contentTypeValue = super.getContentType();
    if (MediaType.TEXT_PLAIN_VALUE.equalsIgnoreCase(contentTypeValue)) {
        logger.debug("Changing on getContentType():");
        return MediaType.APPLICATION_JSON_VALUE;
    }
    return contentTypeValue;
}


@Override
public BufferedReader getReader() throws UnsupportedEncodingException {
    return new BufferedReader(new InputStreamReader(decryptedBody, UTF_8));
}

@Override
public ServletInputStream getInputStream() throws IOException {
    return new ServletInputStream() {
        @Override
        public int read() {
            return decryptedBody.read();
        }
    };
}

1 个答案:

答案 0 :(得分:1)

看来getHeaders方法是在我的过滤器之后的其他地方调用的,而不是使用我更新的值返回标头。

我在我的HttpServletRequestWrapper中添加了这个覆盖,它现在正在工作:

@Override
public Enumeration<String> getHeaders(String name) {
    List<String> headerVals = Collections.list(super.getHeaders(name));
    int index = 0;
    for (String value : headerVals) {
        if ("Content-Type".equalsIgnoreCase(name)) {
            logger.debug("Content type change: ");
            headerVals.set(index, MediaType.APPLICATION_JSON_VALUE);
        }

        index++;
    }

    return Collections.enumeration(headerVals);
}