繁体   English   中英

如何从servlet到jsp获得响应?

[英]How to get response from servlet to jsp?

我正在尝试从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

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

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

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

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

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

我想你应该使用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. 

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

这就是为什么在执行RequestDispatcher.forward()之后,您无法redirectdo operation which adds header or response content

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM