Grails:如何处理JSR 303 bean验证

时间:2012-02-15 14:13:07

标签: java grails bean-validation

我在Grails应用程序中使用Java实体类作为域对象。这些类具有JSR 303验证注释(@ Size,@ NotEmpty等)。

Grails控制器和视图可以正常使用这些实体类,但是当我尝试保存具有破坏约束的实例(@NotEmpty字段的空值)时,我得到一个包含以下内容的错误页面:

/webcall-account-manager-2/company/save
Class
javax.validation.ConstraintViolationException
Message
Validation failed for classes [com.rcslabs.webcall.server.model.Company] during persist time for groups [javax.validation.groups.Default, ] List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='may not be empty', propertyPath=name, rootBeanClass=class com.rcslabs.webcall.server.model.Company, messageTemplate='{org.hibernate.validator.constraints.NotBlank.message}'} ]

Around line 27 of grails-app/controllers/com/rcslabs/webcall/server/model/CompanyController.groovy
24:    def save() {
25:        def companyInstance = new Company()
26:     companyInstance.properties = params
27:        if (!companyInstance.save(flush: true)) {
28:            render(view: "create", model: [companyInstance: companyInstance])
29:            return
30:        }

Trace
    Line | Method
->>  251 | call      in org.grails.datastore.gorm.InstanceMethodInvokingClosure
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|     27 | save      in CompanyController.groovy
|   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    603 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
^    679 | run . . . in java.lang.Thread

如何以正确的方式处理它(字段上方的消息框)?

1 个答案:

答案 0 :(得分:0)

不是100%肯定,因为我从未使用过JSR 303和Grails,但你可以在保存之前调用.validate。当你调用.save时,它正在运行验证,这似乎是抛出异常。因此,尝试手动执行验证调用,然后您应该能够以与if块中使用的方式类似的方式返回错误。