Reputation: 3898
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
Upvotes: 1
Views: 1142
Reputation: 3898
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)
Upvotes: 1
Reputation: 199
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
}
Upvotes: -1
Reputation: 20699
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 )
Upvotes: 1