2011-12-16 25 views
0

在Grails中將模型變量傳遞給佈局的最佳方式是什麼?具體來說,我使用的是具有User類的Spring安全插件。我也有跟類,看起來像這樣:在佈局上獲取域變量

class Contact { 

    String realname 
    String company 
    String mobile 
    String fix 
    String email 
    User user 
     ... 

什麼是獲取當前登錄的人的公司在我的佈局(main.gsp)的選項?

回答

1

要添加到上面的答案,您可以替換爲用戶設置一個會話變量,當你登錄任何控制器方法被調用。

您也可以只設置一個會話變量爲公司在控制器方法:

session.company = Contact.findByUser(session.user)?.company 

或以上

session.company = Contact.findByUser(SecurityContextHolder.context.authentication?.principal)?.company 

中的示例和你main.gsp,是這樣的:

<span id="companyName">${session.company}</span> 
+1

在這種情況下,您應該實現自己的authSuccesshandler和logoutHandler,並將該變量放入(並在註銷時除去)到該會話中,而不是在控制器 – 2011-12-16 14:38:35

1

您的意思是說,您需要自動將此模型傳遞給每個頁面,而不是手動將它傳遞給每個控制器上的渲染?您可以使用filters有:

def filters = { 
    all(controller: '*', action: '*') { 
     before = { 
      request.setAttribute('loggedInPerson', SecurityContextHolder.context.authentication?.principal) 
      //Notice, that there is used original Authentication, from Spring Security 
      //If you need you can load your Contact object there, or something 
     } 
     after = { 

     } 
     afterView = { 

     } 
    } 
} 

,並在你的GSP使用loggedInPerson

Hello ${loggedInPerson.username}! 

順便說一下,也有Spring Security tags,可以幫助你不使用你自己的過濾器,如:

​​
0

如果要將某個對象添加到模型中,還可以使用「intercepto rs「由grails提供。要將某個變量添加到特定控制器,可以使用類似這樣的東西。

def afterInterceptor = {model, modelAndView-> 

    model.loggedInUser = getLoggedInUser() // retrieve your user details here 

} 

而且你可以在main.gsp佈局${loggedInUser}檢索loggedInUser

如果您需要在多個控制器中獲取這些詳細信息,則可以創建BaseController並將afterInterceptor保存在此BaseController中。所有需要在相應視圖中引用登錄用戶的控制器應擴展BaseController