本文介紹了如何在所有模板中顯示當前登錄用戶的信息,包括在Spring安全應用程序中由WebMvcConfigurerAdapter管理的視圖的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個Spring Boot應用程序,它使用了Spring Security和Thymeleaf模板。當控制器由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注冊的任何視圖控制器。相反,我需要確保我的每個控制器都是單獨的類。
那么,有人能告訴我一種自動將登錄的用戶詳細信息插入到我的視圖中的方法嗎,例如本例中的一些-Logging-in-Page.html?謝謝
推薦答案
由于Balaji Krishnan的提示,實現這一點非常容易。
基本上,我必須將Thymeleaf Spring安全集成模塊添加到我的build.gradle文件中,如下所示:
compile("org.thymeleaf.extras:thymeleaf-extras-springsecurity3")
然后在我的模板中,我只使用了以下標記:
<span th:text ="${#authentication.getPrincipal().getUser().getFirstName()}"></span>
這篇關于如何在所有模板中顯示當前登錄用戶的信息,包括在Spring安全應用程序中由WebMvcConfigurerAdapter管理的視圖的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,