java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

后端 未结 8 1070
南笙
南笙 2020-11-21 11:06

This method throws

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

and I am unable to spot th

8条回答
  •  野的像风
    2020-11-21 11:35

    This is because your servlet is trying to access a request object which is no more exist.. A servlet's forward or include statement does not stop execution of method block. It continues to the end of method block or first return statement just like any other java method.

    The best way to resolve this problem just set the page (where you suppose to forward the request) dynamically according your logic. That is:

    protected void doPost(request , response){
    String returnPage="default.jsp";
    if(condition1){
     returnPage="page1.jsp";
    }
    if(condition2){
       returnPage="page2.jsp";
    }
    request.getRequestDispatcher(returnPage).forward(request,response); //at last line
    }
    

    and do the forward only once at last line...

    you can also fix this problem using return statement after each forward() or put each forward() in if...else block

提交回复
热议问题