2016-12-07 55 views
0

我正在做一些Java servlet編碼練習,並且我得到了以下代碼片段(我無法發佈整個代碼)。SEVERE:java.lang.IllegalStateException:在提交響應後無法轉發

//other logic here..... 

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{ 
    String a= request.getParameter("a"); 
    String b= request.getParameter("b"); 
    String c= request.getParameter("c"); 
    getCalculation(request, response, a, b, c); 
} 

public void getCalculation(HttpServletRequest request, HttpServletResponse response, String a, 
     String b, String c) throws ServletException, IOException 
{ 
    //calculation1 
    if (statement) { 
    RequestDispatcher r= request.getRequestDispatcher("/main.jsp"); 
    r.forward(request,response); 
    } 

    //calculation2 
    if (statement) { 
    RequestDispatcher r= request.getRequestDispatcher("/main.jsp"); 
    r.forward(request,response); 
    } 
} 

Calculation1與caculation2在做什麼非常不同,但我需要它們在同一頁上轉發。我認爲這個問題是因爲我在第一次計算時打電話給r.forward。我收到以下錯誤:

java.lang.IllegalStateException: Cannot forward after response has been committed

+0

你可以發佈'getCalculation()'方法的完整代碼嗎? – developer

回答

0

Javadoc of RequestDispatcher

forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException .

您需要轉發後退出​​。類似這樣的:

//calculation 
if (statement) { 
    RequestDispatcher r= request.getRequestDispatcher("/main.jsp"); 
    r.forward(request,response); 
    return; 
} 

//calculation2 
if (statement) { 
    RequestDispatcher r= request.getRequestDispatcher("/main.jsp"); 
    r.forward(request,response); 
    return; 
} 
相關問題