title: How to get/modify all user sessions from a Spring @Service bean (using Struts mvc)?
body: <p>I am implementing a notification service that notifies all users (with active sessions) about new notifications. Since this web application uses Struts MVC (not a single page application), the use of the Web Socket didn't seem appropriate as every page load would require a new WS connection. Instead, my approach was to run a Spring @Service every minute to update all the active users session with a "Unread_Notification_Count" so each page load could simply check the user's session for this value and change the display accordingly (eliminating a database query for every page load).</p>
  
  <p>I have 2 questions: 1) Is this the best approach to solve this problem as I've read in the Spring docs that you should avoid changing users sessions directly. 
   2) If this approach is "ok", then how do I access each users session to insert/change the "Unread_Notification_Count" value?</p>
  
  <pre><code>@Service("notifySessionsService")
  public class NotifySessionsServiceImpl implements NotifySessionsService {
  
      @Autowired
      private transient SessionRegistry sessionRegistry;
  
      @Override
      public void updateUnReadNotificationCount() {
  
          for (Object principal : sessionRegistry.getAllPrincipals()) {
              List&lt;SessionInformation&gt; sessionInformationList = sessionRegistry.getAllSessions(principal, false);
              for (SessionInformation sessionInformation : sessionInformationList) {
                  System.out.println("Updating session for user: "  + ((User)principal).getUsername() + ", sessionId: " + sessionInformation.getSessionId());
                  // [Get users notification count here]
                  // [Put in session, e.g. session.put("Unread_Notification_Count", count)]
              }
          }
  
      }
  
      public void setSessionRegistry(SessionRegistry sessionRegistry) {
          this.sessionRegistry = sessionRegistry;
      }
  }
  </code></pre>