gpt4 book ai didi

java - RequestDispatcher - 何时提交响应?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:06:12 28 4
gpt4 key购买 nike

我在学习 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();
}

最佳答案

因为你还没有调用flush

如果您还没有刷新,转发之前所有内容都会被清除。否则,您会得到预期的结果。

docs:

For a RequestDispatcher obtained via getRequestDispatcher(), the ServletRequest object has its path elements and parameters adjusted to match the path of the target resource.

forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.

关于java - RequestDispatcher - 何时提交响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227713/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com