簡體   English   中英

如何更改Java servlet中的請求屬性以重定向頁面?

[英]How do I change request attributes in Java servlet to redirect a page?

我正在使用JSP和Java servlet創建一個調查。 在JSP中,我有一個表單,“下一步”按鈕指定要進入的下一個問題:“/ survey?q = 2”其中“q”是指定要顯示的問題的參數。 但是,根據答案(或缺少),我可能想要重定向到錯誤頁面,或者回到同一個問題。

我嘗試了一個簡化版本,如果“answer”為null(回答是允許我獲取值的控件的名稱),我會使用request.setAttribute()將“q”parm設置為相同的問題編號。 然而,這似乎沒有覆蓋“q”的值,因為下一個問題會加載而不是重定向到同一個問題。

我也嘗試使用response.sendRedirect()並傳遞所需的url,但是這引發了一個異常“在repsonse提交后無法轉發”。

這是servlet的摘錄:

    // At this point, the URL is /survey?q={SOME#} where SOME# is the next question to
    // go to after the submit.  So if the user was on Question 1, the submit location
    // would be /survey?q=2
    try {
        nextQuestion = Integer.parseInt(request.getParameter("q"));
    } catch (Exception e) {
        System.out.println("Inside the catch");
    }

    // The question we came from, obviously, is nextQuestion - 1        
    currQuestion = nextQuestion - 1;

    // This IF is just because I'm handling the first question differently
    if (currQuestion > 1) {
        answer = request.getParameter("answer");
        System.out.println("Answer = " + answer);

        //This function checkAnswer() returns "invalid" if no answer was selected"
        checkStr = checkAnswer(currQuestion, answer);
        if (checkStr == "invalid") {
            dispatcher = "survey-template.jsp";
            request.setAttribute("q", String.format("%d", currQuestion));
        } else {
            dispatcher = "survey-template.jsp";
        }
    } else {
        dispatcher = "survey-template.jsp";         
    }

    request.getRequestDispatcher(dispatcher).forward(request, response);

所以最大的問題是:如何從servlet重定向頁面? 如果要求進入/survey?q=2 ,而我想回到/survey?q=1 ,我需要做些什么來實現這一目標?

希望這足夠詳細。 如果需要,我可以提供更多。 謝謝!

我也嘗試使用response.sendRedirect()並傳遞所需的url,但是這引發了一個異常“在repsonse提交后無法轉發”

看起來你試圖重定向到一個新的URL,它將根據URL內容寫一個新的響應並關閉這個流,但保留了試圖寫入響應的轉發代碼,這是不允許的,因為響應已經是書面和流關閉。 在代碼中:

//having both is not allowed
//you should only use one of these approaches
response.sendRedirect(<someUrl>);
request.getRequestDispatcher(dispatcher).forward(request, response);

如果您只想重定向到另一個URL,請使用response.sendRedirect(<someUrl>); 並確保沒有進一步的重定向或轉發。 所以,你的代碼可能是:

response.sendRedirect(<someUrl>);
//request.getRequestDispatcher(dispatcher).forward(request, response);

請注意,發送重定向意味着在URL上調用新的GET請求,因此所有請求屬性都將丟失。

使用response.sendRedirect()您應該退出該方法。

你可以試試:

response.sendRedirect("url");
return;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM