我在使用Java PLay 2.2.1中的Form解析java.util.Date类型时遇到错误。我的示例类的模型是:

   @Entity
   public class SampleModel extends Model
  {
  @Id
  Long id;

  @Temporal(javax.persistence.TemporalType.TIMESTAMP)
  @Required(message="endHour must be specified.")
  @Formats.DateTime(pattern="yyyyMMddhhmmss")

  private Date date;

  public setId(Long id){

    this.id = id;
  }

  public Long getId(){

    return this.id;
  }

  public setDate(Date date){

    this.date = date;
  }

  public Date getDate(){

      return this.date;
  }


}

表单在控制器中的使用就像:

public class ControllerSample extends Controller{

   public static Result create(){

       JsonNode request = request().body().asJson();

       Form<SampleModel> form = Form.form(SampleModel.class).bind(request);

       if(form.hasErrors())
       {
          //It always get Errors with dates
       }
       ....

       return ok();
   }
}


最后,我发布的JSON就是这样的:

{"date":"20140318120000"}


我找不到Form正确解析Date对象的方式。有人可以指导我吗?

最佳答案

您可以注册绑定表单和请求时要使用的custom databinder
只要看一下官方文档中的示例,您就可以安全地用LocalTime替换他们正在使用的Date

编辑:哦,别忘了在form request绑定之前注册databinder,以便它对绑定有影响。

09-30 14:00
查看更多