[java] how to fix Cannot call sendRedirect() after the response has been committed?

I am trying to pass values from servlet to jsp page using the code below:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    try {
        System.out.println("try");

        String taskid=request.getParameter("id");   
        convty = new Connectivity();
        con = convty.setConnection();
        st=con.createStatement();

        query="select * from task_table";

        rset=convty.getResultSet(query, con);
        while(rset.next()) {
            System.out.println("while");
            lst.add(rset.getString("task_id"));
            lst.add(rset.getString("date"));
            lst.add(rset.getString("project_name"));    
        }
        rset.close();
        System.out.println("after while");

    } catch(Exception e) {

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

    } finally {
        System.out.println("finally1");
        HttpSession sessionvar = request.getSession();
        sessionvar.setAttribute("TaskData", "lst");

        response.sendRedirect("usertaskpage.jsp");

        lst.clear();
        out.close();            
    }
}

when I run my page I am getting:

Error :

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:

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

but I got the same error.

How to fix this error?

This question is related to java jsp servlets illegalstateexception

The answer is


The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

JAVA 7 OFFICIAL LINK

ADDITIONAL INFO


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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to jsp

Difference between request.getSession() and request.getSession(true) A child container failed during start java.util.concurrent.ExecutionException The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path Using if-else in JSP Passing parameters from jsp to Spring Controller method how to fix Cannot call sendRedirect() after the response has been committed? How to include js and CSS in JSP with spring MVC How to create an alert message in jsp page after submit process is complete getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? How to pass the values from one jsp page to another jsp without submit button?

Examples related to servlets

Google Recaptcha v3 example demo Difference between request.getSession() and request.getSession(true) init-param and context-param java.lang.NoClassDefFoundError: org/json/JSONObject how to fix Cannot call sendRedirect() after the response has been committed? getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? Create a simple Login page using eclipse and mysql Spring get current ApplicationContext insert data into database using servlet and jsp in eclipse What is WEB-INF used for in a Java EE web application?

Examples related to illegalstateexception

how to fix Cannot call sendRedirect() after the response has been committed? SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error What is IllegalStateException? java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState" java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed