如何从servlet到jsp获得响应?

时间:2012-06-06 07:24:03

标签: java jsp servlets response

我正在尝试从servlet使用获得响应

request.setAttribute(error, error);
request.getRequestDispatcher("http://localhost:8080/redicted_test/Home.jsp").forward(request, response);

String redictedURL="http://localhost:8080/redicted_test/Home.jsp";
response.sendRedirect(redictedURL);

但是得到错误

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

我明白我发送回复两次,但我怎么能做到呢? 你能告诉我最简单的方法吗?

4 个答案:

答案 0 :(得分:1)

您已转发请求,现在正在重定向

request.getRequestDispatcher("http://localhost:8080/redicted_test/Home.jsp").forward(request, response);
..
response.sendRedirect(redictedURL);

如果你想从servlet设置一些属性并需要在jsp上显示它,那么只需将请求转发给jsp并显示那些属性

答案 1 :(得分:1)

在您的示例中,您已执行了jsp,并且已在回复缓冲区中发送了呈现的jsp。由于您已开始发送响应,因此发送了响应标头。但就在那之后你想发送重定向,重定向是一种标题操作(更改http状态代码和位置标题)。

答案 2 :(得分:1)

我认为你应该使用include而不是forward ..

forward is used to forward a request, that is control is transfered to the
new servler/jsp. u shud take care to not put any our.println() statements 
in the servlet from where u plan to call forward method. in fact u cant even 
fire response.getWriter() method in this case. u can only do that in the servlet
to which the control is bein fwded 

如果要将请求转发给另一个servlet或JSP,切勿将任何内容写入响应。例如,如果Servlet1将请求转发给Servlet2,Servlet1不应该将任何内容写入响应,也不应该调用response.getOutputStream()方法。这是不允许的,无论servlet1写入响应的是什么都不会输出,否则您将获得IllegalStateException

include - means that the new servlet/jsp will be procesed and any
out.println()/html stuff will be included and then control will come
back to the servlet/jsp that called include method. 

答案 3 :(得分:0)

RequestDispatcher.forward()之后,响应将被提交并关闭。您无法在响应中写入任何标头/内容。

这就是为什么在redirect之后你不能do operation which adds header or response contentRequestDispatcher.forward()

您拥有的替代方案是使用include而不是forward。

但是,我不明白你的用例。您正在转发并重定向到同一页面。