簡體   English   中英

Java Spring:如何僅驗證實體中的特定字段

[英]Java Spring: how to validate only specific fields from my entity

我是Spring的新手,但是表單驗證存在問題。 在我的用戶編輯表單中,我只想驗證特定字段,而不驗證實體中所有帶注釋的字段。 例如,如果我的UserEntity具有以下字段:

@Entity
@Table(name = "users")
public class UserEntity {

@Id
@Column(name = "user_id")
@GeneratedValue
public int user_id;

@NotEmpty
@Column(name = "userlogin")
public String userlogin;

@NotEmpty
@Column(name = "userpass")
public String userpass;

@NotEmpty
@Column(name = "name")
public String name;

@Email
@NotEmpty
@Column(name = "email")
public String email;

@NumberFormat(style = Style.NUMBER)
@NotEmpty
@Column(name = "phone")
public String phone;

當我有注冊表格時,我需要驗證所有字段,並且工作正常。 但是,當我編輯了用戶表單時,我只想編輯和驗證“姓名”,“電子郵件”和“電話”,而不希望更改“ userlogin”和“ userpass”。 但是編輯表單不會成功通過,因為BindingResult會驗證所有字段。 這是我的編輯表單:

 <springForm:form action="/mywebapp/user/edit" commandName="user" method="POST">
    <table>     
        <tr>
            <td>Name:</td>
            <td><springForm:input path="name" value="${user.name}" /></td>
            <td><springForm:errors path="name" cssClass="error" /></td>
        </tr>
        <tr>
            <td>E-mail:</td>
            <td><springForm:input path="email" value="${user.email }" /></td>
            <td><springForm:errors path="email" cssClass="error" /></td>
        </tr>
        <tr>
            <td>Phone:</td>
            <td><springForm:input path="phone" value="${user.phone}" /></td>
            <td><springForm:errors path="phone" cssClass="error" /></td>

        </tr>
        <tr>
            <td><input type="submit" value="Edit" /></td>
        </tr>
    </table>
</springForm:form>

這是我的控制器方法:

 @RequestMapping(value="user/edit", method=RequestMethod.POST)
 public String doUserEdit(@Valid @ModelAttribute("user") UserEntity user, BindingResult result, Principal principal) {

    if(result.hasErrors()) {
        return "user/edit";
    }
    UserEntity u = this.userService.getUser(principal.getName());


    this.userService.editUser(u.getUser_id(), user);

    return "redirect:/user";
}

result.hasError()始終返回true,因為它還會驗證'userlogin'和'userpass'。

如何忽略編輯表單中的其他字段並僅驗證我想要的字段?

我通常創建一個單獨的表單類,僅適用於表單提交處理,並將所有必要的驗證放在這里:

public class UserUpdateForm {
    @NotEmpty
    private String name;
    @Email
    private String email;
    @NotEmpty
    @NumberFormat(style = Style.NUMBER)
    private String phone;

    //Getters and setters here
} 

這個想法是您將模型類從表示(表單)類中解開。 唯一的缺點是您必須以某種方式處理表單對象和模型對象之間的轉換。 推土機這樣的東西可能會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM