在Spring中如何从“< sec:authentication property =" principal.username" />"”中打印用户名和姓氏 [英] In Spring How to print user first name and last name from "<sec:authentication property="principal.username"/>"
问题描述
如何从打印用户名和姓?< sec:authentication property =principal.username/>
此 principal.username
仅打印用户ID。但我想在这里打印用户名和数据库的名字。可能吗?
This principal.username
only prints user Id. But I want here to print the user first and last name from database. Is it possible?
推荐答案
我想你在谈论Spring Security。
I guess you are talking about Spring Security.
这里是我使用的解决方案:
Here is a solution I used:
创建一个将映射用户的类。它必须实现接口 org.springframework.security.core.userdetails.UserDetails :
Create a class that will map your users. It have to implements the interface org.springframework.security.core.userdetails.UserDetails :
public class MyUserDetails implements UserDetails {
private String username;
private String password;
private String firstname;
private String lastname;
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
// Etc.
}
创建 org.springframework.security.core.userdetails.UserDetailsService 的实现,它将从数据库加载您的用户:
Create an implementation of org.springframework.security.core.userdetails.UserDetailsService that will load your users from the database :
@Component
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private MyUserDAO userDAO;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final MyUserDetails user = userDAO.getUserByUsername(username);
if(user == null) {
throw new UsernameNotFoundException("No user found for username '" + username +"'.");
}
return user;
}
}
现在您必须告诉Spring Security使用您的服务从您的用户加载详细信息:
Now you have to tell Spring Security to use your service to load the details from your users :
<authentication-manager>
<user-service id="myUserDetailsService"/>
</authentication-manager>
现在你应该可以使用< sec:authentication property = principal.firstname/>
和< sec:authentication property =principal.lastname/>
显示名字和姓氏当前用户。
Now you should be able to use <sec:authentication property="principal.firstname"/>
and <sec:authentication property="principal.lastname"/>
to display the firstname and the lastname of the current user.
这篇关于在Spring中如何从“< sec:authentication property =" principal.username" />"”中打印用户名和姓氏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!