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

喜欢而已 提交于 2019-12-30 09:38:36

问题


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?


回答1:


you can access the RequestContextHolder and get the value

String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
           .getRequest().getRemoteAddr();



回答2:


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).




回答3:


You can also use this interface in your HttpSessionListener : ServletRequestListener You can implement : requestInitialized() like this.

@Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
    this.request = (HttpServletRequest) servletRequestEvent.getServletRequest();
}

it s working fine, the request object can bring you the remote adress, there is a méthod to do that



来源:https://stackoverflow.com/questions/3597083/how-to-get-the-ip-address-when-a-session-is-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!