2013-06-30 82 views
8

我是grails的新手。我必須和會議一起工作。我見過會議文件。但不知道在哪裏把代碼放在我的控制器中。我有一個學生創建名稱createStudent的頁面。現在我希望只有當用戶進入會話時才能訪問此頁面。現在我該怎麼做。我必須在登錄時將用戶設置爲變量。任何人都可以幫助我嗎?如何在grails中使用會話

def index() { 
    def user = session["user"] 
    if (user){ 
     redirect(controller: 'admistratorAction', action: 'createUser') 
    }else{ 
     redirect(controller: 'login', action: 'index') 
    } 

} 

回答

12

您可以使用您的控制器內session.getAttribute(key)session.setAttribute(key, value)方法。或者,也有插件,如Spring Security Core Plugin,已經處理得很好。

Peter Ledbrook爲Spring Security插件here提供了一個很好的教程,插件文檔鏈接到至少一個其他教程。

**編輯**

如你所說,爲了使用會話用戶直接將需要在會話在較早的點進行設置。例如:

def setCurrentStudent() { 
    def aStudent = [name: "Student1"] 
    session["user"] = aStudent 
    render "Added $aStudent to the session." 
} 

Spring Security將在登錄時自動執行此操作。然後,可以使用springSecurityService隨時訪問當前用戶。

class SomeController { 
    def springSecurityService 
    def someAction = { 
     def user = springSecurityService.currentUser 
     … 
    } 
} 
+0

感謝您的回覆。我已經在使用Spring Security Core插件了。但我不知道如何使用它的會話。我在編輯器中給出了一個示例源代碼。如果條件爲false,它將重定向到登錄頁面。但如果爲true,則不會重定向createUser頁面。你現在可以幫忙嗎?! –

+0

我不確定我完全理解這個問題 - 爲什麼你需要直接使用會話?我用一些代碼片段更新了我的答案。希望能幫助到你。 – osborp

+0

感謝@osborp它現在有所幫助。我將在稍後討論會議的細節。但現在這是基本的 –