title: Store username in database while doing rest or soap api calls from application A to application B in Java Spring 4
body: <p>I have two applications, in first application say A user login by username and password. I get logged in username by using spring authentication obejct in application A. Application A is making rest or soap api calls to application B. I am passing username from A to B  application by adding username in header of rest or soap calls. Application B is making database calls, doing CRUD on SQL database. I want to save that username in updated by, modified by fields. I used bean to store username but when multiple users are using application it's getting overwritten. How this can be achieved? Thank you </p>
  
  <p>In the following interceptor userSync will save my current logged in username, usernameGetter will be used to get current logged in username from http request. userSync and usernameGetter are singleton beans.</p>
  
  <pre><code>public class RequestInterceptor extends HandlerInterceptorAdapter {
  
  
  
  private DomainUserSynchronizer userSynchronizer;
  
  @Autowired
  UsernameGetter usernameGetter;
  
  @Autowired
  private UserSynchronizer userSync;
  
  private static final Logger LOGGER = LoggerFactory.getLogger(RequestInterceptor.class);
  
  
  
  @Override
  public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
          throws Exception {
  
      LOGGER.info("Inside after completion");
  }
  
  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
          throws Exception {
  
      // do nothing
  
  }
  
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
          throws Exception {
  
      HttpSession session = request.getSession();
  
      // Enumeration e = (Enumeration) (session.getAttributeNames());
  
       //session.getAttribute("an");
       //session.getAttribute("MYSPEAK_SESSION_HASH");
  
  
  
      String username = usernameGetter.getUsernameFromSession(request);
      if(username!=null &amp;&amp; !username.isEmpty()){
          LOGGER.info("Found username in request: "+ username);
          LOGGER.info("Setting username in userSynchronizer: "+ username);
          userSync.getCurrentUser().setName(username);
      }
      else{
          LOGGER.info(" Username not found in request: ");
          LOGGER.info("Setting default username in userSynchronizer: "+ userSync.getCurrentUser().getName());
  
      }   
  
      return true;
  }
  
  public DomainUserSynchronizer getUserSynchronizer() {
      return userSynchronizer;
  }
  
  public void setUserSynchronizer(DomainUserSynchronizer userSynchronizer) {
      this.userSynchronizer = userSynchronizer;
  }
  }
  </code></pre>