I would like to know, how I can get the User object from Thymeleaf. Currently I am calling my userService, which will get the user from the DB. I don't like this approach, because for every call a db query will be made.
Is it possible to get the user from memory?
<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;
}
If you are using spring security and thymeleaf, you could check:
https://github.com/thymeleaf/thymeleaf-extras-springsecurity3
For example:
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With