开发者

can we do getwriter and forward in a single servlet

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 wo开发者_JS百科rks 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.


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:

request.setAttribute("message", "some message"); // Will be available as ${message}
request.getRequestDispatcher("/somepage.jsp").forward(request, response);

and in somepage.jsp

<p>Message: ${message}</p>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜