Today, I am going to explain how to use command object in grails application to validate the client information without using domain class. You will see the benefits of using command object in this blog.

The command object’s purpose is to bind the data from web-form parameters into a non-domain class that offers its own validation.

  • Benefits
    Benefit of command object class over domain class is that command object don’t persist data into the database. As you know domain class is persisting class and directly interact with database to store it’s properties value, so we ignore as much as we can to use domain class.
    To solve this problem command object comes into play. These are light weight object and not interact with database. A class is only considered to be a command object when it is used as a parameter of an action of controller. When we use this class as an action parameter of controller then controller initialize the command object and bind the request parameter with this object. Now, move towards a little example which gives clear understanding about it.

First we make a User domain class

class User {

    String username
    String password

    static constraints = {
        username size: 5..15, blank: false, unique: true
        password size: 5..15, blank: false
    }
}

Now, we make a groovy class named UserCommand.groovy. Command object class is defined in the same source file as the controller that is using it. This is not a convention. We can make command object class anywhere in our web-application but one condition should be satisfy, that we have to mark this class with @grails.validation.Validateable annotation.

Note: Grails controllers support the concept of command objects. When we defined this class in the same source as controller, grails automatically mark this class as
@grails.validation.Validateable.

@grails.validation.Validateable
    class UserCommand {

    String username
    String password

    static constraints = {
        importFrom User
    }
}
  • Note: importFrom statement import all static constraints apply on User domain and apply it to command class domain. We can also add some extra validation here.
  • Now, we make a User controller with a login action.
class UserController {

    def login(UserCommand cmd) {
        if (cmd.hasErrors()) {
            redirect(action: 'loginForm')
            return
        } else {
	    // now we have valid parameter comes from client side
	    //any login realated task 
        }
    }
}
  • Here we define a controller with a login action & UserCommand object as parameter. Now whenever any request comes for this action from client, the controller validate the username & password by using command object. We don’t need to interact with domain class for validation. This command object works as mediator between User domain and client request. If validation fails it returns the error on the same page(login form).

Hope this helps 🙂 .