Playframework 2.2:验证很火,没有在pojo上添加验证注释

时间:2014-12-26 13:53:14

标签: java playframework-2.0 validationerror

当我提交表单时,playframework会激活验证,但是在pojo类中,我没有定义任何Annotations进行验证。验证仅在两个字段上激活。我的代码如下:

POJO班级:

public class User {
public int id;
public String name;
public int age;

public User() {}

public User(int id, String name, int age){
    this.id = id;
    this.name = name;
    this.age = age;
}

@Override
public String toString() {
    return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}

我的控制器方法:

public Result saveUser() {
    Form<User> userData = userForm.bindFromRequest();
    if(userData.hasErrors()){
        flash("error", "Please enter valid values");
        return badRequest(add_user.render(userData));
    }
    User user = userData.get();
    boolean result = userService.addNewUser(user);
    if(result){
        flash("success", String.format("Add user success %s", user));
    }else{
        flash("error", String.format("Fail to save user, Please contact admin %s", user));
    }
    return redirect(routes.UserController.newUsers());
}

HTML表单:

@(userForm: Form[com.harmeetsingh13.entities.User])
@import helper._
@import helper.twitterBootstrap._

@main("New User"){
<h1 style="margin-left: 20px;">User Form</h1>
@helper.form(action = com.harmeetsingh13.controllers.routes.UserController.saveUser(), 
        'id -> "userForm", 'style -> "margin-left: 20px;"){
    <fieldset>
        <legend>User (@userForm("name").valueOr("New"))</legend>
        @helper.inputText(userForm("id"), '_label -> "ID")
        @helper.inputText(userForm("name"), '_label -> "Name")
        @helper.inputText(userForm("age"), '_label -> "Age")
    </fieldset>
    <input type="submit" class="btn btn-primary" value="Save" />
}
}

当我提交表单时,我收到以下错误:

enter image description here

1 个答案:

答案 0 :(得分:-1)

我不知道,为什么会发生这种情况,但play-framework默认使用基本类型。当我将我的pojo User的数据类型从int更改为String时,验证不会自动触发。我仍然没有在play-framework中找到关于这些类型的验证的任何内容,但这确实困扰了开发人员。