title: spring auto populate user details for every request
body: <p>I have a spring MVC based web application. Currently in my web page i am showing the user first name and last name after user logs in. The way i am doing this is, for every HttpServletRequest that comes into @Controller@RequestMapping, i get the Principal object and get the user details from it, then populate the ModelMap with firstname and lastname attribute. For example here is the sample code</p>
  
  <pre><code>@Autowired
  private SecurityDetails securityDetails;
  
  @RequestMapping(method = RequestMethod.GET)
  public String showWelcomePage(HttpServletRequest request,
          HttpServletResponse response, ModelMap model, Principal principal)
  {
      securityDetails.populateUserName(model, principal);
              ... lot of code here;
      return "home";
  }
  
  
  
  public boolean populateUserName(ModelMap model, Principal principal) {
      if (principal != null) {
          Object ob = ((Authentication)principal).getPrincipal();
          if(ob instanceof MyUserDetails)
          {
              MyUserDetails ud = (MyUserDetails)ob;
              model.addAttribute("username", ud.getFirstName() + " " + ud.getLastName());
          }
          return true;
      }
      else
      {
          logger.debug("principal is null");
          return false;
      }
  }
  </code></pre>
  
  <p>My problem is i am having to call the populateUserName method for every RequestMapping. Is there a elegant way, like populating this in Interceptor method, which will result in this method being called just in one place for entire application?</p>