In 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.
@Controller
public class PageController {
@RequestMapping(method = RequestMethod.GET)
public ModelAndView handleRequest() {
User user = (User) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
Map<String, Object> userModel = new HashMap<String, Object>();
userModel.put("username", user.getUsername());
return new ModelAndView("page", "model", userModel);
}
}
The username can then be displayed in an HTML page as:
<c:out value="${model.username}" />