Over a million developers have joined DZone.

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

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

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

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}