MyTwoCents
MyTwoCents

Reputation: 7622

Get all active HttpSession in RESTEasy implementaion

I need to get list of all the active Session so that I can manage them. Basically I need to manage all the logged in Users in application. Using HttpServletRequest req I am able to get current session but need to get all the sessions

Something like this:

     public EmployeeTO getEmployeeById(int id, HttpServletRequest req) {
        EmployeeTO employeeTO = null;
        try{

            HttpSession session = req.getSession();
            HttpSessionContext httpSessionContext = session.getSessionContext();


        }catch(Exception e){
            e.printStackTrace();
        }
        return employeeTO;
    }

Am using RESTFul implementation with JASS for Login

Upvotes: 0

Views: 675

Answers (1)

Vasu
Vasu

Reputation: 22452

I have a screen which shows the list of all active Users. If I check one User and click close session. I need to terminate that users session. To do that I need to have sessions somewhere accessible.

Using the HttpServletRequest, you will be able to get only the current request's (user's) session object. But if you want to track all session objects, you can do that by implementing HttpSessionListener as shown below:

  public class MyProjectSessionListenerAndInvalidator 
                                 implements HttpSessionListener {

     private static Map<String,Session> sessions = new HashMap<>();

      @Override
      public void sessionCreated(HttpSessionEvent event) {
          //add your code here, 
          //this will be invoked whenever there is a new session object created
           //Get the newly created session
           Session session = event.getSession();
           //get userId or unique field from session
           sessions.put(userId, session);
      }

      @Override
      public void sessionDestroyed(HttpSessionEvent event) {
         //add your code here
         //this will be invoked whenever there is a new session object removed

          //Get the removed session
          Session session = event.getSession();
          //get userId or unique field from session
          sessions.remove(userId);
      }

      public R getSessions() {
         //add code here
      }

      public void invalidateSession(String userId) {
         //add code here
      }
 }

N.B.: I recommend to use getSessions() and invalidateSession() carefully.

Upvotes: 1

Related Questions