简体   繁体   English

在Java Servlet中提交响应后无法转发

[英]Cannot forward after response has been committed in java servlet

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. 我有登录JSP,它将重定向到名为DisplayData的servlet,该servlet必须检查用户凭据并仅显示注册用户的数据。 But it throws error called "Cannot forward after response has been committed". 但是它会引发错误,即“提交响应后无法转发”。 here is the servlet code 这是servlet代码

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. 请帮助我。

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 . 在代码的下方,您有一个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. 一旦完成了转发,它将继续执行从您上次中断的地方开始执行,并且在finally块的保证下,您可以保证转发。 The finally block will be executed no matter what happened earlier in your code. 无论代码前面发生了什么,都将执行finally块。 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. 如果您是第一次执行代码顶部的转发中的一个,则在您击中finally块时,它将失败,因为它随后尝试第二次转发请求,这将导致您遇到的错误。

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). 您需要重新排列/重写代码,以便您最多只能执行一个正向操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM