Java – finds the number of active sessions created from a given client IP
Is there a way to determine the number of active sessions created from a given client IP address?
Solution
The standard servlet API does not provide such facilities The best way is to maintain a map < httpsession, string > (where string is the IP address), check httpsession #isnew() on each ServletRequest, and add it to the map together with ServletRequest #getremoteaddr() You can then use collections #frequency () in map #values () using an active session You just need to ensure that httpsession is removed from the map during httpsessionlistener#sessiondestroyed()
All this can be done in a single listener that implements servletcontextlistener, httpsessionlister, and ServletRequestListener
This is an example of a kick-off:
public class SessionCounter implements servletcontextlistener,HttpSessionListener,ServletRequestListener {
private static final String ATTRIBUTE_NAME = "com.example.SessionCounter";
private Map<HttpSession,String> sessions = new ConcurrentHashMap<HttpSession,String>();
@Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute(ATTRIBUTE_NAME,this);
}
@Override
public void requestInitialized(ServletRequestEvent event) {
HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
HttpSession session = request.getSession();
if (session.isNew()) {
sessions.put(session,request.getRemoteAddr());
}
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
sessions.remove(event.getSession());
}
@Override
public void sessionCreated(HttpSessionEvent event) {
// NOOP. Useless since we can't obtain IP here.
}
@Override
public void requestDestroyed(ServletRequestEvent event) {
// NOOP. No logic needed.
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP. No logic needed. Maybe some future cleanup?
}
public static SessionCounter getInstance(ServletContext context) {
return (SessionCounter) context.getAttribute(ATTRIBUTE_NAME);
}
public int getCount(String remoteAddr) {
return Collections.frequency(sessions.values(),remoteAddr);
}
}
On the web XML is defined as follows:
<listener>
<listener-class>com.example.SessionCounter</listener-class>
</listener>
You can use it in any servlet, as follows:
SessionCounter counter = SessionCounter.getInstance(getServletContext());
int count = counter.getCount("127.0.0.1");
