简体   繁体   中英

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.

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

Method: POST

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

Request Body : { "name": "Vinod", "age": 34 }

I get employee.name as null and employee.age=0 always

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. To get a hold on JSON request you have to call

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'

Grails constructs command object from JSON in request body of POST(JSON to 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.

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.

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.validation.Validateable
class Employee implements Validateable{
    String name
    int age
}

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