Play Framework 2.5:视图模型绑定请求返回'null'

时间:2016-04-14 05:46:23

标签: java playframework playframework-2.0 playframework-2.5

我尝试使用bindFromRequest()将我的视图与模型绑定,但视图和模型不绑定,模型给出null值。

这是我的控制器

package controllers;

import play.mvc.*;
import play.data.Form;
import views.html.*;
import models.Login;
import controllers.*;
import com.avaje.ebean.Model;

public class LoginController extends Controller {

    public Result authenticate() {
        Form<Login> loginForm = Form.form(Login.class).bindFromRequest();

        //  password value is return null.
        System.out.println("password :: "+loginForm.get().password); 
        if (loginForm.hasErrors()) {
          return ok(login.render("Error in login" ,Form.form(Login.class)));
        } else  { }
    }
}

这是Model Login.java

import com.avaje.ebean.Model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Login extends Model {

  @Id
  public String id;
  public String email;
  public String password;

}

这是Login View login.html:

     <form class="login-form" action="@routes.LoginController.authenticate" method="post">

      <h1><a href="@routes.LoginController.index" id="logo"><span>
        <img src="@routes.Assets.at("/images/logo-main.jpg")" alt="PUAthletics" height="42" >
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("/images/logo-main.jpg")"/></span></a></h1>
      <p class="loginMessage ">
      @message
      </p>
      <input type="email" name="email" placeholder="Email" value="@form("email").value" />
      <input type="password" name="password" placeholder="Password"/>
      <button type="submit" class="submit-upld">Login</button>
     </form>

1 个答案:

答案 0 :(得分:0)

我猜你在这里得到了NPE:

System.out.println("password :: "+loginForm.get().password); 

如果是这样,那是因为表单有错误。如果您的表格有效,您应该先检查:

if (loginForm.hasErrors()) {
   return badRequest(login.render("Error in login" , loginForm);
}

然后检索您的模型。考虑将无效数据类型传递到表单的情况,在这种情况下Play不能构建模型。