java - 如何更改 Java servlet 中的请求属性以重定向页面?

标签 java servlets

我正在使用 JSP 和 Java servlet 创建调查。在 JSP 中,我有一个表单,“下一步”按钮指定要转到的下一个问题:“/survey?q=2”,其中“q”是指定要显示的问题的参数。但是,根据答案(或缺乏答案),我可能想重定向到错误页面,或返回同一问题。

我尝试了一个简化版本,如果“答案”为空(答案是允许我获取值的控件的名称),我将使用 request.setAttribute()< 设置“q”参数 到相同的问题编号。然而,这似乎并没有覆盖“q”的值,因为将加载下一个问题而不是重定向到同一问题。

我还尝试使用 response.sendRedirect() 并传递所需的 url,但这引发了异常“提交回复后无法转发”。

以下是 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,我需要做什么要做什么才能实现这一点?

希望这足够详细。如果需要的话我可以提供更多。 谢谢!

最佳答案

I also tried using the response.sendRedirect() and passing the desired url, but this threw an exception "Cannot forward after repsonse has been committed"

看起来您尝试重定向到一个新的 URL,该 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 请求,因此所有请求属性都将丢失。

关于java - 如何更改 Java servlet 中的请求属性以重定向页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22183463/

相关文章:

java - 与 HttpSession 关联的可关闭对象

java - Android: setOnBufferingUpdateListener 未定义 VideoView 类型

java - 如何在同一个项目中以不同方式配置两个rabbitlistener?

java - 如何告诉 NetBeans 使用库的 JAR 的最新可用版本?

java - 我的 jsp 打印 'null' 而不是 null

java - java中 session 变量偶尔丢失

java - 如何在 Android 中使用 SQLite 数据库将两列相乘?

java - 黑莓对齐的布局设计问题

java - Servlets response.sendRedirect(String url) 似乎没有发送编码,为什么?

java - 为什么使用 JAX-RS 与 JAX-RS 时浏览器中的下载弹出窗口不显示标准servlet?