Search code examples
jspservletsresponse.redirectforward

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


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!


Solution

  • 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: