gpt4 book ai didi

java - 如何在所有模板中显示当前登录用户的信息,包括 Spring Security 应用程序中由 WebMvcConfigurerAdapter 管理的 View

转载 作者:搜寻专家 更新时间:2023-11-01 01:00:05 25 4
gpt4 key购买 nike

我有一个使用 Spring Security 和 Thymeleaf 模板的 Spring Boot 应用程序。当 Controller 由 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> 

但是没有用。

我知道可以按如下方式使用 ControllerAdvise:

@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 中注册的任何 View Controller 。相反,我需要确保我的每个 Controller 都是单独的类。

那么,有人可以指点我一种自动将登录用户详细信息插入到我的 View 中的方法吗,例如some-logged-in-page.html 在这个例子中?谢谢

最佳答案

这要归功于 Balaji Krishnan 的提示,这很容易实现。

基本上,我必须将 Thymeleaf Spring Security 集成模块添加到我的 build.gradle 文件中,如下所示:

compile("org.thymeleaf.extras:thymeleaf-extras-springsecurity3")

然后在我的模板中我只使用了以下标记:

<span th:text ="${#authentication.getPrincipal().getUser().getFirstName()}"></span>

关于java - 如何在所有模板中显示当前登录用户的信息,包括 Spring Security 应用程序中由 WebMvcConfigurerAdapter 管理的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35090329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com