如何在所有模板中显示当前登录用户的信息,包括Spring Security应用程序中由WebMvcConfigurerAdapter管理的视图
我有一个使用Spring Security和Thymeleaf模板的Spring Boot应用程序。 当控制器由WebConfigurerAdapter的子类管理时,我试图在模板中显示登录用户的名字和姓氏。
所以,说我的WebConfigurerAdapter子类看起来像这样
@Configuration public class MvcConfig extends WebMvcConfigurerAdapter{ @Override public void addViewControllers(ViewControllerRegistry registry){ registry.addViewController("/some-logged-in-page").setViewName("some-logged-in-page"); registry.addViewController("/login").setViewName("login"); } .... }
我的用户实体类看起来像这样
@Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false, updatable = false) private Long id; @Column(name="first_name", nullable = false) private String firstName; public String getFirstName() { return firstName; } ... }
在我的模板中,我尝试使用类似的代码
但它没有用。
我知道可以使用ControllerAdvise,如下所示:
@ControllerAdvice public class CurrentUserControllerAdvice { @ModelAttribute("currentUser") public UserDetails getCurrentUser(Authentication authentication) { return (authentication == null) ? null : (UserDetails) authentication.getPrincipal(); } }
然后使用以下代码访问模板中的详细信息:
但这不适用于在我的MvcConfig类中注册的任何视图控制器。 相反,我需要确保每个控制器都是单独的类。
那么,是否有人可以指出我自动将登录的用户详细信息插入到我的视图中的方法,例如本例中的some-logged-in-page.html? 谢谢
由于Balaji Krishnan的暗示,这很容易实现。
基本上,我必须将Thymeleaf Spring Security集成模块添加到我的build.gradle文件中,如下所示:
compile("org.thymeleaf.extras:thymeleaf-extras-springsecurity3")
然后在我的模板中我使用了以下标记:
使用Spring Security 4和Thymeleaf 3时:
这个结构对我有用(春季靴子1.5和2.0 /百里香叶3):
这里记录(页面底部) Thymeleaf + Spring Security集成基础知识
Logged user: Bob
不要忘记在视图的html部分中包含sec标记:
我希望这有帮助!
祝你今天愉快!
托马斯
正如@ B378所说,当使用Spring Security 4和Thymeleaf 3时:你必须使用以下内容。
因为Spring安全性在内部使用UserDetails。 UserDetails包含一个名为getUsername()的函数。
- 这个方法怎么给我一个-61错误?
- Selenium 3.0 Firefx驱动程序因org.openqa.selenium.SessionNotCreatedException而失败:无法创建新的远程会话
- BackgroundSubtractorMOG2中“history”的含义是什么?
- Google GSON嵌套了HashMaps反序列化
- 如何防止jsoup转换特殊字符?
- 在Java中获取k个最小(或最大)数组元素的最快方法是什么?
- 如何解析比NumberFormat在Java中更严格的数字?
- 尝试在Spring MVC中使用OAuth保护资源
- 如何在不破坏Maven发布插件的情况下传递javac多个命令行参数,其中一些包括冒号?