RequestDispatcher - 何时提交响应?

时间:2013-08-14 09:19:34

标签: java servlets commit requestdispatcher

我在学习RequestDispatcher时正在编写一些基本代码。我知道当调用rd.forward()时,控制(和响应处理)将被转发到路径中指定的资源 - 在本例中是另一个servlet。但是,由于代码中前面的out.write()语句,为什么这段代码不会抛出IllegalStateException(不是我想要的)?

我想我真正要问的是,这些out.write()语句将如何或何时提交?

谢谢, 杰夫

public class Dispatcher extends HttpServlet{
  public void doGet(HttpServletRequest request, HttpServletResponse response)
           throws IOException, ServletException{

    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    out.write("In Dispatcher\n");

    String modeParam = request.getParameter("mode");
    String path = "/Receiver/pathInfo?fruit=orange";
    RequestDispatcher rd = request.getRequestDispatcher(path);
    if(rd == null){
        out.write("Request Dispatcher is null. Please check path.");
    }
        if(modeParam.equals("forward")){
            out.write("forwarding...\n");
            rd.forward(request, response);
        }
        else if(modeParam.equals("include")){
            out.write("including...\n");
            rd.include(request, response);
        }
    out.flush();
    out.close();
}

}

3 个答案:

答案 0 :(得分:4)

因为您尚未调用flush

如果你没有脸红,那么在转发之前一切都会被清除掉。否则,你会得到一个预期的豁免。

docs:

一样
  

对于通过getRequestDispatcher()获取的RequestDispatcher,   ServletRequest对象的路径元素和参数调整为   匹配目标资源的路径。

     应该在响应提交之前调用

forward   客户端(在刷新响应正文输出之前)。如果回应   已经提交,这个方法抛出了   IllegalStateException异常。 响应缓冲区中未提交的输出是   在前锋之前自动清除。

答案 1 :(得分:3)

阅读docs

  

flush()上调用PrintWriter会提交回复。

现在,根据你的好奇心,为什么没有IllegalStateException抛出。这只是因为PrintWriter.flush()不会抛出此异常或任何已检查的异常。并且,我们知道在调用rd.forward()时未提交响应,因为flush()在方法的后面出现。

答案 2 :(得分:1)

你没有在转发之前调用flush()。所以它没有显示任何异常。如果在转发请求之前写入flush(),那么它将抛出异常。

当我们调用flush()时,缓冲区中的所有内容都会被发送到浏览器并清除缓冲区。

在以下场景中,我们将获得例外。

response.getWriter().print('hello...');  
response.getWriter().flush();  
request.getRequestDispatcher("/index.").forward(request, response);