我正在使用Spring和Thymeleaf开发一个Java项目。 我已经为用户配置了一个工作类,该工作类存储了存储在服务器上的图片的字符串。 它工作得很好,我成功地在主块中调用它。在我的项目的上半部分,我有一个导航面板,在我的html的标题部分中描述。完整的HTML看起来像这样: 的layout.html:
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head th:include="fragments/head" th:with="pageTitle='Java Project'"></head>
<body>
<header th:include="fragments/header"></header>
<main th:include="${view}"></main>
<footer th:include="fragments/footer"></footer>
<span th:include="fragments/scripts-bundle"></span>
</body>
</html>
现在,我根据提供的上层代码成功调用了定义视图变量的主块中的user.picture。这是一个有效的例子:
这是主要块中的视图:
……
<th:block th:each="user : ${users}">
<tr th:class="${user.isAdmin() ? 'info' : null}">
…………
<td> <img class="img-circle" th:src="@{/images/users/{picture}(picture=${user.picture})}" height="43" width="43"/></td>
………
</tr>
</th:block>
……
视图由Controller中的这部分代码调用:
@GetMapping("/")
public String listUsers(Model model){
List<User> users = this.userRepository.findAll();
model.addAttribute("users", users);
model.addAttribute("view", "admin/user/list");
return "layout";
}
在用户类中,我有:
….
private String picture;
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
…..
一切正常。
现在我想在视图中调用相同的代码,但是要在描述导航面板的fragment / header部分中执行此操作。 我不能成功地做到这一点。 根据我的谦虚知识,我看到了两种方法:
1 /在百万美元视图中按控制器代码注入用户: 试过像:
@GetMapping("/fragments/header")
@PreAuthorize("isAuthenticated()")
public String setPicHead(Model model){
UserDetails principal = (UserDetails) SecurityContextHolder.getContext()
.getAuthentication()
.getPrincipal();
User user = this.userRepository.findByEmail(principal.getUsername());
model.addAttribute("user", user);
model.addAttribute("fragments/header", user);
return "fragments/header";
}
In the fragments/header html I added:
<li sec:authorize="isAuthenticated()">
<img class="img-circle" th:src="@{/images/users/(picture=${user.picture})}" height="43" width="43"/>
</li>
根本不起作用并锁定整个项目
2 /我猜第二种方法是使用Thymeleaf功能独立调用用户。我猜 这可以做到,因为Thymeleaf拥有完整的引擎功能。有人可以帮我这个吗? 提前谢谢。
答案 0 :(得分:0)
我找到了解决方案:
在这里注射:
@GetMapping("/")
public String index(Model model) {
UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = this.userRepository.findByEmail(principal.getUsername());
model.addAttribute("user", user);
model.addAttribute("view", "home/index");
return "layout";
}
在标题部分,它是这样的:
<li sec:authorize="isAuthenticated()">
<img class="img-circle" th:src="@{/images/users/{one}(one=${user.picture})}" height="49" width="49"/>
</li>
如果有人在Thymeleaf中与直接身份验证共享解决方案,我会很高兴。