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