gpt4 book ai didi

Spring 启动+ thymeleaf : get logged in user

转载 作者:行者123 更新时间:2023-12-02 03:18:01 24 4
gpt4 key购买 nike

我想知道如何从 Thymeleaf 获取 User 对象。目前我正在调用我的 userService,它将从数据库获取用户。我不喜欢这种方法,因为每次调用都会进行数据库查询。

是否可以从内存中获取用户?

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

指挥官服务:

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 启动+ thymeleaf : get logged in user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27253060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com