Spring - POST 后重定向(即使有验证错误) [英] Spring - Redirect after POST (even with validation errors)

查看:24
本文介绍了Spring - POST 后重定向(即使有验证错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何保留" BindingResult 以便它可以通过 Spring <form:errors> 标记在后续 GET 中使用.我想这样做的原因是因为 Google App Engine 的 SSL 限制.我有一个通过 HTTP 显示的表单,帖子是一个 HTTPS URL.如果我只转发而不是重定向,那么用户将看到 https://whatever.appspot.com/my/表单 URL.我正在努力避免这种情况.任何想法如何解决这个问题?

I'm trying to figure out how to "preserve" the BindingResult so it can be used in a subsequent GET via the Spring <form:errors> tag. The reason I want to do this is because of Google App Engine's SSL limitations. I have a form which is displayed via HTTP and the post is to an HTTPS URL. If I only forward rather than redirect then the user would see the https://whatever.appspot.com/my/form URL. I'm trying to avoid this. Any ideas how to approach this?

下面是我想要做的,但我只在使用 return "create" 时看到验证错误.

Below is what I'd like to do, but I only see validation errors when I use return "create".

@RequestMapping(value = "/submit", method = RequestMethod.POST)
public final String submit(
    @ModelAttribute("register") @Valid final Register register,
    final BindingResult binding) {

    if (binding.hasErrors()) {
        return "redirect:/register/create";
    }

    return "redirect:/register/success";
}

推荐答案

从 Spring 3.1 开始,您可以使用 RedirectAttributes.在执行重定向之前添加您希望可用的属性.添加 BindingResult 和用于验证的对象,在本例中为 Register.

Since Spring 3.1 you can use RedirectAttributes. Add the attributes that you want to have available before doing the redirect. Add both, the BindingResult and the object that you are using to validate, in this case Register.

对于 BindingResult,您将使用名称:org.springframework.validation.BindingResult.[您的 ModelAttribute 名称]".

For BindingResult you will use the name: "org.springframework.validation.BindingResult.[name of your ModelAttribute]".

对于用于验证的对象,您将使用 ModelAttribute 的名称.

For the object that you are using to validate you will use the name of ModelAttribute.

要使用 RedirectAttributes,您必须将其添加到您的配置文件中.除其他事项外,您还告诉 Spring 使用一些较新的类:

To use RedirectAttributes you have to add this in your config file. Among other things you are telling to Spring to use some newer classes:

<mvc:annotation-driven />

现在错误将显示在您重定向的任何地方

Now the errors will be displayed wherever you are redirecting

@RequestMapping(value = "/submit", method = RequestMethod.POST)
public final String submit(@ModelAttribute("register") @Valid final Register register, final BindingResult binding, RedirectAttributes attr, HttpSession session) {

if (binding.hasErrors()) {
    attr.addFlashAttribute("org.springframework.validation.BindingResult.register", binding);
    attr.addFlashAttribute("register", register);
    return "redirect:/register/create";
}

return "redirect:/register/success";
}

这篇关于Spring - POST 后重定向(即使有验证错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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