RequestDispatcher - 何时提交响应?

Jef*_*ine 7 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();
}
Run Code Online (Sandbox Code Playgroud)

}

Tal*_*ala 4

因为你还没有打电话flush

如果您还没有冲水,转发前所有内容都会被清除。否则,你会得到你所期望的例外。

正如文档中所示

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

应该在响应提交给客户端之前调用forward(在刷新响应正文输出之前)。如果响应已提交,则此方法将抛出 IllegalStateException。响应缓冲区中未提交的输出在转发之前会自动清除。