如何使用过滤器为ServletRequest设置协议

时间:2018-04-03 15:59:49

标签: java servlets servlet-filters

我有一个像这样的过滤器:

public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);
        String host = requestWrapper.getHeader("Host");
        String _protocol = requestWrapper.getProtocol(); // e.g. HTTP/1.1
        if(host == null || host.isEmpty()) {
            host = "127.0.0.1:8080";
        }
        System.out.println("====================================================");
        System.out.println("Updating Host: " + host);
        System.out.println("====================================================");
        requestWrapper.addHeader("Host", host);
        chain.doFilter(requestWrapper, response); // Goes to default servlet.
    }

我想知道是否可以修改过滤器内_protocol的协议(ServletRequest)?

1 个答案:

答案 0 :(得分:1)

您可以创建HttpServletRequestWrapper的子类并覆盖getProtocol。只要受影响的代码中的任何一个仅使用getProtocol方法来获取协议(而不是使用协议的内部值),那么您可以将ProtocolFixRequest替换为原始HttpServletRequest。预计。例如:

public class ProtocolFixRequest extends HttpServletRequestWrapper {

    private final String fixedProtocol;

    public ProtocolFixRequest(HttpServletRequest request, String protocol) {
        super(request);
        fixedProtocol = protocol;
    }

    @Override
    public String getProtocol() {
        return fixedProtocol;
    }
}

使用它:

HttpServletRequest fixedRequest = new ProtocolFixRequest(originalRequest, "myProtocol");
chain.doFilter(fixedRequest, response);