动态查询和实体查询
1、实现一个简单的查询表单
首先,在/grails-app/views/user/新建一个search.gsp,建立一个查询表单
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Search Hubbub</title> 5 <meta name="layout" content="main"/> 6 </head> 7 8 <body> 9 <formset> 10 <legend>Search for Friends</legend> 11 <g:form action="results"> 12 <label for="userId">User Id</label> 13 <g:textField name="userId" /> 14 <g:submitButton name="search" value="Search"/> 15 </g:form> 16 </formset> 17 </body> 18 </html>
这里有一些grails标签库的标记,后续会详细列出来
访问这个页面时,惯例会访问http://localhost:8080/hubbub/user/search打开这个页面,所以需要在UserController中增加访问方法。form表单提交给results这个action,在UserController中处理这个业务逻辑,现在定制UserController
1 package com.grailsinaction 2 3 class UserController { 4 5 def scaffold = true 6 7 def search = { 8 } 9 10 def results = { 11 /*基于页面参数,找到userId*/ 12 def users = User.findAllByUserIdLike(params.userId) 13 return [ users: users, term : params.userId ] 14 } 15 }
这句def users = User.findAllByUserIdLike(params.userId)有点小毛病,如果信息是模糊查询,强制要求用户使用%%通配符,修改一下,看看Grails的魔法
def users = User.findAllByUserIdLike("%${params.userId}%")
现在已经将search表单提交给results闭包了,并且闭包已经获取到返回数据了,下一步就是将数据结果返回给用户
在/grails-app/views/user/新建一个results.gsp页面文件
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Search Results</title> 5 <meta name="layout" content="main"/> 6 </head> 7 8 <body> 9 <h1>Results</h1> 10 <p>Searched ${com.grailsinaction.User.count()} records 11 for items matching <em>${term}</em>. 12 Found <strong>${users.size()}</strong> hits. 13 </p> 14 15 <ul> 16 <g:each var="user" in="${users}"> 17 <li>${user.userId}</li> 18 </g:each> 19 </ul> 20 <g:link action='search'>Search Again</g:link> 21 </body> 22 </html>
${users.size()}:统计命中的用户总数
<g:each var="user" in="${users}">:遍历UserController->results->users
<li>${user.userId}</li>: 显示用户账号
2、加点缺省数据到系统
修改conf/bootstarp.groovy
1 import com.grailsinaction.Profile 2 import com.grailsinaction.User 3 4 class BootStrap { 5 6 def init = { servletContext -> 7 environments { 8 development { 9 createAdminUserIfRequired() 10 } 11 test { 12 createAdminUserIfRequired() 13 } 14 production { 15 println "No special configuration required" 16 } 17 } 18 } 19 20 def destroy = { 21 } 22 23 void createAdminUserIfRequired() { 24 if (User.count() == 0) { 25 println "Fresh Database. Creating ADMIN user." 26 def profile = new Profile(email: "[email protected]") 27 def user = new User(userId: "admin", password: "secret", profile: profile).save() 28 } else { 29 println "Existing admin user, skipping creation" 30 } 31 } 32 }
3、运行系统,访问http://localhost:8080/hubbub/user/search看效果吧。