3

I have a jetty container with two different servlets, lets call then A and B. In a special occasion a qr code code appear in servlet A (the user is already logged in and is using his desktop) and the user by using his mobile device read this qr code and is redirected the servlet B on his mobile device. The problem here is that i cant keep his session.

The QR code brings the user session key however i have no way to verify if this session is valid. I would like to know if there is any special method to request the valid session keys on jetty, since both servlet are in the same server.

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Winter
  • 1,896
  • 4
  • 32
  • 41

1 Answers1

8

Well the best solution i found was to establish a HttpSessionListener :) for that we have to override some methods:

public class HttpSessionCollector implements HttpSessionListener {
private static final Map<String, HttpSession> sessions = new HashMap<String, HttpSession>();

@Override
public void sessionCreated(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    sessions.put(session.getId(), session);
}


@Override
public void sessionDestroyed(HttpSessionEvent event) {
    sessions.remove(event.getSession().getId());
}

public static HttpSession find(String sessionId) {
    return sessions.get(sessionId);
}

public static Map<String, HttpSession> getSessions() {
    return sessions;
}

}

and then set the listener on /WEB-INF/web.xml

<web-app>
  <listener>
    <listener-class>[yourpack].HttpSessionCollector</listener-class>
  </listener>
...
</web-app>

Now we can call at anywhere inside the package the HttpSessionCollector. e.g. to obtain all valid sessions we have just to:

private Map<String, HttpSession> sessions;
sessions=HttpSessionCollector.getSessions(); 
Winter
  • 1,896
  • 4
  • 32
  • 41
  • 1
    conceptually quite nice. a further improvement might be the use of something not in-memory (a redis or mongodb store might do nicely) for reasons of scale. synchronization could potentially become an issue as well – jsh Aug 13 '13 at 18:51