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

不羁的心 提交于 2020-01-13 19:11:06

问题


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 the 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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/7432514/how-to-access-command-objects-from-filter-and-is-it-possible-at-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!