spring-mvc - 向 Spring 3 DataBinder 添加自定义对象字段的错误消息

标签 spring-mvc bean-validation

我正在尝试手动将单个电子邮件错误消息添加到我的模型中,但 View 中没有显示任何内容。
我认为这可能是我创建 ObjectError 或将其附加到 BindingResult 的方式。
我将错误添加到 catch 中。

以下是当我将电子邮件字段留空并且 JSR-303 注释启动时 result.errors 的内容(错误显示在 View 中):

[Field error in object 'user' on field 'email': rejected value []; codes [NotEmpty.user.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.email,email]; arguments []; default message [email]]; default message [may not be empty]]


这是我手动添加ErrorObject后result.errors的内容(电子邮件错误不显示在 View 中):

[Error in object 'email': codes []; arguments []; default message [An account already exists for this email.]]


Controller :

@RequestMapping(value = "/registration", method = RequestMethod.POST)
    public ModelAndView post(@Valid User user, BindingResult result)
    {

        if (result.hasErrors())
        {
            ModelAndView modelAndView = new ModelAndView(
                    Consts.MODEL_RESISTER_PAGE);
            modelAndView.addObject("user", user);
            return modelAndView;
        }
        else
        {
            try
            {
                userService.addUser(user);

                ModelAndView modelAndView = new ModelAndView(
                        Consts.MODEL_CARD_REPORTS_HOME_PAGE);
                modelAndView.addObject("userRegisteredSuccess", Boolean.TRUE);

                return modelAndView;
            }
            catch (DataIntegrityViolationException ex)
            {
                ObjectError error = new ObjectError("email","An account already exists for this email.");

                result.addError(error);

                ModelAndView modelAndView = new ModelAndView(
                        Consts.MODEL_RESISTER_PAGE);

                modelAndView.addAllObjects(result.getModel());
                modelAndView.addObject("user", user);

                return modelAndView;
            }
        }
    }

我的模型:

@Entity
public class User implements Serializable
{
    /**
     * 
     */
    private static final long serialVersionUID = -5232533507244034448L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotEmpty
    @Size(min=2, max=15)
    private String firstname;

    @NotEmpty
    @Size(min=2, max=15)
    private String surname;

    @NotEmpty
    @Email
    private String email;

    @NotEmpty
    @Size(min=6, max=10)
    private String password;

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public String getFirstname()
    {
        return firstname;
    }

    public void setFirstname(String firstname)
    {
        this.firstname = firstname;
    }

    public String getSurname()
    {
        return surname;
    }

    public void setSurname(String surname)
    {
        this.surname = surname;
    }

    public String getEmail()
    {
        return email;
    }

    public void setEmail(String email)
    {
        this.email = email;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }
}



文件add.html

<form id="registrationForm" action="#" th:action="@{/registration}" th:object="${user}" method="post" class="clearfix">
    <legend>Registration</legend>

    <div class="control-group input" th:class="${#fields.hasErrors('firstname')}? 'control-group input error'">
      <input type="text" th:field="*{firstname}" placeholder="Firstname" />
      <span class="help-block" th:if="${#fields.hasErrors('firstname')}" th:errors="*{firstname}"></span>
    </div>

    <div class="control-group input" th:class="${#fields.hasErrors('surname')}? 'control-group input error'">
      <input type="text" th:field="*{surname}" placeholder="Surname" />
      <span class="help-block" th:if="${#fields.hasErrors('surname')}" th:errors="*{surname}"></span>
    </div>

    <div class="control-group input" th:class="${#fields.hasErrors('email')}? 'control-group input error'">
      <input type="text" th:field="*{email}" placeholder="Email" />
      <span class="help-block" th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span>
    </div>

    <div class="control-group input" th:class="${#fields.hasErrors('password')}? 'control-group input error'">
        <input type="password" th:field="*{password}" placeholder="Password" />
        <span class="help-block" th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></span>
    </div>

    <div class="clearfix">
      <input type="submit" class="btn btn-success btn-large" value="Register" />
    </div>
</form>

最佳答案

我通常调用 result.rejectValue("property", "error.object");BindingResult 添加错误。如果要添加全局对象错误,可以使用 result.reject("error.object");

因此,在您的代码中,而不是:

ObjectError error = new ObjectError("email","An account already exists for this email.");
result.addError(error);

尝试:

result.rejectValue("email", "error.user", "An account already exists for this email.");

查看引用here .

希望这有帮助。

关于spring-mvc - 向 Spring 3 DataBinder 添加自定义对象字段的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12107503/

相关文章:

java - 在没有spring boot的情况下使用spring mvc项目配置angular 2

java - 常见对象集合的 JSR303 验证

java - SpingMVC + Angularjs+ POST 与 jsp

tomcat - org.springframework.web.SpringServletContainerInitializer 无法转换为 javax.servlet.ServletContainerInitializer

Java @interface.List 组在自定义约束注释中不起作用

maven-2 - org.hibernate.validator.engine.ConfigurationImpl 的来源

java - 未调用标有@AssertTrue 的方法

java - 验证不适用于 EntityManager.merge()

java - 如何在 Spring MVC 中填充下拉框

java - Grails 中 Quartz 工作的 withTransaction?