技术开发 频道

精通 Grails:用定制URI和codec优化Grails中的URI

  创建 User 类

  Blogito 虽然已经支持条目,但它尚不支持用户。因此,必须先创建一个新的 User 类。

  首先,在命令行提示符键入 grails create-domain-class User。接下来,将清单 1 内的代码添加到 grails-app/domain/User.groovy:

  清单 1. User 类

class User {
  static constraints
= {
    login(unique:
true)
    password(password:
true)
    name()
  }
  
  static hasMany
= [entries:Entry]
  
  
String login
  
String password
  
String name
  
  
String toString(){
    name
  }
}

  login 和 password 字段的作用不言自明;它们用来处理身份验证。name 字段用于显示的目的。比如,如果用 jsmith 登录,将会显示 “Jane Smith”。正如您所见,User 和 Entry 之间存在着一对多的关系。

  将 static belongsTo 字段添加到 grails-app/domain/Entry.groovy,以完成一对多的关系,如清单 2 所示:

  清单 2. 向 Entry 类添加一对多的关系

class Entry {
  static belongsTo
= [author:User]
  
//snip
}

  我们注意到,在定义关系时,可以很容易地重命名此字段。User 类具有一个名为 entries 的字段。Entry 类现在具有一个名为 author 的字段。

  通常,在此时,都会创建一个相关的 UserController 以提供一个完整的 UI 来管理 Users。我却没有打算这么做。我只是想用几个无存根的 Users 作为占位符。在下一篇 精通 Grails 的文章中,您将更为全面地了解用户身份验证和授权的相关内容。因此,我们走 “刚刚好” 的路线,通过使用 grails-app/conf/BootStrap.groovy 添加几个新用户,如清单 3 所示:

  清单 3. 在 BootStrap.groovy 中使用无存根 Users

import grails.util.GrailsUtil

class BootStrap {

  def init
= { servletContext ->
    switch(GrailsUtil.environment){
      
case "development":
        def jdoe
= new User(login:"jdoe", password:"password", name:"John Doe")
        def e1
= new Entry(title:"Grails 1.1 beta is out",
           summary:
"Check out the new features")
        def e2
= new Entry(title:"Just Released - Groovy 1.6 beta 2",
           summary:
"It is looking good.")
        jdoe.addToEntries(e1)
        jdoe.addToEntries(e2)
        jdoe.save()
        
        def jsmith
= new User(login:"jsmith", password:"wordpass", name:"Jane Smith")
        def e3
= new Entry(title:"Codecs in Grails", summary:"See Mastering Grails")
        def e4
= new Entry(title:"Testing with Groovy", summary:"See Practically Groovy")
        jsmith.addToEntries(e3)
        jsmith.addToEntries(e4)
        jsmith.save()              
      break

      
case "production":
      break
    }

  }
  def destroy
= {
  }
}

  请注意,我是如何将条目分配给一个 User 的。您无需担心处理主键或外键的麻烦。Grails Object Relational Mapping (GORM) API 让您能从对象的角度而不是关系数据库理论来进行思考。

  接下来,对在 上一篇 文章中所创建的 grails-app/views/entry/_entry.gsp 局部模板稍作处理。在 Entry.lastUpdated 字段的旁边显示作者,如清单 4 所示:

  清单 4. 向 to _entry.gsp 添加作者

<div class="entry">
  
<span class="entry-date">
    
<g:longDate>${entryInstance.lastUpdated}</g:longDate> : ${entryInstance.author}
  
</span>
  
<h2><g:link action="show" id="${entryInstance.id}">${entryInstance.title}
    
</g:link></h2>                  
  
<p>${entryInstance.summary}</p>
</div>

  ${entryInstance.author} 在 User 类上调用 toString() 方法。也可以使用 ${entryInstance.author.name} 来显示您所选择的字段。还可以使用此语法随心所欲地遍历这些类的嵌套结构。

  现在,我们就可以看看所做的这些变更的实际效果了。键入 grails run-app 并在 Web 浏览器内访问 http://localhost:9090/blogito/。屏幕应该类似于图 1:

  图 1. 显示了新添加的作者的条目  

  现在 Blogito 可以支持多个用户,下一步是让读者能按作者来查看这些条目。

0
相关文章