8.1.10 Command Objects

Grails controllers support the concept of command objects. A command object is a class that is used in conjunction with data binding, usually to allow validation of data that may not fit into an existing domain class.

A class is only considered to be a command object when it is used as a parameter of an action.

Declaring Command Objects

Command object classes are defined just like any other class.

  1. class LoginCommand implements grails.validation.Validateable {
  2. String username
  3. String password
  4. static constraints = {
  5. username(blank: false, minSize: 6)
  6. password(blank: false, minSize: 6)
  7. }
  8. }

In this example, the command object class implements the Validateable trait. The Validateable trait allows the definition of Constraints just like in domain classes. If the command object is defined in the same source file as the controller that is using it, Grails will automatically make it Validateable. It is not required that command object classes be validateable.

By default, all Validateable object properties which are not instances of java.util.Collection or java.util.Map are nullable: false. Instances of java.util.Collection and java.util.Map default to nullable: true. If you want a Validateable that has nullable: true properties by default, you can specify this by defining a defaultNullable method in the class:

  1. class AuthorSearchCommand implements grails.validation.Validateable {
  2. String name
  3. Integer age
  4. static boolean defaultNullable() {
  5. true
  6. }
  7. }

In this example, both name and age will allow null values during validation.

Using Command Objects

To use command objects, controller actions may optionally specify any number of command object parameters. The parameter types must be supplied so that Grails knows what objects to create and initialize.

Before the controller action is executed Grails will automatically create an instance of the command object class and populate its properties by binding the request parameters. If the command object class is marked with Validateable then the command object will be validated. For example:

  1. class LoginController {
  2. def login(LoginCommand cmd) {
  3. if (cmd.hasErrors()) {
  4. redirect(action: 'loginForm')
  5. return
  6. }
  7. // work with the command object data
  8. }
  9. }

If the command object’s type is that of a domain class and there is an id request parameter then instead of invoking the domain class constructor to create a new instance a call will be made to the static get method on the domain class and the value of the id parameter will be passed as an argument.

Whatever is returned from that call to get is what will be passed into the controller action. This means that if there is an id request parameter and no corresponding record is found in the database then the value of the command object will be null. If an error occurs retrieving the instance from the database then null will be passed as an argument to the controller action and an error will be added the controller’s errors property.

If the command object’s type is a domain class and there is no id request parameter or there is an id request parameter and its value is empty then null will be passed into the controller action unless the HTTP request method is "POST", in which case a new instance of the domain class will be created by invoking the domain class constructor. For all of the cases where the domain class instance is non-null, data binding is only performed if the HTTP request method is "POST", "PUT" or "PATCH".

Command Objects And Request Parameter Names

Normally request parameter names will be mapped directly to property names in the command object. Nested parameter names may be used to bind down the object graph in an intuitive way.

In the example below a request parameter named name will be bound to the name property of the Person instance and a request parameter named address.city will be bound to the city property of the address property in the Person.

  1. class StoreController {
  2. def buy(Person buyer) {
  3. // ...
  4. }
  5. }
  6. class Person {
  7. String name
  8. Address address
  9. }
  10. class Address {
  11. String city
  12. }

A problem may arise if a controller action accepts multiple command objects which happen to contain the same property name. Consider the following example.

  1. class StoreController {
  2. def buy(Person buyer, Product product) {
  3. // ...
  4. }
  5. }
  6. class Person {
  7. String name
  8. Address address
  9. }
  10. class Address {
  11. String city
  12. }
  13. class Product {
  14. String name
  15. }

If there is a request parameter named name it isn’t clear if that should represent the name of the Product or the name of the Person. Another version of the problem can come up if a controller action accepts 2 command objects of the same type as shown below.

  1. class StoreController {
  2. def buy(Person buyer, Person seller, Product product) {
  3. // ...
  4. }
  5. }
  6. class Person {
  7. String name
  8. Address address
  9. }
  10. class Address {
  11. String city
  12. }
  13. class Product {
  14. String name
  15. }

To help deal with this the framework imposes special rules for mapping parameter names to command object types. The command object data binding will treat all parameters that begin with the controller action parameter name as belonging to the corresponding command object.

For example, the product.name request parameter will be bound to the name property in the product argument, the buyer.name request parameter will be bound to the name property in the buyer argument the seller.address.city request parameter will be bound to the city property of the address property of the seller argument, etc…​

Command Objects and Dependency Injection

Command objects can participate in dependency injection. This is useful if your command object has some custom validation logic which uses a Grails service:

  1. class LoginCommand implements grails.validation.Validateable {
  2. def loginService
  3. String username
  4. String password
  5. static constraints = {
  6. username validator: { val, obj ->
  7. obj.loginService.canLogin(obj.username, obj.password)
  8. }
  9. }
  10. }

In this example the command object interacts with the loginService bean which is injected by name from the Spring ApplicationContext.

Binding The Request Body To Command Objects

When a request is made to a controller action which accepts a command object and the request contains a body, Grails will attempt to parse the body of the request based on the request content type and use the body to do data binding on the command object. See the following example.

grails-app/controllers/bindingdemo/DemoController.groovy

  1. package bindingdemo
  2. class DemoController {
  3. def createWidget(Widget w) {
  4. render "Name: ${w?.name}, Size: ${w?.size}"
  5. }
  6. }
  7. class Widget {
  8. String name
  9. Integer size
  10. }
  1. $ curl -H "Content-Type: application/json" -d '{"name":"Some Widget","42"}'[size] localhost:8080/demo/createWidget
  2. Name: Some Widget, Size: 42
  3. $ curl -H "Content-Type: application/xml" -d '<widget><name>Some Other Widget</name><size>2112</size></widget>' localhost:8080/bodybind/demo/createWidget
  4. Name: Some Other Widget, Size: 2112
The request body will not be parsed under the following conditions:-The request method is GET-The request method is DELETE-The content length is 0

Note that the body of the request is being parsed to make that work. Any attempt to read the body of the request after that will fail since the corresponding input stream will be empty. The controller action can either use a command object or it can parse the body of the request on its own (either directly, or by referring to something like request.JSON), but cannot do both.

grails-app/controllers/bindingdemo/DemoController.groovy

  1. package bindingdemo
  2. class DemoController {
  3. def createWidget(Widget w) {
  4. // this will fail because it requires reading the body,
  5. // which has already been read.
  6. def json = request.JSON
  7. // ...
  8. }
  9. }

Working with Lists of Command Objects

A common use case for command objects is a Command Object that contains a collection of another:

  1. class DemoController {
  2. def createAuthor(AuthorCommand command) {
  3. // ...
  4. }
  5. class AuthorCommand {
  6. String fullName
  7. List<BookCommand> books
  8. }
  9. class BookCommand {
  10. String title
  11. String isbn
  12. }
  13. }

On this example, we want to create an Author with multiple Books.

In order to make this work from the UI layer, you can do the following in your GSP:

  1. <g:form name="submit-author-books" controller="demo" action="createAuthor">
  2. <g:fieldValue name="fullName" value=""/>
  3. <ul>
  4. <li>
  5. <g:fieldValue name="books[0].title" value=""/>
  6. <g:fieldValue name="books[0].isbn" value=""/>
  7. </li>
  8. <li>
  9. <g:fieldValue name="books[1].title" value=""/>
  10. <g:fieldValue name="books[1].isbn" value=""/>
  11. </li>
  12. </ul>
  13. </g:form>

There is also support for JSON, so you can submit the following with correct databinding

  1. {
  2. "fullName": "Graeme Rocher",
  3. "books": [{
  4. "title": "The Definitive Guide to Grails",
  5. "isbn": "1111-343455-1111"
  6. }, {
  7. "title": "The Definitive Guide to Grails 2",
  8. "isbn": "1111-343455-1112"
  9. }],
  10. }