Mar*_*lic 2 html java spring thymeleaf spring-boot
我试图为每个页面提供以下模型,以便我可以检查当前用户是否已登录,从而控制每个页面的标题菜单项,但我不想总是返回 index.html 。有什么办法可以返回自己吗?
@RequestMapping(value = "/**", method = RequestMethod.GET)
String index(Model model) {
Users user = usersRepository.findOne(1 L);
if (user != null) {
String currentRole = user.getRole().toString();
model.addAttribute("currentRole", currentRole);
// System.out.println("Current Role: " + currentRole);
} else {
model.addAttribute("currentRole", "ANONYMOUS");
}
return "index";
}
Run Code Online (Sandbox Code Playgroud)
我的菜单:
<li th:switch="${currentRole}">
<!-- Is Employee, so show "My Requests" -->
<div th:case="EMPLOYEE">
<a href="#" th:href="@{/requests}">
<div style="float: left; margin-right: 10px;">My Requests</div>
<!-- Handle notifications here -->
<div style="overflow: hidden" id="circle">1</div>
</a>
</div>
<!-- Is Manager, so show "My Approvals" -->
<div th:case="MANAGER">
<a href="#" th:href="@{/requests}">
<div style="float: left; margin-right: 10px;">My Approvals</div>
<!-- Handle notifications here -->
<div style="overflow: hidden" id="circle">1</div>
</a>
</div>
</li>
<li><a href="#" th:href="@{/team}">My Team</a></li>
<!-- Is logged in, so don't show "Log In" -->
<li th:unless="${currentRole}">
<a href="/login" th:href="@{/login}" class="btn-login">Log In</a>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 Spring 安全性,Thymeleaf 有一个集成模块可以直接在您的模板中处理此问题,因此您可能甚至不需要模型中的用户名。将依赖项添加到相应版本的org.thymeleaf.extras:thymeleaf-extras-springsecurity4.
然后将 xmlns 添加到您的 html
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
Run Code Online (Sandbox Code Playgroud)
你可以做
<div th:text="${#authentication.name}">
The value of the "name" property of the authentication object should appear here.
</div>
Run Code Online (Sandbox Code Playgroud)
有关Spring Security 集成模块的更多信息
| 归档时间: |
|
| 查看次数: |
1625 次 |
| 最近记录: |