How to print user first name and last name from <sec:authentication property="principal.username"/>
This principal.username
only prints user Id. But I want here to print the user first and last name from database. Is it possible?
I guess you are talking about Spring Security.
Here is a solution I used:
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.
}
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;
}
}
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With