有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java spring boot(webflux)rest控制器获取远程IP地址

使用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上下文。如何将请求上下文注入方法中,以便访问一些基本的socket细节?谢谢


共 (1) 个答案

  1. # 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依赖项