Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the IP address when a session is created?

In my grails application, I have implemented the interface HttpSessionListener to listen for session creation as given below:

class MyHttpSessionListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        log.info "***************** Session created: id= ${event.getSession()?.id}"
    }
}

Now, I would like to log the IP address that is responsible for the session creation.

How can I do that?

like image 593
fabien7474 Avatar asked Aug 29 '10 23:08

fabien7474


2 Answers

you can access the RequestContextHolder and get the value

String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
           .getRequest().getRemoteAddr();
like image 97
Aaron Saunders Avatar answered Sep 24 '22 00:09

Aaron Saunders


As far as I know you can't using the HttpSessionListener interface.

You can get and log the IP Address from "ServletRequest.getRemoteAddr()" but you don't have access to the servlet request from HttpSessionListener or from HttpSessionEvent.

Best idea would to have a javax.servlet.Filter which gets the IP address and sets it as a session attribute if not already present. (You could also do the logging if not already present).

like image 45
Cristian Vat Avatar answered Sep 25 '22 00:09

Cristian Vat