在FreeMarker模板中,您可以使用内置的Session
对象来访问当前会话
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome, ${session.user.name}!</h1>
</body>
</html>
在这个例子中,我们直接使用了${session.user.name}
来获取当前已验证用户的名称。请注意,您可能需要根据实际情况调整属性名称,例如,如果您的用户对象存储在名为currentUser
的属性中,那么您需要使用${session.currentUser.name}
。
如果您在Java代码中使用了Spring Security,您可以通过以下方式在FreeMarker模板中获取当前已验证的用户:
Principal
对象暴露给FreeMarker模板:@Bean
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPath("/WEB-INF/views/");
Map<String, Object> sharedVariables = new HashMap<>();
sharedVariables.put("principal", (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
configurer.setFreemarkerVariables(sharedVariables);
return configurer;
}
${principal}
来访问当前已验证的用户对象。例如,要显示用户的名称,可以使用${principal.username}
。<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome, ${principal.username}!</h1>
</body>
</html>
请根据您的实际情况调整代码示例。
领取专属 10元无门槛券
手把手带您无忧上云