Springboot / Thymeleaf从每个页面的模型检查当前用户

时间:2017-02-08 21:22:17

标签: java html spring spring-boot thymeleaf

我试图为每个页面提供以下模型,以便我可以检查当前用户是否已登录,从而控制每个页面的标题菜单项,但我不想总是回报指数。有没有办法让自己回归?

@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";
}

我的菜单:

<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>

2 个答案:

答案 0 :(得分:3)

如果您使用的是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">

你可以做到

<div th:text="${#authentication.name}">
    The value of the "name" property of the authentication object should appear here.
</div>

有关Spring Security Integration module

的更多信息

答案 1 :(得分:2)

当你使用Spring时,你可以创建@ControllerAdvice类并放置所需的逻辑,就像这样(未经测试)

@ControllerAdvice
public class UserRoleAdvice {

    // ... autowire needed services

    @ModelAttribute("currentRole")
    public String currentRole() {
        Users user = usersRepository.findOne(1 L);
        if (user != null) {
            return user.getRole().toString();
        } else {
            return "EMPLOYEE";
        }
    }
}

这将为所有页面添加此参数...