DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Getting Logged On User in a Spring-Web Application

Getting Logged On User in a Spring-Web Application

David Salter user avatar by
David Salter
·
Jan. 18, 12 · Java Zone · Interview
Like (0)
Save
Tweet
10.39K Views

Join the DZone community and get the full member experience.

Join 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.

@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}" />

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

Web application

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 5 Steps to Create a Successful Agile Release Plan
  • Complete Guide to TestOps
  • Data Mesh — Graduating Your Data to Next Level
  • Spring, IoC Containers, and Static Code: Design Principles

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo