Question

I have login JSP which will redirect to servlet called DisplayData which must check the user credentials and displays the data only for registered users. But it throws error called "Cannot forward after response has been committed". here is the servlet code

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException
{
    HttpSession session = request.getSession(true);
    HttpSession usersession = request.getSession(true);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String query;
    Connection conn;
    Statement stmt;
    ResultSet res;
    DatabaseConnection dbconn;

    String username="";
    String hiddenname = request.getParameter("hiddenname");

    if (hiddenname.equals("login"))
    {
        username = request.getParameter("username");
        //System.out.println(username);
        String password = request.getParameter("password");
        // System.out.println(password);
        usersession.setAttribute("uname", username);
        usersession.setAttribute("upass", password);
        Connection con = dbconnection.getCon();
        System.out.println(con);
        PreparedStatement statemt = null;
        try {
            statemt = con.prepareStatement("select User_name,Password from login_details where User_name = ? and Password = ?");
            System.out.println(statemt);
            statemt.setString(1, username); // set input parameter 1
            statemt.setString(2, password); // set input parameter 2
            ResultSet rs = statemt.executeQuery();
            if (rs.next() == false)
            {
                out.write("Invalid user name or password. Please press back button to login again");

            }
            else
            {
                String url="/index.jsp";
                RequestDispatcher dispatcher=getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            con.close();
        }
        catch (SQLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    List lst=new ArrayList();
    String login_name,login_password;
    try
    {

        login_name=(String) session.getAttribute("uname");
        login_password=(String) session.getAttribute("upass");
        request.setAttribute("UserName", login_name);
        request.setAttribute("UserPassword", login_password);
        dbconn=new DatabaseConnection();
        conn=dbconn.setConnection();
        stmt=conn.createStatement();
        query="select * from mpi";
        res=dbconn.getResultSet(query, conn);
        while(res.next())
        {

            lst.add(res.getString("UniqueID"));
            lst.add(res.getString("Phylum"));
            lst.add(res.getString("Family"));
            lst.add(res.getString("Genus"));
            lst.add(res.getString("NCBI_Taxnomy_ID"));
            lst.add(res.getString("16s_Sanger_seq"));
            lst.add(res.getString("Genome_Sequencing_Batch"));
            lst.add(res.getString("Stock_number"));
            lst.add(res.getString("Stock_Location"));
            lst.add(res.getString("Soil_batch"));
            lst.add(res.getString("Host"));
            lst.add(res.getString("Operator"));
            lst.add(res.getString("GPS_coordinates"));
            lst.add(res.getString("Greenhouse_or_Natural_sites"));
            lst.add(res.getString("Isolation_procedure"));
            lst.add(res.getString("Date_of_isolation"));
            lst.add(res.getString("Previous_Ids"));
            lst.add(res.getString("Compartment"));
            lst.add(res.getString("Publication"));
            lst.add(res.getString("Strain_Derivatives"));
            lst.add(res.getString("Growth_conditions"));
            lst.add(res.getString("Natural_antibiotic_resistance"));
            lst.add(res.getString("Colony_morphology"));
        }
        res.close();
    }
    catch(Exception e)
    {
        RequestDispatcher rd=request.getRequestDispatcher("/error.jsp");
        rd.forward(request, response);
        e.printStackTrace();

    }
    finally
    {
        request.setAttribute("UserData", lst);
        RequestDispatcher rd=request.getRequestDispatcher("/displayrecord.jsp");
        rd.forward(request, response);
        lst.clear();
        out.close();
    }

}

I don't know where the mistake is. Kindly help me.

Was it helpful?

Solution

You have a couple of forwards in your code. One example:

String url="/index.jsp";
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);

Further down the code you have a block with try/catch/finally. Specifically you have the block

finally
{
    request.setAttribute("UserData", lst);
    RequestDispatcher rd=request.getRequestDispatcher("/displayrecord.jsp");
    rd.forward(request, response);
    lst.clear();
    out.close();
}

When you forward a request it does not stop the execution in your method. Once it is done with the forward it will continue execution where you left off and you are having a guaranteed forward in the end with the finally block. The finally block will be executed no matter what happened earlier in your code. If you are first executing one of the forwards up in the top of your code, it will fail when you are hitting the finally block because then it is trying to forward the request a second time and that will cause the error you are experiencing.

Look closely at your full stack trace because it should indicate the exact line number where it is trying to use the response (in your case the forwards) a second time. You need to rearrange/rewrite your code so that you only execute one forward (at most).

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