Programmers learn & share
0 votes
307 views

Problem :

I am trying to pass the values from the servlet to jsp page

But when I run the page I am facing below error:

Error as below :

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
    org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:483)
    src.Taskservlet.doPost(Taskservlet.java:108)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

I tried to use the below code as well:

RequestDispatcher dd=request.getRequestDispatcher("usertaskpage.jsp");

dd.forward(request, response);

But still I got a same error.

How can I fix above error?

by (3.9k points)   | 307 views

1 Answer

0 votes

Solution :

It seems you have already forwarded a response in catch block with below code:

RequestDispatcher dd = request.getRequestDispatcher("error.jsp");
dd.forward(request, response);

So,now you must not again call the :

response.sendRedirect("usertaskpage.jsp");

As it is already forwarded (committed).

So what you can really do is: keep the string to assign where you need to forward a response.

    String page = "";
    try {
 
    } catch (Exception e) {
      page = "error.jsp";
    } finally {
      page = "usertaskpage.jsp";
    }
RequestDispatcher dd=request.getRequestDispatcher(page);
dd.forward(request, response);

 OR

Cause of IllegalStateException exception is the java servlet is attempting to write to a response after a response has been committed. It is always better to ensure that the no content is added to a response after a forward or the redirect is done to avoid the IllegalStateException. It can be done by including the ‘return’ statement immediately next to a forward or redirect statement.

by (36.1k points)  
2,218 questions
2,683 answers
59 comments
241 users