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

之前在使用Servlet的时候,总是在 doGet()/doPost() 的最后一行才使用请求转发或者重定向。如果需要根据条件来判断进行不同的请求转发或者重定向,代码如下:

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    if (req.getSession().getAttribute(AttrConsts.LOGIN_USER) == null) {
        req.getRequestDispatcher(PathConsts.PATH_PREFIX + PathConsts.LOGIN_PAGE).forward(req, resp);
    }
    req.getRequestDispatcher(PathConsts.PATH_PREFIX + PathConsts.MAIN_PAGE).forward(req, resp);
}

上边的代码在执行后会报如下异常:

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

报异常的原因是重复转发或者重定向了请求,如果有多个转发或者重定向,需要在每个转发或者重定向请求之后加上return语句(最后一个请求转发或者重定向不需要加return),如下:

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    if (req.getSession().getAttribute(AttrConsts.LOGIN_USER) == null) {
        req.getRequestDispatcher(PathConsts.PATH_PREFIX + PathConsts.LOGIN_PAGE).forward(req, resp);
        return;
    }
    req.getRequestDispatcher(PathConsts.PATH_PREFIX + PathConsts.MAIN_PAGE).forward(req, resp);
}

通过return语句确保在转发或者重定向请求之后返回,避免在执行上边的转发/重定向之后,接着继续往下执行转发/重定向请求,这样就不会再报这个异常了。

已标记关键词 清除标记
package piggybank; import java.util.Scanner; public class piggybank { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Welcome to the Piggy Bank. Please enter starting balance: "); double startingBalance = input.nextDouble(); System.out.println("Piggy Bank ATM"); System.out.printf("Balance : %6.2f", startingBalance); System.out.println(); while (true){ System.out.println(); System.out.println("OPTIONS"); System.out.println(); System.out.println("1.Deposit\n"+"2.Withdraw\n"+"3.Quit\n"); System.out.println(); System.out.println("Choose one:"); int option = input.nextInt(); switch (option) { case 1: System.out.println("Enter deposit amount:\n" + "Piggy Bank ATM"); double deposit = input.nextDouble(); double depositBalance= startingBalance + deposit; System.out.printf(" Balance: $%6.2f ",depositBalance); System.out.println(); break; case 2: System.out.println("Enter withdrawal amount:\n" + "Piggy Bank ATM"); double withdraw = input.nextDouble(); double withdrawBalance= startingBalance - withdraw; System.out.printf("Balance:$%8.2f ",withdrawBalance); System.out.println(); break; case 3: System.out.printf("Ending Balance: $%8.2f ", startingBalance); break; } input.close(); } } } 我想要反复执行存取款程序,但是就会显示出错 ![图片说明](https://img-ask.csdn.net/upload/201909/28/1569658326_406248.png) 求帮忙! 想要得到以下运行结果 ![图片说明](https://img-ask.csdn.net/upload/201909/28/1569658512_523449.png) 我的运行结果是这样的,没有办法进行第二次输入 ![图片说明](https://img-ask.csdn.net/upload/201909/28/1569658741_470527.png) 呜呜呜,初学什么都不会,求助
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页