5

我想知道,我如何能從Thymeleaf獲得用戶對象。目前我正在調用我的userService,它將從DB獲取用戶。我不喜歡這種方法,因爲每次調用db查詢都會進行。春季開機+百里香:獲取登錄用戶

是否有可能從內存中獲取用戶?

<link href="/css/style2.css" 
    th:if="${@commanderService.getCurrentCommander()} and 
     ${@commanderService.getCurrentCommander().settings == 'template=1'}" 
    rel="stylesheet" type="text/css" /> 

CommanderService:

public Commander getCurrentCommander() { 
    Object principal = 
     SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
    Commander commander = findByName((String)principal); 

    return commander; 
} 
+0

你有機會獲得本金'RequestMappingMethod' – 2014-12-02 18:18:38

+0

您是否使用自定義的UserDetailsS​​ervice?如果是這樣,你能提供你的實施? – 2014-12-03 15:55:48

+0

羅伯特:是的,但它的空 - 它只有findUserByName方法返回null – 2014-12-03 17:59:13

回答

3

如果您正在使用彈簧安全和thymeleaf,你可以檢查: https://github.com/thymeleaf/thymeleaf-extras-springsecurity3
例如:

<div sec:authentication="name"> 
    The value of the "name" property of the authentication object should appear here. 
</div> 

<div sec:authorize="hasRole('ROLE_ADMIN')"> 
    This content is only shown to administrators. 
</div> 
+0

會給你只有安全對象的名稱 - 我需要的是從用戶對象的其他字段 – 2014-12-03 08:41:21

+0

我明白@AlexTbk,如果你需要完整的用戶對象一個選項是將其添加到模型中,或者您也可以像顯示的那樣訪問它。如果您需要定義是否爲某些類型的用戶添加了某些樣式表,則角色可能會有所幫助。 – 2014-12-03 14:05:57

+0

這是一個好主意 - 我可以爲該樣式表設置一個特殊角色。多數民衆贊成在此,謝謝! – 2014-12-03 17:58:15