【问题标题】:spring boot (webflux) rest controller get remote IP addressspring boot(webflux)rest控制器获取远程IP地址
【发布时间】:2019-02-09 14:49:59
【问题描述】:

使用 spring boot 进行简单的 REST 应用程序。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

我有一个简单的控制器来处理请求。

@RestController
@RequestMapping("/api")
public class MainController {

    @RequestMapping("/test")
    public BasicDTO getBasic(HttpServletRequest request){
        System.out.println(request.getRemoteAddr());
        return new BasicDTO();
    }

}

HttpServletRequest 上下文不会被注入。如何将请求上下文注入方法中,以便我可以访问一些基本的套接字详细信息?谢谢。

【问题讨论】:

  • 如何调用“api/test”端点?
  • 你在使用 javax.servlet.http.HttpServletRequest 吗?
  • 这个方法还有什么作用呢?您不会从此方法返回任何内容。
  • 不知道你们为什么说不能注射。我刚刚实现了一个类似的例子,我可以注入它。 prntscr.com/kqiksp
  • 抱歉,我一定是忽略了它。我已删除我的答案。

标签: java spring spring-boot spring-webflux


【解决方案1】:

查看您的pom.xml,它使用spring-boot-starter-webflux,因此您必须使用ServerHttpRequest 而不是HttpServletRequest

或者包括,

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

并删除 spring-boot-starter-webflux 依赖项。

【讨论】:

  • 宾果游戏。在我的方法中指定ServerHttpRequest request 会正确注入org.springframework.http.server.reactive.ServerHttpRequest
  • 如果需要更多详细信息,请通过request.getRemoteAddress().getAddress().getHostAddress()获取IP地址
猜你喜欢
  • 1970-01-01
  • 2022-08-04
  • 2020-08-19
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 2012-03-01
  • 2012-03-22
相关资源
最近更新 更多