forward and sendRedirect issue. "Cannot call sendRedirect() after the response has been committed" [duplicate]

StackOverflow https://stackoverflow.com/questions/18078801

Question

i want to implement this..
In my page1.jsp i have a link and the link triggers a servlet

    <a href="Servlet">link1</a>

So, when the user press the link1, the servlet among other things i want to do two things.
1 Pass to the next page page2.jsp an object and
2 redirect the user to the page2.jsp

In the Servlet i wrote:

     request.setAttribute("cis", myObjet);
     RequestDispatcher disp = getServletContext().getRequestDispatcher("/page2.jsp");
     disp.forward(request, response);
     response.sendRedirect("page2.jsp");

After i run the application, i get an error in console that says:

Cannot call sendRedirect() after the response has been committed

i read some topics relevant to this, but i havent solve it. Also the application continue to work, although i have this error in the console... thank you a lot!

Was it helpful?

Solution 2

First of all, you can't call sendRedirect(), after you have already used forward(). So, you get that exception.

However, it seems like the use of sendRedirect() there is really not needed. You seem to be believing that you need to use sendRedirect() after forward(), since you have used the same page in both of them. Actually, it's not like that.

Simply remove the sendRedirect line, and you'll be fine.

See also:

OTHER TIPS

if you have to more than one redirect lines which checks conditions each own, to not get exception you should control the response is committed.

HttpServletResponse response = (HttpServletResponse) getResponse();

if (!response.isCommitted()){
// redirect or dispatch whereever you want
}

What you are trying to do is fundamentally wrong. You can't do a redirect after a forward or vice versa. You can do either forward or redirect.

Read up these links:

http://docs.oracle.com/javaee/6/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse)

http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#sendRedirect(java.lang.String)

http://javapapers.com/jsp/difference-between-forward-and-sendredirect/

Hope this helps.

Sahil

You can work with the combination of rd.include(req,res); and res.sendRedirect(-); at the same time but you can't with the combination of rd.forward(req,res); and res.sendRedirect(-); at the same time. Because both the forwards to the new page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top