Getting Logged On User in a Spring-Web Application

DZone 's Guide to

Getting Logged On User in a Spring-Web Application

· Java Zone ·
Free Resource

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.

public class PageController {
  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView handleRequest() {
    User user = (User) SecurityContextHolder.getContext()
    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}" />

From http://www.davidsalter.com/2012/01/getting-logged-on-user-in-spring-web.html


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}