views:

30

answers:

1

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.

A: 

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>
BalusC
thanks for the reply. I was trying to use this to print "processing your request" as the first response then the process with takes a long time then forward to the jsp page. Can you suggest me a way to do this without using AJAX.
karanits
Without using AJAX, you'll have to resort to a meta refresh page and the session scope. You can find an example in "Long Running Process" section of [this site](http://simple.souther.us/not-so-simple.html).
BalusC