我想知道如何从Thymeleaf获取User对象。当前,我正在调用userService,它将从数据库获取用户。我不喜欢这种方法,因为对于每个调用都会进行数据库查询。
是否可以从内存中获取用户?
<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;
}
最佳答案
如果您正在使用Spring Security和 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>
关于 Spring Boot + thymeleaf : get logged in user,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27253060/