Kliver Max
Kliver Max

Reputation: 5299

How to get response from servlet to jsp?

I am trying get response from servlet use

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);

But get error

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

Im understand that im send response twice, but how i can do it else? Can u tell me simplest way?

Upvotes: 1

Views: 8560

Answers (3)

Houcem Berrayana
Houcem Berrayana

Reputation: 3080

In your example you have executed the jsp and the rendered jsp was sent in the response buffer. And since you have started to send the response, the response headers were sent. But just after that you wanted to send redirection and a redirection is a kind of headers manipulation (changes http status code and location headers).

Upvotes: 1

Ramesh PVK
Ramesh PVK

Reputation: 15446

After a RequestDispatcher.forward(), the response will be committed and closed. You cannot write any header/content to the response.

That is why you cannot redirect or do operation which adds header or response content after doing RequestDispatcher.forward().

The alternative you have is use include instead of forward.

But, i did not understand your use case. You are forwarding and redirecting to the same page.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240860

You already have forwarded the request and now you are redirecting it

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

If you want to set some attributes from servlet and need to display it on jsp, then just forward the request to jsp and display those attributes

Upvotes: 1

Related Questions