Hi everyone, i encountered this error when i want to forward user to different page according to different situation.

The error occurs if the login is null and the cash is null :(
seems like the it does not know where to forward because there is two forward.
is there anywhere to redirect or forward or whatever and don't run the remaining code?

any help on this will be very appreciated.

-----------------------------------------------------------------------------------

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<%
            if (request.getAttribute("login") == null) {
                pageContext.forward("login.jsp");
            }
            if (request.getAttribute("cash") == null) {
                pageContext.forward("no_cash.jsp");
            }
%>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Content Page</title>
    </head>
    <body>
    </body>
</html>

Decide a preference for your NULL checks; should the NULL check for `login` be performed before the NULL check for `cash` or vice versa. Use ELSE IF instead of just IF for the second conditional check.

When you forward, you are effectively saying that the forwarded page now has the responsibility of rendering the response. Forwarding to a page effectively "commits" /finalizes the response. Forwarding twice i.e. forwarding after the response has been committed results in an IllegalArgumentException as per the servlet specification.

hello ~s.o.s~, thx for ur reply.

this is the code i want, it will redirect directly without running to the end of jsp code.
but is there java code that is equivalent to this "<jsp:forward page="login.jsp"></jsp:forward>"?

it would be helpful if there is java code of it.

<%
if (request.getAttribute("login") == null) {
%>
<jsp:forward page="login.jsp"></jsp:forward>
<%
}
if (request.getAttribute("cash") == null) {
%>
<jsp:forward page="no_cash.jsp"></jsp:forward>
<%
}
%>

> but is there java code that is equivalent to this

Yes, look into the `forward` method of the `RequestDispatcher` interface. Read this.

Hi ~s.o.s~,

i still have "Cannot forward after response has been committed" error, even i have changed the code accordingly. Can help me take a look and advise me what is wrong with my code? =( Thanks.

~s.o.s~,i really thank for your help.

<%
            if (request.getAttribute("login") == null) {
                RequestDispatcher dispatcher =
                        request.getRequestDispatcher("/login.jsp");
                dispatcher.forward(request, response);
            }
            if (request.getAttribute("cash") == null) {
                RequestDispatcher dispatcher =
                        request.getRequestDispatcher("/login.jsp");
                dispatcher.forward(request, response);
            }
%>

Cannot still getting the same error. seems like it cannot be redirected twice (meaning it will go to the code of response.sendRedirect("no_cash.jsp"), please refer to the 1st post

<%
            if (request.getAttribute("login") == null) {
                response.sendRedirect("/login.jsp");
            }
            if (request.getAttribute("cash") == null) {
                response.sendRedirect("/no_cash.jsp");
            }
%>

Mhh! What do you want to do?
Something like this?

<%
            if (request.getAttribute("login") == null) {
                response.sendRedirect("/login.jsp");
            }
            else if (request.getAttribute("cash") == null) {
                response.sendRedirect("/no_cash.jsp");
            }
%>

you cannot redirect the same page twice or the two conditions *MUST NOT* happen at the same time!

Ok i should rephrase response.sendRedirect() will execute the remaining of the code. e.g:

if (request.getAttribute("login") == null) {
response.sendRedirect("/login.jsp");
}
else if (request.getAttribute("cash") == null) {
response.sendRedirect("/no_cash.jsp");
}
//a large chunk of code

i am trying to 'break' or whatever to achieve redirect immediately without it running through the large chunk of code; it would be time consuming and not a good programming style.

i used the prog code above and i run in debug mode (netbeans IDE), it will still run the large chunk of code then redirect, but i use <jsp:forward page="login.jsp"></jsp:forward> (please see the 3rd post) then it won't run to the large chunk of code. but it's very confusing to have jsp tag all around, so i wanna ask is there any java code equivalent to <jsp:forward page="login.jsp"></jsp:forward>?

thanks.

I have not understood what you want to do. Can you post that chunk of code?

Hi ~s.o.s~,

i still have "Cannot forward after response has been committed" error, even i have changed the code accordingly. Can help me take a look and advise me what is wrong with my code? =( Thanks.

~s.o.s~,i really thank for your help.

<%
            if (request.getAttribute("login") == null) {
                RequestDispatcher dispatcher =
                        request.getRequestDispatcher("/login.jsp");
                dispatcher.forward(request, response);
            }
            if (request.getAttribute("cash") == null) {
                RequestDispatcher dispatcher =
                        request.getRequestDispatcher("/login.jsp");
                dispatcher.forward(request, response);
            }
%>

You still haven't made those changes; like already mentioned if both 'login' and 'cash' are not present, you end up doing a `forward` twice. Replace the second `if` with an `if..else` and it should work out fine.

Also, try rewriting your code. Put the forwarding logic in a Servlet and have three conditional checks instead of the two present right now. Create three JSP's; no_cash.jsp, no_login.jsp and normal.jsp. Inside the servlet, write something along the lines of:

protected void doGet(HttpServletRequest req, HttpServletResponse res) {
  if(noLogin) {
     // forward to no_login.jsp
  } else if(noCash) {
    // forward to no_cash.jsp
  } else {
    // forward to normal.jsp
  }
}

i just wanna find some in java that is similar to the "exit" in PHP

if (!array_key_exists("user", $_SESSION)) {
    header('Location: index.php');
    exit;
}

when it is exit then the rest of code will be ignored.

<?php

session_start();
if (!array_key_exists("user", $_SESSION)) {
    header('Location: index.php');
    exit;
}
require_once("Includes/db.php");
$wisherId = WishDB::getInstance()->get_wisher_id_by_name($_SESSION["user"]);

$wishDescriptionIsEmpty = false;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
    if (array_key_exists("back", $_POST)) {
        header('Location: editWishList.php' );
        exit;
    } else
    if ($_POST["wish"] == "") {
        $wishDescriptionIsEmpty =  true;
    } else {
        WishDB::getInstance()->insert_wish($wisherId, $_POST["wish"], $_POST["dueDate"]);
        header('Location: editWishList.php' );
        exit;
    }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <header>
        <title>Make your wish!</title>
    </header>
    <body>
        <?php
        if ($_SERVER["REQUEST_METHOD"] == "POST")
        $wish = array("description" => $_POST["wish"],
                                    "due_date" => $_POST["dueDate"]);
        else
        $wish = array("description" => "",
                                    "due_date" => "");
        ?>
        <form name="editWish" action="editWish.php" method="POST">
            Describe your wish: <input type="text" name="wish"  value="<?php echo $wish['description'];?>" /><br/>
            <?php
            if ($wishDescriptionIsEmpty) echo "Please enter a description<br/>";
            ?>
            When do you want to get it? <input type="text" name="dueDate" value="<?php echo $wish['due_date']; ?>"/><br/>
            <input type="submit" name="saveWish" value="Save Changes"/>
            <input type="submit" name="back" value="Back to the List"/>
        </form>
    </body>
</html>

did you read sos post?
It explains all those.
Are you doing if on independent conditions? It will not fully work.
re-read sos post and get the point

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.