Spring MVC 验证 - 避免回发

发布于 2024-10-25 04:29:18 字数 277 浏览 2 评论 0原文

我想验证 Spring 3 MVC 表单。当元素无效时,我想重新显示带有验证消息的表单。到目前为止这非常简单。问题是,当用户在无效提交后点击刷新时,我不希望他们发布,我希望他们获取。这意味着我需要从表单 POST(提交)进行重定向,以重新显示带有验证消息的表单(表单是通过 POST 提交的)。

我认为最好的方法是使用 SessionAttributeStore.retrieveAttribute 来测试表单是否已在用户会话中。如果是,则使用商店表单,否则创建一个新表单。

这听起来正确吗?有更好的方法吗?

I'd like to validate a Spring 3 MVC form. When an element is invalid, I want to re-display the form with a validation message. This is pretty simple so far. The rub is, when the user hits refresh after an invalid submission, I don't want them to POST, I want them to GET. This means I need to do a redirect from the form POST (submission) to re-display the form with validation messages (the form is submitted via a POST).

I'm thinking the best way to do this is to use SessionAttributeStore.retrieveAttribute to test if the form is already in the user's session. If it is, use the store form, otherwise create a new form.

Does this sound right? Is there a better way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浮光之海 2024-11-01 04:29:18

为了解决这个问题,我在 POST 重定向后将 Errors 对象存储在会话中。然后,在 GET 上,我将其放回模型中。这里有一些漏洞,但它应该在 99.999% 的情况下都能工作。

public class ErrorsRedirectInterceptor extends HandlerInterceptorAdapter {
    private final static Logger log = Logger.getLogger(ErrorsRedirectInterceptor.class);

    private final static String ERRORS_MAP_KEY = ErrorsRedirectInterceptor.class.getName()
            + "-errorsMapKey";

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler, ModelAndView mav)
        throws Exception 
    {
        if (mav == null) { return; }

        if (request.getMethod().equalsIgnoreCase(HttpMethod.POST.toString())) {
            // POST
            if (log.isDebugEnabled()) { log.debug("Processing POST request"); }
            if (SpringUtils.isRedirect(mav)) {
                Map<String, Errors> sessionErrorsMap = new HashMap<String, Errors>();
                // If there are any Errors in the model, store them in the session
                for (Map.Entry<String, Object> entry : mav.getModel().entrySet()) {
                    Object obj = entry.getValue();
                    if (obj instanceof Errors) {
                        if (log.isDebugEnabled()) { log.debug("Adding errors to session errors map"); }
                        Errors errors = (Errors) obj;
                        sessionErrorsMap.put(entry.getKey(), errors);
                    }
                }
                if (!sessionErrorsMap.isEmpty()) {
                    request.getSession().setAttribute(ERRORS_MAP_KEY, sessionErrorsMap);
                }
            }
        } else if (request.getMethod().equalsIgnoreCase(HttpMethod.GET.toString())) {
            // GET
            if (log.isDebugEnabled()) { log.debug("Processing GET request"); }
            Map<String, Errors> sessionErrorsMap =
                    (Map<String, Errors>) request.getSession().getAttribute(ERRORS_MAP_KEY);
            if (sessionErrorsMap != null) {
                if (log.isDebugEnabled()) { log.debug("Adding all session errors to model"); }
                mav.addAllObjects(sessionErrorsMap);
                request.getSession().removeAttribute(ERRORS_MAP_KEY);
            }
        }
    }
}

To solve this problem, I store the Errors object in the session after a redirect on a POST. Then, on a GET, I put it back in the model. There are some holes here, but it should work 99.999% of the time.

public class ErrorsRedirectInterceptor extends HandlerInterceptorAdapter {
    private final static Logger log = Logger.getLogger(ErrorsRedirectInterceptor.class);

    private final static String ERRORS_MAP_KEY = ErrorsRedirectInterceptor.class.getName()
            + "-errorsMapKey";

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler, ModelAndView mav)
        throws Exception 
    {
        if (mav == null) { return; }

        if (request.getMethod().equalsIgnoreCase(HttpMethod.POST.toString())) {
            // POST
            if (log.isDebugEnabled()) { log.debug("Processing POST request"); }
            if (SpringUtils.isRedirect(mav)) {
                Map<String, Errors> sessionErrorsMap = new HashMap<String, Errors>();
                // If there are any Errors in the model, store them in the session
                for (Map.Entry<String, Object> entry : mav.getModel().entrySet()) {
                    Object obj = entry.getValue();
                    if (obj instanceof Errors) {
                        if (log.isDebugEnabled()) { log.debug("Adding errors to session errors map"); }
                        Errors errors = (Errors) obj;
                        sessionErrorsMap.put(entry.getKey(), errors);
                    }
                }
                if (!sessionErrorsMap.isEmpty()) {
                    request.getSession().setAttribute(ERRORS_MAP_KEY, sessionErrorsMap);
                }
            }
        } else if (request.getMethod().equalsIgnoreCase(HttpMethod.GET.toString())) {
            // GET
            if (log.isDebugEnabled()) { log.debug("Processing GET request"); }
            Map<String, Errors> sessionErrorsMap =
                    (Map<String, Errors>) request.getSession().getAttribute(ERRORS_MAP_KEY);
            if (sessionErrorsMap != null) {
                if (log.isDebugEnabled()) { log.debug("Adding all session errors to model"); }
                mav.addAllObjects(sessionErrorsMap);
                request.getSession().removeAttribute(ERRORS_MAP_KEY);
            }
        }
    }
}
怀念你的温柔 2024-11-01 04:29:18

您的问题尚不清楚,但听起来您的 GET 和 POST 操作已映射到同一处理程序。在这种情况下,您可以执行以下操作:

if ("POST".equalsIgnoreCase(request.getMethod())) {
    // validate form
    model.addAttribute(form);
    return "redirect:/me.html";
}
model.addAttribute(new MyForm());
return "/me.html";

在 JSP 中检查表单上是否有任何错误并根据需要进行显示。

It's not clear from your question but it sounds like your GET and POST actions are mapped to the same handler. In that case you can do something like:

if ("POST".equalsIgnoreCase(request.getMethod())) {
    // validate form
    model.addAttribute(form);
    return "redirect:/me.html";
}
model.addAttribute(new MyForm());
return "/me.html";

In the JSP check if there are any error on the form and display as needed.

放飞的风筝 2024-11-01 04:29:18

这种方法称为 PRG (POST/REdirect/GET) 设计模式,几天前我将其解释为答案之一:

Spring MVC 简单重定向控制器示例

希望有帮助:)

Such approach is called PRG (POST/REdirect/GET) design pattern I explained it few days ago as one of the answers:

Spring MVC Simple Redirect Controller Example

Hope it helps :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文