开发者

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

I often write something like:



    def myAction{ MyActionCommand cmd ->
       if( cmd.hasErrors() ){
          return render(status:HttpServletResponse.SC_BAD_REQUEST );
       }else{
          // actual action logic
       }


So, I'd like to extract that common pattern into some reusable location. Filter looks like good candidate, but I can't find the way to get command object from th开发者_运维百科e filter. Tryed something like this (in filters closure):



    formValidation( controller:'*', action:'*' ){
       before = { cmd ->
          if( cmd.hasErrors() ){
              response.sendError( HttpServletResponse.SC_BAD_REQUEST );
              return false;
          }else{
              return true;
          }
       }
    }


Intersted in grails 1.3.7 compatible solution. Is it possible at all?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜