【问题标题】:Can't get client IP in Grails无法在 Grails 中获取客户端 IP
【发布时间】:2014-10-06 15:52:51
【问题描述】:

我正在尝试编写一个简单的 Grails 控制器来返回用户的位置。

当我硬核 IP 地址时,位置部分可以正常工作。问题在于获取用户的IP地址。

运行以下代码时,出现以下错误:

“方法没有签名:helloworld.HelloController.getRemoteAddr() 适用于参数类型:() 值:[]”

错误似乎是由以下行引起的:

def ipAddress = getRemoteAddr()

我通过运行 grails 应用程序的机器上的 localhost:8090/helloworld/hello/index 和笔记本电脑上的 192.168.0.10:8090/helloworld/hello.index 进行连接。

我的其余代码:

类 HelloController {

def geoIpService

def index() {

    def ip = getIpAddress()
    def location = geoIpService.getLocation(ip)
    render location.countryName + " " + location.city     
}           

def getIpAddress(javax.servlet.http.HttpServletRequest request) {
    // def ipAddress = getRemoteAddr()

    def ipAddress = getRemoteAddr()

    if (ipAddress && InetAddressValidator.VALIDATOR.isValid(ipAddress)){
        log.debug("Remote IP Address ::: " + ipAddress)

        return ipAddress
    }

    ipAddress = request.getHeader("X-Forwarded-For")

    if(ipAddress && InetAddressValidator.VALIDATOR.isValid(ipAddress)) {
        log.debug("Remote IP Address ::: " + ipAddress)

        return ipAddress
    }

    ipAddress = request.getHeader("Client-IP")

    if(ipAddress && InetAddressValidator.VALIDATOR.isValid(ipAddress)) {
        log.debug("Remote IP Address ::: " + ipAddress)

        return ipAddress
    }
    return ipAddress

}

}

任何帮助将不胜感激!

【问题讨论】:

  • 不应该是request.getRemoteAddr()吗?
  • @MarcB 嗯,现在我收到以下错误:无法在空对象上调用方法 getRemoteAddr() 这很简单。我对 Grails 和我目前正在做的任务非常陌生。

标签: grails ip


【解决方案1】:

您可以通过内置的request 对象从任何 Grails 控制器访问当前的HttpServletRequest。正如您所做的那样,无需将其指定为您的方法的参数。如果你改变:

def getIpAddress(javax.servlet.http.HttpServletRequest request) {
...

到:

def getIpAddress() {
...

然后您就可以使用request.getRemoteAddr()(或者简单地使用带有Groovy 便捷访问器语法的request.remoteAddr)。

【讨论】:

    猜你喜欢
    • 2012-09-30
    • 2015-09-01
    • 2012-10-14
    • 2016-02-07
    • 1970-01-01
    • 2016-10-07
    • 2015-06-06
    • 2020-11-10
    • 2020-12-08
    相关资源
    最近更新 更多