0

I'm using JavaEE and have an HttpSessionListener implementation that I am trying to use to get an IP address when a client creates a session. How do I do this?

My webapp is 2.4 (cannot change this, I'm afraid):

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

Here is my session created method:

public void sessionCreated(HttpSessionEvent se) {
        System.err.println("Session source: " + se.getSource());

        System.err.println("SessionLifecycleListener:sessionCreated() not implemented yet");
        HttpSession s = se.getSession();
        printAll(s.getAttributeNames(), "HttpSession attribute names");

        ServletContext sc = s.getServletContext();
        printAll(sc.getAttributeNames(), "ServletContext attribute names");
    }

How do I get the IP address given the HttpSessionEvent?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
mikeb
  • 8,943
  • 4
  • 43
  • 94

1 Answers1

0

This is not possible via standard Servlet API. The IP address is only available via HttpServletRequest and this is in turn nowhere available when having only HttpSession at hands.

Some if not all servlet based (MVC) frameworks offer the possibility to grab the associated HTTP request as a thread local variable (TLS), such as JSF, Grails, Spring, etc. If you aren't using such a framework and thus can't rely on its API, then you'd need to homegrow a TLS yourself as illustrated in this answer How can I get HttpServletRequest from ServletContext? Ultimately, grab it in sessionCreated() as below:

HttpServletRequest request = YourContext.getCurrentInstance().getRequest();
// ...

Alternatively, let the servlet filter check if the is new and then copy the IP address in there.

if (session.isNew()) {
    session.setAttribute("ip", ip);
}

Which you then extract in the sessionCreated().

String ip = (String) event.getSession().getAttribute("ip");

Do note that this is not reliably possible in sessionDestroyed() as there's not necessarily means of a HTTP request during sessionDestroyed(). See also How to get request object in sessionDestroyed method?

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452