Getting Logged On User in a Spring-Web Application
Join the DZone community and get the full member experience.
Join For FreeIn a web application, it can be useful to get the logged on user's name
and display it within a web page, for example as a link to allow the
user to edit their profile. In a Spring Web application the username
can easily be obtained in a controller and passed via a map to the user
interface.
To get the username in a controller class, we would use the SecurityContextHolder.getContext().getAuthentication().getPrincipal() method to get hold of the principal. We can then call the .getUsername() method to get the username of the currently logged on user.
The username can then be displayed in an HTML page as:
<c:out value="${model.username}" />
From http://www.davidsalter.com/2012/01/getting-logged-on-user-in-spring-web.html
Opinions expressed by DZone contributors are their own.
Comments