如何在所有模板中显示当前登录用户的信息,包括由WebMvcConfigurerAdapter在Spring Security应用程序中管理的视图
2022-09-03 03:31:43
我有一个使用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;
}
...
}
在我的模板中,我尝试使用像这样的代码
<div sec:authentication="firstName"></div>
但它没有奏效。
我知道可以使用控制器通知,如下所示:
@ControllerAdvice
public class CurrentUserControllerAdvice {
@ModelAttribute("currentUser")
public UserDetails getCurrentUser(Authentication authentication) {
return (authentication == null) ? null : (UserDetails) authentication.getPrincipal();
}
}
然后使用如下代码访问模板中的详细信息:
<span th:text ="${currentUser.getUser().getFirstName()}"></span>
但这不适用于在我的类MvcConfig注册的任何视图控制器。相反,我需要确保我的每个控制器都是单独的类。
那么,有人可以给我指出一种自动将登录用户详细信息插入我的视图的方法,例如,在这个例子中,某些登录页面.html?谢谢