How to handle request header with Filter

3

How to change, remove, or add header of a request to a Web application using Filter ?

    
asked by anonymous 20.06.2015 / 17:56

1 answer

3

To retrieve a header from the HTTP request you can use the methods getHeader , getHeaders , as well as other utilities such as getDateHeader

Already to add or change is a little more work, since directly you can not do this. For this you need a wrapper / decorator that will have custom headers , but remember, the original request headers will not change, you is only decorating the request and holding in this wrapper the changed and included headers.

To facilitate a wrapper base you can now extend it, HttpServletRequestWrapper . From it we will change the way the header is obtained, so we will overwrite getHeader and getHeaderNames .

So let's build a CustomHttpServletRequestWrapper , something like this:

public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final Map<String, String> headers = new HashMap<>();

    public CustomHttpServletRequestWrapper(final HttpServletRequest request) {
        super(request);
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        final HttpServletRequest request = (HttpServletRequest) this.getRequest();
        final List<String> list = new ArrayList<>();

        list.addAll(Collections.list(request.getHeaderNames()));
        list.addAll(headers.keySet());

        return Collections.enumeration(list);
    }

    @Override
    public String getHeader(final String name) {
        if (headers.containsKey(name)) {
            return headers.get(name);
        }
        return super.getHeader(name);
    }

    public void addHeader(final String name, final String value) {
        headers.put(name, value);
    }

}

Notice that we are using a map, so I am assuming that we will only have one value for each header name, key of the map. You can add another type of data to allow repeated names for headers if needed.

Your filter would look something like this:

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        final CustomHttpServletRequestWrapper wrapper = new CustomHttpServletRequestWrapper(httpRequest);
        wrapper.addHeader("CUSTOM-HEADER", "value");
        chain.doFilter(wrapper, response);
    } else {
        chain.doFilter(request, response);
    }
}

This wrapper considers only requests HTTP , that is, they have headers by default. If you need not only HTTP requests, but all other ServletRequest take a look at ServletRequestWrapper , you can keep headers for them also similarly as we did in CustomHttpServletRequestWrapper .

    
20.06.2015 / 19:18