在Java Servlet中提交响应后无法转发 [英] Cannot forward after response has been committed in java servlet

查看:169
本文介绍了在Java Servlet中提交响应后无法转发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有登录JSP,它将重定向到名为DisplayData的servlet,该servlet必须检查用户凭证并仅显示注册用户的数据.但是它会引发错误,即已提交响应后无法转发".这是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. 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.

推荐答案

您的代码中有一些转发.一个例子:

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

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

再往下看,您使用try/catch/finally的代码块.具体来说,您拥有

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();
}

转发请求时,它不会停止方法中的执行.一旦完成了前向操作,它将继续从您上次中断的地方开始执行,最后通过finally块保证前向.无论代码前面发生了什么,都将执行finally块.如果您是第一次执行代码顶部的转发中的一个,则在您按下finally块时它将失败,因为它随后尝试第二次转发该请求,这将导致您遇到的错误

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).

这篇关于在Java Servlet中提交响应后无法转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆