【问题标题】:Servlet redirect to same page with error messageServlet 重定向到带有错误消息的同一页面
【发布时间】:2013-01-15 22:28:13
【问题描述】:

我有一个关于 servlet 重定向到同一初始页面的问题。 以下是场景: 假设用户想购买一件商品,他填写金额并提交。表单被提交给一个 servlet,可用的数量与数据库中的可用数量进行核对。因此,如果订购的商品数量多于可用商品,则 servlet 将重定向到同一页面,但会显示“商品不可用”之类的消息。 所以我的问题是如何实施这种情况。如何使用错误消息重定向到相同的初始页面。我不想在这里使用ajax。

这是我的想法: 1.)如果产生错误,我是否应该设置上下文属性,然后在重定向后在初始页面再次检查并显示已设置的消息。

此类活动的最佳做法是什么?

【问题讨论】:

  • 将鼠标放在您放置在问题上的[servlets] 标记上,直到出现一个黑框,然后单击其中的info 链接。这个问题在第一个 Hello World 示例中已经涵盖了很长时间。

标签: java jsp servlets redirect scope


【解决方案1】:

最常见和推荐的场景(用于 Java servets/JSP 世界中的服务器端验证)是将一些错误消息设置为 request 属性(在 request 范围内 ),然后使用Expression Language 在JSP 中输出此消息(参见下面的示例)。未设置错误消息时 - 不会显示任何内容。

但是在请求中存储错误消息时,您应该将请求转发到初始页面。重定向时不适合设置请求属性,因为如果您使用重定向,这将是一个完全NEW 请求,并且请求属性在请求之间重置

如果您想将请求重定向到引用页面(您从中提交数据的页面),那么您可以将错误消息存储在会话中(在 会话范围内 em>),即设置一个会话属性。但在这种情况下,您还需要在提交的请求正确时从会话中删除该属性,否则只要会话存在,就会出现错误消息。

至于 context 属性,它适用于整个 Web 应用程序(应用程序范围)和所有用户,而且它与 Web 一样存在应用程序存在,这在您的情况下几乎没有用。如果您将错误消息设置为应用程序属性它将对所有用户可见,而不仅仅是提交错误数据的用户。


好的,这是一个原始示例。

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <display-name>Test application</display-name>

    <servlet>
        <servlet-name>Order Servlet</servlet-name>
        <servlet-class>com.example.TestOrderServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Order Servlet</servlet-name>
        <url-pattern>/MakeOrder.do</url-pattern>
    </servlet-mapping>

</web-app>


order.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <h1>Test page</h1>
    <form action="MakeOrder.do" method="post">
        <div style="color: #FF0000;">${errorMessage}</div>
        <p>Enter amount: <input type="text" name="itemAmount" /></p>
        <input type="submit" value="Submit Data" />
    </form>
</body>
</html>


选项№1:将错误消息设置为请求属性

package com.example;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import java.io.IOException;

public class TestOrderServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
        int amount = 0;
        try {
            amount = Integer.parseInt(request.getParameter("itemAmount"));
        } catch (NumberFormatException e) {
            // do something or whatever
        }

        if ((amount > 0) && (amount < 100)) {   // an amount is OK
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } else {                                // invalid amount
            // Set some error message as a request attribute.
            if (amount <= 0) {
                request.setAttribute("errorMessage", "Please submit an amount of at least 1");
            } 
            if (amount > 100){
                request.setAttribute("errorMessage", "Amount of items ordered is too big. No more than 100 is currently available.");
            }
            // get back to order.jsp page using forward
            request.getRequestDispatcher("/order.jsp").forward(request, response);
        }
    }
}


选项№2:将错误消息设置为会话属性

TestOrderServlet.java

package com.example;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import java.io.IOException;

public class TestOrderServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
        int amount = 0;
        try {
            amount = Integer.parseInt(request.getParameter("itemAmount"));
        } catch (NumberFormatException e) {
            // do something or whatever
        }

        if ((amount > 0) && (amount < 100)) {   // an amount is OK
            // If the session does not have an object bound with the specified name, the removeAttribute() method does nothing.
            request.getSession().removeAttribute("errorMessage");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } else {                                // invalid amount
            // Set some error message as a Session attribute.
            if (amount <= 0) {
                request.getSession().setAttribute("errorMessage", "Please submit an amount of at least 1");
            } 
            if (amount > 100){
                request.getSession().setAttribute("errorMessage", "Amount of items ordered is too big. No more than 100 is currently available.");
            }
            // get back to the referer page using redirect
            response.sendRedirect(request.getHeader("Referer"));
        }
    }
}

相关阅读:

【讨论】:

  • 我确实被重定向回我的登录页面,但出现错误,但如果我登录良好并点击返回 - 它仍然显示“错误消息”。
  • @AnnadatePiyush 好吧,这是预期的行为。浏览器中的“后退”按钮功能可让您“回到历史”(通常使用浏览器缓存)。如果最后一个操作是“错误消息”,它会再次显示。阅读此处了解更多信息:How does the Back button in a web browser work?
  • 这有帮助。那我需要参加会议。
猜你喜欢
  • 2020-10-12
  • 2014-03-05
  • 2012-08-12
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
相关资源
最近更新 更多