简体   繁体   English

Grails命令对象未绑定

[英]Grails Command Object not getting Bound

I am doing a POC for Command object in Grails Controller and i face a road block where the binding doesn't happen. 我正在Grails Controller中为Command对象做POC,我遇到了没有发生绑定的障碍。

Command Object 命令对象

public class Employee {

    String name;

    int age;

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Controller : 控制器:

class EmployeeController {

    def index() {

        render (" Employee Index Called ");
    }

    def emp(Employee employee){

        println( employee.toString());
        render(" Success");

    }
}

I am calling emp action from a rest client as below 我正在从其他客户打电话给emp行动,如下所示

Method: POST 方法:开机自检

URL : http://localhost:8080/Grails/employee/emp 网址http:// localhost:8080 / Grails / employee / emp

Request Body : { "name": "Vinod", "age": 34 } 请求正文{“ name”:“ Vinod”,“ age”:34}

I get employee.name as null and employee.age=0 always 我将employee.name设置为null,并且employee.age = 0始终

I am suspecting my Request Body is wrong but not sure. 我怀疑我的请求正文有误,但不确定。 Please help where I am going wrong. 请帮我哪里错了。

Thanks 谢谢

As far as I know, json is not bound automatically to command object (defined as action method arg), only plain params are. 据我所知,json不会自动绑定到命令对象(定义为动作方法arg),只有普通params可以绑定。 To get a hold on JSON request you have to call 要保留JSON请求,您必须致电

def json = request.JSON

and then you can try binding it to your object: 然后您可以尝试将其绑定到您的对象:

def co = new MyCommandObject( json )

For POST request method, I had to set 'Content-Type' header as 'application/json' 对于POST请求方法,我必须将“ Content-Type”标头设置为“ application / json”

Grails constructs command object from JSON in request body of POST(JSON to Java Object) Grails在POST的请求正文中从JSON构造命令对象(JSON到Java Object)

Whenever Grails finds 'Content-Type' header as 'application/json' it will automatically parse the request body in JSON to command object and pass it on to the controller method. 每当Grails找到“ Content-Type”标头作为“ application / json”时,它将自动将JSON中的请求正文解析为命令对象,并将其传递给控制器​​方法。

You may also want to make the command class validatable by doing the following. 您可能还想通过执行以下操作使命令类可验证。 In Grails 3: Your command class can to implement grails.validation.Validateable trait. 在Grails 3中:您的命令类可以实现grails.validation.Validateable特征。

import grails.validation.Validateable

class Employee implements Validateable{
    String name
    int age
}

In Grails 2.x: You command class can have grails.validation.Validateable annotation 在Grails 2.x中:您的命令类可以具有grails.validation.Validateable批注

@grails.validation.Validateable
class Employee implements Validateable{
    String name
    int age
}

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

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