大佬教程收集整理的这篇文章主要介绍了重构Grails命令验证,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
def add(CreatePersonCommand command) { if(command.hasErrors()) { redirect(action: 'add') return } }
我不喜欢这种重复,所以我想重构它.我希望Grails会有如下内容:
@Validate(action:'someAction') def add(CreatePersonCommand command) { }
要么
def add(@Valid CreatePersonCommand command) { }
哪个会自动验证命令,并在出现错误时重定向到GSP.我尝试用拦截器和过滤器创建这样的东西,但我失败了,因为我无法访问过滤器中的操作和命令.
有一个像这样的命令:
@grails.validation.Validateable class FooCommand implements serializable { String username String email static consTraints = { username nullable: false,blank: false,minSize: 6 email email: true,nullable: false,blank: false } }
并且具有动作索引的Controller仅在params验证命令对象时执行,并且在验证错误的情况下重定向到动作错误:
class FooController { def index() { render 'ok!' } def error() { render 'errors = ' + params.errors } }
然后,您可以为所有请求(或您想要的请求)定义过滤器,并根据请求尝试的控制器和操作,您可以使用所需的参数验证命令对象,如下所示:
class FooFilters { def filters = { all(controller:'*',action:'*') { before = { if (params.controller == 'foo' && (!params.action || params.action == 'index')) { FooCommand cmd = new FooCommand(params.subMap(['username','email'])) if (!cmd.validate()) { redirect controller: 'foo',action: 'error',params: [errors:cmd.errors] return false } } return true } } } }
以上是大佬教程为你收集整理的重构Grails命令验证全部内容,希望文章能够帮你解决重构Grails命令验证所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。