Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring boot (webflux) rest controller get remote IP address

Using spring boot for simple REST application.

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

I have a simple controller that handles requests.

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

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

}

The HttpServletRequest context does not get injected. How can I inject the request context into the method so that I can access some basic socket details? Thanks.

like image 275
user2914191 Avatar asked Sep 04 '18 14:09

user2914191


People also ask

Can I use Springmvc and WebFlux together?

Use Spring MVC with WebFlux to build Java-based web applications. Employ the various Spring MVC architectures. Work with controllers and routing functions. Build microservices and web services using Spring MVC and REST.

How does Spring WebFlux work internally?

Spring WebFlux internally uses Project Reactor and its publisher implementations, Flux and Mono. The new framework supports two programming models: Annotation-based reactive components. Functional routing and handling.

What is reactive WebFlux?

It is a reactive fully non-blocking, annotation-based web framework built on Project Reactor that supports reactive streams back pressure and runs on non-blocking servers such as Netty, Undertow and Servlet 3.1+ containers.


1 Answers

Looking at your pom.xml it uses spring-boot-starter-webflux so you must use ServerHttpRequest instead of HttpServletRequest.

Or include,

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

and remove spring-boot-starter-webflux dependency.

like image 76
benjamin c Avatar answered Sep 19 '22 03:09

benjamin c