简体   繁体   English

Grails与命令对象的数据绑定

[英]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. 在JSON发布请求的情况下,我看到了一些奇怪的行为。 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. 仅当我具有内部命令的集合时才使用我的自定义属性编辑器,即在这种情况下看到setValue(Object obj)被调用。 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. 在这种情况下,自定义编辑器的setValue(Object obj)或setAsString(String text)都不会被调用。

I am using post request with JSON input.Please let me know if anyone understands this behavior. 我正在使用带有JSON输入的发布请求。如果有人了解此行为,请告诉我。

There are two way to implement command object in Grails 在Grails中有两种方法来实现命令对象

1) create command object inside controller 2) create command object inside src/groovy directory 1)在控制器内创建命令对象2)在src / groovy目录内创建命令对象

both way must define annotations before class start "@grails.validation.Validateable" 两种方式都必须在类开始之前定义批注“ @ grails.validation.Validateable”

1) type 1 LoginController.groovy 1)输入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 2)输入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. 注意:您需要从.gsp页面传递'emailId'和'password'值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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