Question

This question already has an answer here:

Is it possible to write a servlet filter to take inspect HTTP response codes?

I want to write a filter that will non-destructively inspect outgoing HTTP response codes. But, there does not seem to be a getResponseCode() like method on the Response object.

It is also not clear to me how unhandled exceptions from the servlet are supposed to be dealt with. I really don't want this filter to actually set anything. Passive is good.

Ideas?

(My other approach involves writing a custom Tomcat valve, but that is not so portable.)

Was it helpful?

Solution

you can wrap your outgoing response using HttpServletResponseWrapper:

class GetStatusWrapper extends HttpServletResponseWrapper {

    private int status;

    GetStatusWrapper(HttpServletResponse response) {
        super(response);
    }

    @Override
    public void setStatus(int sc) {
        super.setStatus(sc);
        status = sc;
    }

    public int getStatus() {
        return status;
    }
}

then in your filter:

public class GetStatusResponseFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, 
                         ServletResponse response, 
                         FilterChain filterChain) 
                            throws IOException, ServletException {
        GetStatusWrapper wrapper;
        wrapper = new GetStatusWrapper((HttpServletResponse) response);
        filterChain.doFilter(request, wrapper);
        System.out.println("status = " + wrapper.getStatus());
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}

OTHER TIPS

Would you consider writing a proxy wrapper around the original response class? This way you can handle events / method calls on the object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top