我们可以在单个 servlet 中执行 getwriter 和 Forward 操作吗
假设我的表单称为 servlet。我会在里面做一些处理。在 servlet 中,我想在页面上打印一些内容。为此,我
PrintWriter out=response.getWriter();
out.println("some text here");
在 servlet 中进一步使用了一些表单处理,效果很好,之后我希望将 servlet 转发到 jsp 页面。为此我使用了
RequestDispatcher rd = request.getRequestDispatcher("/somepage.jsp");
rd.forward(request, response);
问题就在这里。文本
some text here
被打印,但 servlet 不会将请求转发到 jsp 页面,就好像代码没有运行一样。
Lets say my form called a servlet. I would do some processing in it. In the servlet i want to print something on the page. for that i used
PrintWriter out=response.getWriter();
out.println("some text here");
then further in the servlet i did some more form processing which works fine and after that i want the servlet to be forwarded to a jsp page. For this i used
RequestDispatcher rd = request.getRequestDispatcher("/somepage.jsp");
rd.forward(request, response);
the problem comes here. the text
some text here
gets printed, but the servlet doesn't forward request to the jsp page, as if the code doesn't run.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,你不能那样做。如果您调查过服务器日志文件,那么您应该注意到类似
IllegalStateException: 无法转发,响应已提交
的内容。向响应写入内容将提交响应并将响应标头和写入的字节发送到客户端。但是之后发送转发可能需要更改响应标头,而这不再可能,因为这些标头已经发送。服务器无法获取已发送的标头和字节并重做响应。这是一个没有回头路的点。
在 servlet 内发出一些 HTML/模板输出也被认为是不好的做法。您应该在 JSP 中执行此操作。您可以将消息存储在请求范围中,并在 JSP 中使用 EL 来显示它。
例如:
在
somepage.jsp
中No, you cannot do that. If you have investigated the server log files, then you should have noticed something like as
IllegalStateException: cannot forward, response already committed
.Writing something to the response will commit the response and send the response headers and the written bytes to the client side. But sending a forward afterwards might require a change in the response headers and that's not possible anymore because those are already sent. The server cannot grab the already sent header and bytes back and redo the response. It's a point of no return.
It's also considered bad practice to emit some HTML/template output inside a servlet. You should be doing this in a JSP. You can store the messages in the request scope and use EL in JSP to display it.
For example:
and in
somepage.jsp