介紹
學習grails,網上爲您準備了很多教程。我在網上找到一個視頻教程,介紹用Grails90分鐘創建一個簡單的Twitte應用程序,可以跟着視頻一步一步地學習。但視頻教程講的非常快,可能跟不上。所以我創建這個簡單的教程,供您參考。
我的假設是,你使用Grails2.0.0版本。除此之外,在本教程中我使用的插件有以下版本:searchable – 0.6.3 and springSecurityCore – 1.2.6.。 我使用的操作系統爲 Ubuntu。實際上,不同版本的插件,結果可能會有不同。
讓我們開始吧
每一個Grails項目的第一步都是是創建項目。啓動終端,並進入到所需的工作目錄。例如,我想在我的桌面上創建的項目文件夾,首先去那裏。
grails create-app simple-twitter
等待Grails的配置項目。配置完成後,進入項目所在目錄,並且安裝spring-security-core插件。
cd simple-twitter
grails install-plugin spring-security-core
插件將爲您的項目提供登錄和註銷功能。安裝插件後,輸入下面的代碼:
grails s2-quickstart org.grails.twitter Person Authority
這裏的org.grails.twitter 是Person 和 Authority類所在的包。Person 擁有Authority,Authority是賦予Person 的一個角色。
您會發現,在grails-app/domain/org/grails/twitter路徑下,系統爲我們創建了3個領域模型:
- Authority.groovy
- Person.groovy
- PersonAuthority.groovy
String realName
package org.grails.twitter
class Person {
transient springSecurityService
String realName
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
static constraints = {
username blank: false, unique: true
password blank: false
}
static mapping = {
password column: '`password`'
}
Set getAuthorities() {
PersonAuthority.findAllByPerson(this).collect { it.authority } as Set
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
}
首次運行項目時,讓我們創建一些虛擬的用戶爲我們工作。
在grails-app/conf的文件夾裏面,你可以找到BootStrap.groovy中的文件。項目運行時,這個文件首先被加載到服務器上並對項目進行初始化。讓我們編輯這個文件,在每一次服務器啓動時,自動填充虛擬用戶。
這個文件看起來想這個樣子:
import org.grails.twitter.*
class BootStrap {
def init = { servletContext ->
/* If there are no Persons in the record. */
if (!Person.count()) {
createData()
}
}
def destroy = {
}
private void createData() {
def userRole = new Authority(authority: 'ROLE_USER').save()
/* The default password for all user. No need to encode here to avoid double encoding. */
String password = 'password'
[yancy: 'Yancy Vance Paredes', john: 'John Doe', jane: 'Jane Smith'].each { userName, realName ->
def user = new Person(username: userName, realName: realName, password: password, enabled: true).save()
PersonAuthority.create user, userRole, true
}
}
}
現在讓我們來運行應用程序。
grails run-app
http://localhost:8080/simple-twitter
當您點擊 LoginController, 您會看到上面的頁面. 您如果要成功登錄,必須提供正確的用戶名和密碼。
您可以輸入任何用戶名,只要是在BootStrap.groovy文件中存在的。默認情況下,所有用戶的密碼是:“password”,不帶引號。
在接下來的教程中,我們將學習如何爲用戶添加狀態消息。