Hello everyone. I have a question.

In a servlet, can we write something on page using

PrintWriter out=response.getWriter();

,then clearing the page and then also forward the request using

RequestDispatcher rd = request.getRequestDispatcher("/some jsp page");
 rd.forward(request, response);

I was trying to do this but for some reason forwarding part is not happening.

Recommended Answers

All 5 Replies

no answers?!!!

Because your question doesn't make sense. Explain properly, do not expect us to do guess work and what you trying to do.

Ok.sorry about that..Let me rephrase. 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 proccessing 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 doesnt forward request to the jsp page, as if the code doesnt run. I hope now I am clear enough.

As a servlet developer you need to make up your mind -- whether to do the processing in the servlet and use it for sending a response to the client OR add/update request/session/application scoped parameters and let some other managed component (another servlet/jsp page) handle the processing/response creation.

The HTTP servlet specification creates an abstraction over the HTTP request/response model. Once response is sent to the client, it can't be *revoked* and a new one be sent. When you say `out.println()`, you are effectively pushing the HTTP response to the client or more specifically "committing" the response (assuming that your output buffer is already full). After that, any attempts at `forwarding` your request to some other resource for processing gives an IllegalArgumentException.

Does your server log show any exception stack trace when you make your request?

commented: You know your craft +6

Thanks for the reply, I see what you mean. I had a feeling this is not good coding, thats why i wrote this to confirm.
I have not checked the logs yet. But I dont know ehy exception was not shown anywhere..not even in console

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.