简体   繁体   中英

Grails data binding with command object

Could anyone explain to me how and which particular classes in grails does the data binding with command objects?

I am seeing some weird behavior in case of JSON post requests. For example, I have nested command objects that are registered with custom property editor. My custom property editor is being used only if I have collection of inner commands ie I am seeing setValue(Object obj) getting called in this case. For example,

class TestCommand
{
  List<InnerCommand> innerCommands = ListUtils.lazyList([], FactoryUtils.instantiateFactory(InnerCommand))
}

But when I have a simple nested command, my property editor does not get called which I dont want. For example,

class TestCommand
{
  InnerCommand cmd = new InnerCommand
}

In this case neither the setValue(Object obj) nor setAsString(String text) of my custom editor is getting called.

I am using post request with JSON input.Please let me know if anyone understands this behavior.

There are two way to implement command object in Grails

1) create command object inside controller 2) create command object inside src/groovy directory

both way must define annotations before class start "@grails.validation.Validateable"

1) type 1 LoginController.groovy

class LoginController{

       def login(){
            LoginCommand loginCommand=new LoginCommand()
            bindData(loginCommand, params)
           if(loginCommand.validate()){
             render 'login success'
           }else{
             render 'invalid user name or password'
           }
       }
    }

@grails.validation.Validateable
class LoginCommand {

        String emailId
        String password

        static constraints = {
        emailId blank:false,nullable:false,email:true
        password blank:false,nullable:false
    }

}

2) type 2 LoginCommand.groovy

@grails.validation.Validateable
class LoginCommand {

    String emailId
    String password

    static constraints = {
        emailId blank:false,nullable:false,email:true
        password blank:false,nullable:false
    }

}

Note: you need to pass 'emailId' and 'password' value from your .gsp page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM