Servlet 重定向到带有错误消息的同一页面 [英] Servlet redirect to same page with error message

查看:25
本文介绍了Servlet 重定向到带有错误消息的同一页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a question about servlet redirection to the same initial page. The following is the scenario: Suppose a user want to buy an item, so he fills in the amount and submits it. The form is submitted to a servlet and the quantity available is checked against the available in the database. So if the amount of items ordered is more than the available the servlet redirects to the same page but with a message like "item is unavailable". So my question is how to implement this case. How to redirect to the same initial page with an error message. I don't want to use ajax here.

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

Here is how I have thought of it as : 1.)should I set a context attribute if error is generated and then check it again in initial page after re-direction and show the message that has been set.

此类事件的最佳做法是什么?

What are the best practices for this kind of events?

推荐答案

最常见和推荐的方案(用于 Java serlvets/JSP 世界中的服务器端验证)是将一些错误消息设置为 请求属性strong>(在请求范围中),然后使用表达语言在 JSP 中输出此消息(见下面的例子).如果未设置错误消息 - 将不会显示任何内容.

The most common and recommended scenario (for the server side validation in Java serlvets/JSP world) is setting some error message as a request attribute (in the request scope) and then outputting this message in a JSP using Expression Language (see the example below). When the error message is not set - nothing will be shown.

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

But when storing an error message in a request, you should forward a request to the initial page. Setting a request attribute is not suitable when redirecting, because if you use a redirect it will be a totally NEW request and request attributes are reset between requests.

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

If you want to redirect a request to the referring page (the one from which you submitted data) then you can store an error message in a session (in the session scope), i.e. set a session attribute. But in this case, you also need to remove that attribute from the session when the submitted request is correct, because otherwise an error message will be available as long as the session lives.

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

As for the context attribute it is meant to be available to the whole web application (application scope) and for ALL users, plus it lives as long as the web application lives, which is hardly useful in your case. If you set an error message as an application attribute it will be visible to ALL users, not only to the one that submitted the wrong data.

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

OK, here is a primitive example.

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>


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);
        }
    }
}


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"));
        }
    }
}

<小时>

相关阅读:

这篇关于Servlet 重定向到带有错误消息的同一页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆