java 创建会话时如何获取IP地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3597083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:34:49  来源:igfitidea点击:

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

javagrailsservletshttpsession

提问by fabien7474

In my grailsapplication, I have implemented the interface HttpSessionListenerto listen for session creation as given below:

在我的grails应用程序中,我实现了接口HttpSessionListener来监听会话创建,如下所示:

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.

现在,我想记录负责创建会话的 IP 地址

How can I do that?

我怎样才能做到这一点?

回答by Aaron Saunders

you can access the RequestContextHolder and get the value

您可以访问 RequestContextHolder 并获取值

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

回答by Cristian Vat

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

据我所知,您不能使用 HttpSessionListener 接口。

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.

您可以从“ServletRequest.getRemoteAddr()”获取并记录 IP 地址,但您无权从 HttpSessionListener 或 HttpSessionEvent 访问 servlet 请求。

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

最好的办法是使用 javax.servlet.Filter 来获取 IP 地址并将其设置为会话属性(如果尚不存在)。(如果尚未存在,您也可以进行日志记录)。

回答by Pierre-Olivier Pignon

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

你也可以在你的 HttpSessionListener 中使用这个接口: ServletRequestListener 你可以像这样实现: requestInitialized() 。

@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

它工作正常,请求对象可以为您带来远程地址,有一种方法可以做到这一点