Command对象
上一节中的多数据绑定中的表单内容和user对象、profile对象的字段是完全一一对应的,如果不是一一对应就会出现问题,这时,我们需要用到command对象。
假如,重写register功能,加入一个密码验证功能,验证密码字段在user对象是不存在的。
1、修改UserController,增加一个UserRegistrationCommand类
grails-app\controllers\com\grailsinaction\UserController.groovy
1 ...... 2 class UserRegistrationCommand { 3 String userId 4 String password 5 String passwordRepeat 6 byte[] photo 7 String fullName 8 String bio 9 String homepage 10 String email 11 String timezone 12 String country 13 String jabberAddress 14 15 static constraints = { 16 userId(size: 3..20) 17 password(size: 6..8, blank: false, 18 validator: { passwd, urc -> 19 return passwd != urc.userId 20 } 21 ) 22 passwordRepeat(nullable: false, 23 validator: { passwd2, urc -> 24 return passwd2 == urc.password 25 } 26 ) 27 fullName(nullable: true) 28 bio(nullable: true, maxSize: 1000) 29 homepage(url: true, nullable: true) 30 email(email: true, nullable: true) 31 photo(nullable: true) 32 country(nullable: true) 33 timezone(nullable: true) 34 jabberAddress(email: true, nullable: true) 35 } 36 }
2、使用这个command对象
修改grails-app\controllers\com\grailsinaction\UserController.groovy,增加一个register2 action
1 def register2 = { UserRegistrationCommand urc -> 2 if (urc.hasErrors()) { 3 return [ user : urc ] 4 } else { 5 def user = new User(urc.properties) 6 user.profile = new Profile(urc.properties) 7 if (user.save()) { 8 flash.message = "Welcome aboard, ${urc.fullName ?: urc.userId}" 9 redirect(uri: '/') 10 } else { 11 // maybe not unique userId? 12 return [ user : urc ] 13 } 14 } 15 }
3、新建register2.gsp注册页面
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Register New User (Command Object)</title> 5 <meta name="layout" content="main"/> 6 <style> 7 dd { 8 text-align: left; 9 margin-left: 80px; 10 margin-top: 5px; 11 } 12 </style> 13 </head> 14 15 <body> 16 <h1>Register New User (Command Object)</h1> 17 <g:hasErrors> 18 <div class="errors"> 19 <g:renderErrors bean="${user}" as="list" /> 20 </div> 21 </g:hasErrors> 22 <g:form action="register2"> 23 <dl> 24 <dt>User Id</dt><dd><g:textField name="userId" value="${user?.userId}"/></dd> 25 <dt>Password</dt><dd><g:passwordField name="password" value="${user?.password}"/></dd> 26 <dt>(repeat)</dt><dd><g:passwordField name="passwordRepeat" value="${user?.passwordRepeat}"/></dd> 27 <dt>Full Name</dt><dd><g:textField name="fullName" value="${user?.fullName}"/></dd> 28 <dt>Bio</dt><dd><g:textArea name="bio" value="${user?.bio}"/></dd> 29 <dt>Email</dt><dd><g:textField name="email" value="${user?.email}"/></dd> 30 <dt><g:submitButton name="register" value="Register"/></dt> 31 </dl> 32 </g:form> 33 </body> 34 </html>