简体   繁体   English

如何使用Spring处理表单错误(与类字段不匹配)

[英]How to handle form errors (that don't match a class fields) with spring

I've been studying Spring for some weeks, so I don't know the "Logic" to use while handling certain issues. 我已经学习Spring几周了,所以我不知道在处理某些问题时要使用的“逻辑”。

I tell you immediately that my problem is not how to check if 2 form fields match! 我立即告诉您,我的问题不是如何检查2个表单字段是否匹配! I'm just using mail and confirmMail to make an example. 我只是使用mail和ConfirmMail做一个例子。

I know how to handle form errors by using @Valid annotation on a Object, but what if the form contain a field that my class doesn't have? 我知道如何通过在对象上使用@Valid注释来处理表单错误,但是如果表单包含我的类没有的字段怎么办?

Let's say there's a form to sign up: I have a class called User, with name, age and email fields. 假设有一种表单可以注册:我有一个名为User的类,其中包含名称,年龄和电子邮件字段。 I have no problem handling errors with 我没有问题处理错误

<form:errors path="name" cssClass="error">
<form:errors path="age" cssClass="error">
<form:errors path="mail" cssClass="error">

Now let's say I want to add another field in my form, called for example confirmEmail, to check, server side, that the email is correct. 现在,假设我要在表单中添加另一个字段,例如,confirmEmail,以检查服务器端电子邮件是否正确。 How should I handle it? 我应该如何处理? I can't create another field called confirmEmail in my class User, it doens't sound correct to me. 我无法在班级用户中创建另一个名为ConfirmEmail的字段,这对我来说听起来不正确。

This is my Form 这是我的表格

<form:form action="signUpSent" method="post" commandName="utente">

            <form:input path="nome"/>
            <form:errors path="nome" cssClass="DivErroriSpring"/>

            <form:input path="cognome"/>
            <form:errors path="cognome" cssClass="DivErroriSpring"/>

            <form:input path="email"/>
            <form:errors path="email" cssClass="DivErroriSpring"/>  

            <form:input path="confermaEmail"/>
            <form:errors path="confermaEmail" cssClass="DivErroriSpring"/>

            <input type="submit">

        </form:form>

this is my class User (Utente in italian) 这是我的课程用户(意大利语中的Utente)

public class Utente {

    @NotEmpty   
    @Size(min=3,max=20)
    private String nome;    

    @NotEmpty
    @NotNull
    @Size(min=3,max=20)
    private String cognome;     

    @NotEmpty
    @Email
    private String email;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getCognome() {
        return cognome;
    }

    public void setCognome(String cognome) {
        this.cognome = cognome;
    }

    public String getEmail() {
        return email;
    }

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

}

As you can see, in my class User(Utente in italian) I don't have a field called confirmMail (confermaEmail in italian), because it wouldn't be correct to have it, would it? 如您所见,在我的类User(意大利语中的Utente)中,我没有名为confirmMail(意大利语中的confermaEmail)的字段,因为拥有它并不正确,对吗?

To be more clear, the question is: how should I handle errors when form field doens't match a field of my class User? 更明确地说,问题是:当表单字段与类User的字段不匹配时,我应该如何处理错误?

I see 2 possible solutions (apart from adding the additional field to your User object). 我看到2种可能的解决方案(除了将附加字段添加到您的User对象之外)。

The first involves treating your web layer as a different problem domain (bounded context) as your business domain. 第一个涉及将您的Web层视为与您的业务域不同的问题域(有界上下文)。 Generally there is a mismatch in what you want to show/use on screen as to what you actually need in the business part of your application. 通常,您想要在屏幕上显示/使用的内容与您在应用程序的业务部分中实际需要的内容不匹配。

@FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must match")    
public class UserForm {
     private String email;
     private String confirmEmail;
     ...
}

In your controller you have the validation if it validates copy the needed fields to the User object (maybe using a mapper framework liker Dozer or MapStruct ) 在您的控制器中,您可以进行验证(如果它可以验证),将所需的字段复制到User对象(可能使用诸如 DozerMapStruct之类的映射器框架)

The second is adding a input field for the confirmation email, add that field as a @RequestParam to your method signature and do manual validation in your controller. 第二个是为确认电子邮件添加一个输入字段,将该字段作为@RequestParam添加到您的方法签名中,并在控制器中进行手动验证。 You can simply add errors to the BindingResult . 您可以简单地将错误添加到BindingResult

public String register(@Valid @ModelAttribute User user, BindingResult result, @RequestParam("confirmEmail", required=false) String confirmEmail) {
     if (!StringUtils.equals(confirmEmail, user.getEmail()) {
         result.reject("email", "email.confirm.mustequal");
     }
    ....

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM