简体   繁体   中英

Grails command object initialization

In my Grails 2.3.8 app, I've defined the following controller action

class RegisterController {

    def register(User user) {
        render text: "User name is '$user.name'"
    }
}

The user argument is a domain class instance. If I invoke this controller with the URL

http://localhost:8080/myapp/register/register

I get a NullPointerException . However my understanding of databinding is that if this action is invoked without any parameters, the argument should be assigned a new User()

However my understanding of databinding is that if this action is invoked without any parameters, the argument should be assigned a new User()

That is not necessarily the case. For domain class command objects if no parameters are present a new instance is only created for POST requests.

From http://grails.org/doc/2.4.0.RC1/guide/theWebLayer.html#commandObjects ...

If the command object's type is a domain class and there is no id request parameter 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.

That text may be missing from the 2.3.8 docs. I will verify that and add it if necessary.

What if you modify:

'$user.name'

To be:

'${user?.name}'

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