Search code examples
javaservlet-filters

how to modify a http header if already set?


I need to modify this header based on page contents.

eg: this is a contrieved example-since it was requested. I cannot go into the details of the specific header The servlet/page sets a header specialheader=xyz based on what backend system was accessed. If this specialheader is set the filter will modify it to xyz+abc. If the header is not set, the filter will set it to 123.

I could use a filter to create a wrapped HttpServletResponse and modify it on its way back. However, I am fuzzy on the details.

I know I have to prevent the output from being sent back to client before my filter does its job. In order to do this, do I need to pass it my own OutputStream and buffer the output?

Do I really need to do that ? can I avoid buffering the output which may put load on the server

The basic question is- if I need to modify the header AFTER the doFilter call, what is the minimum do I need to do ? Is there some other way of preventing the output from being committed such as overriuciding flush etc., ?


Solution

  • Just implement getHeader and getHeaderNames to ignore the header you want to discard and set the Wrapper as a filter.

    import java.io.ByteArrayOutputStream;
    import java.io.PrintWriter;
    import java.util.Collection;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpServletResponseWrapper;
    
    public class GenericResponseWrapper extends HttpServletResponseWrapper {
    
    
    
        public GenericResponseWrapper(final HttpServletResponse response) {
            super(response);    
        }
    
        @Override
        public String getHeader(String name) {
            // TODO Auto-generated method stub
            return super.getHeader(name);
        }
        @Override
        public Collection<String> getHeaderNames() {
            // TODO Auto-generated method stub
            return super.getHeaderNames();
        }
    }
    
    
    public class Wrapper implements Filter {
    
        @Override
        public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
            final HttpServletRequest httpRequest = (HttpServletRequest) request;
            final HttpServletResponse httpResponse = (HttpServletResponse) response;
                final GenericResponseWrapper wrapper = new GenericResponseWrapper(httpResponse);
                wrapper.getResponse().setCharacterEncoding("UTF-8");
    
                chain.doFilter(request, wrapper);
    }
    }