在提交响应后,是否可以从servlet过滤器转发或重定向? [英] Is it possible to forward or redirect from a servlet filter after the response has been committed?

查看:135
本文介绍了在提交响应后,是否可以从servlet过滤器转发或重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

逻辑是过滤器被击中,条件不成立,因此它通过过滤器链。提交响应后,过滤器被命中,条件现在为真(设置了请求属性)。它进入执行转发,但页面永远不会转发。我知道这与提交的响应有关,因为我测试了它在第一次到达链之前转发的不同逻辑,并且它确实成功转发。

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);
    }
}

我的部署描述符示例:

<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>


推荐答案

<$ c $的已提交状态c> HttpServletResponse 实际上是一种说明响应头是否已写入底层套接字的方法。 已提交的响应已经(至少)编写了第一行。由于响应的第一行包含状态代码,因此您无法更改已提交响应的状态代码......这意味着将状态更改为3xx以进行重定向为时已晚。同样,由于您已经开始发送回复,因此无法进行本地转发。

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 to do a redirect. Similarly, you cannot do a local forward because you've already started sending the response.

这篇关于在提交响应后,是否可以从servlet过滤器转发或重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆