views:

38

answers:

2

The logic is that the filter gets hit, the condition is not true, so it goes through the filter chain. After the response is committed, the filter gets hit, and the condition is now true (a request attribute was set). It goes in to execute the forward, but the page never forwards. I know this has something to do with the response being committed because I tested different logic where it forwards before it hits the chain for the first time, and it does forward successfully.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest)request;

    if (some condition equals true) {
        httpServletRequest.getRequestDispatcher("/home.jsp").forward(request, response);
        return;
    } else {
        chain.doFilter(request, response);
    }
}

Example from my deployment descriptor:

<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>com.filters.MyFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
    <dispatcher>REQUEST</dispatcher>  
    <dispatcher>FORWARD</dispatcher> 
</filter-mapping>
+2  A: 

No, that's not possible. When a response is committed, then it means that the headers and (partial) content is already been sent to the client (webbrowser). This is a point of no return. You cannot change the target page of the response anymore. You cannot take the sent bytes back.

You need to rearrange your logic so that you never send/commit a response until it's clear what target page you'd like to forward/include/redirect.

BalusC
+3  A: 

The "committed" status of an HttpServletResponse is really a way of saying whether the response headers have been written to the underlying socket. A "committed" response has had (at least) the first line written. Since the first line of the response contains the status code, it follows that you cannot change the status code of a committed response ... and that means it is too late to change the status to 3xx do a redirect. Similarly, you cannot do a local forward because you've already started sending the response.

Stephen C