我尝试使用JSR-303注释(类级别)和验证器实现为play 2.0.1编写自定义表单验证器.
不幸的是,当我提交表单并且验证失败时,我得到一个可能是游戏错误的IllegalStateException(但我想确认).
请在下面找到相关的代码摘录和问题描述(为了清晰起见,只有相关部分)
部分控制器代码(接收表单提交)
public static Result save() { Form<UserForm> userForm = form(UserForm.class).bindFromRequest(); if (userForm.hasErrors()) { return badRequest(createForm.render(userForm)); } UserForm user = userForm.get();
验证器声明为
public class FieldMatchValidator extends Validator<Object> implements ConstraintValidator<FieldMatch,Object>
验证注释声明为
@Target({TYPE,ANNOTATION_TYPE}) @Retention(RUNTIME) @Constraint(validatedBy = FieldMatchValidator.class) @play.data.Form.Display(name="constraint.fieldmatch") public @interface FieldMatch { String message() default FieldMatchValidator.message; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};
提交表单我收到错误
Caused by: java.lang.IllegalStateException: No value at play.libs.F$None.get(F.java:217) ~[play_2.9.1.jar:2.0.1] at play.data.Form.get(Form.java:363) ~[play_2.9.1.jar:2.0.1] at controllers.UsersController.save(UsersController.java:40) ~[classes/:2.0.1] at Routes$$anonfun$routes$1$$anonfun$apply$25$$anonfun$apply$26.apply(routes_routing.scala:189) ~[classes/:na] at Routes$$anonfun$routes$1$$anonfun$apply$25$$anonfun$apply$26.apply(routes_routing.scala:189) ~[classes/:na] at play.core.Router$HandlerInvoker$$anon$4$$anon$1.invocation(Router.scala:1086) ~[play_2.9.1.jar:2.0.1]
提到的UsersController的行是调用UserForm user = userForm.get();
试图了解问题所在,我发现有问题的代码可能在play的Form.java中.
Form绑定(Map data,String … allowedFields)包含:
if(result.hasErrors()) { for(FieldError error: result.getFieldErrors()) { ... } return new Form(rootName,backedType,data,errors,None()); }
并且hasErrors()是
public boolean hasErrors() { return !errors.isEmpty(); }
结果是result.hasErrors()返回true(因为在类级别定义的验证器失败),但构建的错误列表仍为空(result.getFieldErrors()返回一个空列表).
因此,Form.hasErrors()返回false但Form.get()失败.
我错过了什么或者它实际上是一个错误?
感谢致敬,