How to access command objects from filter and is it possible at all?

人走茶凉 提交于 2019-12-06 06:42:49

No, it isn't possible to do what you are asking. Command Objects are not full framework artifacts like Controller, Service, etc, and so they do not get their validation logic added to them, unless they are a parameter to a Controller action. To that end a Command Object in a filter wouldn't have a .validate() or .hasErrors() method to check against.

As another option you could use the @Validateable annotation:

http://grails.org/doc/latest/guide/7.%20Validation.html#7.5%20Validation%20Non%20Domain%20and%20Command%20Object%20Classes

Move your Command Object to src/groovy as a regular Groovy class and annotate it with @Validateable. Then in your filter you can do:

def validObj = new MyValidateable(params)
if (!validObj.validate()) {
    response.sendError( HttpServletResponse.SC_BAD_REQUEST );
    return false;
} else {
    return true;
}

Make sure you add the package name of your validateable class to the grails.validateable.packages List in Config.groovy.

What about creating a service like this:

class AutoValidateService {
    def onValid(def cmd, Closure onValid) {
        if( cmd.hasErrors() ){
            return render(status:HttpServletResponse.SC_BAD_REQUEST );
        }else{
            onValid()
        }
    }
}

The use it like so:

class FooController {

    AutoValidateService autoValidateService

    def myAction{ MyActionCommand cmd ->
        autoValidateService.onValid(cmd) {
            // do something
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!