Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (10.2k points)
edited by

I have a Spring MVC web app which uses Spring Security. I want to know the username of the currently logged in user. I'm using the code snippet given below . Is this the accepted way?

I don't like having a call to a static method inside this controller - that defeats the whole purpose of Spring, IMHO. Is there a way to configure the app to have the current SecurityContext, or current Authentication, injected instead?

  @RequestMapping(method = RequestMethod.GET)

  public ModelAndView showResults(final HttpServletRequest request...) {

    final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();

    ...

  }

1 Answer

0 votes
by (46k points)
edited by

You can try this in Spring 3, the simplest method is:

Are you interested in learning Java from the basics! Refer to this video on Java provided by Intellipaat:

@RequestMapping(method = RequestMethod.GET)

public ModelAndView showResults(final HttpServletRequest request, Principal principal) {

final String currentUser = principal.getName();

}

Browse Categories

...