为什么只打印“您会看到目标?”?

时间:2019-06-13 07:09:08

标签: java html servlets

呼叫者servlet:

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("<HTML>");
    out.println("<BODY>Will you see the source?");
    out.println("</BODY></HTML>");
    RequestDispatcher disp=req.getRequestDispatcher("/Test");
    disp.forward(req, res);
    out.close();
}

("/Test"):
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<HTML><TITLE>The Test</TITLE>");
    out.println("<BODY>Will you see the target?");
    out.println("</BODY></HTML>");
    out.close();
}

为什么只打印“您会看到目标?”?它不应该打印“您会看到源吗?”也是因为PrintWriter放置在前进位置之前?

2 个答案:

答案 0 :(得分:1)

阅读文档,即forward的Javadoc:

  

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

答案 1 :(得分:0)

它实际上会打印“您会看到源吗?”文本。但是在打印后,对RequestDispatcher进行了初始化,并对“ / Test”调用了forward()。这样做会将请求转发到URL“ / Test”,从而加载新页面。