重构Grails命令验证

时间:2014-07-14 17:28:13

标签: grails groovy

在我的应用程序中,我有很多代码如下:

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。我尝试用拦截器和过滤器创建这样的东西,但我失败了,因为我无法访问过滤器中的操作和命令。

也许我错过了一些东西,但有没有更好的方法来解决这个问题,或者实现类似上述的东西?

2 个答案:

答案 0 :(得分:0)

考虑到问题中的评论,我想出了一个暂时的解决方法。

拥有如下命令:

@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
    }
}

具有操作index的Controller只有在params验证命令对象且操作error重定向到验证错误时才执行:

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
            }
        }
    }
}

此代码可以通过多种方式进行改进。但我认为这足以作为一个示例解决方案。

答案 1 :(得分:0)

虽然不完全是你要求的我写了一个插件,但它做了类似的事情。它使用和AST来添加处理程序,如果没有提供,它还使用默认处理程序增强控制器。但是,处理程序只给出了具有Command的命令对象,作为名称的最后一部分,因为插件也试图给命令对象更多的约定。

http://plugins.grails.org/plugin/virtualdogbert/command