Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive Spring does not support HttpServletRequest as parameter in REST endpoint?

I created a RestController which look like this :

@RestController public class GreetingController {      @RequestMapping(value = "/greetings", method = RequestMethod.GET)     public Mono<Greeting> greeting(HttpServletRequest request) {          return Mono.just(new Greeting("Hello..." + request.toString()));     } } 

Unfortunately when I try to hit the "greetings" endpoint I get an exception :

java.lang.IllegalStateException: No resolver for argument [0] of type [org.apache.catalina.servlet4preview.http.HttpServletRequest]

I am using

compile('org.springframework.boot.experimental:spring-boot-starter-web-reactive') 

How to fix this ?

Link to full stack-trace. Link to build.gradle

----------EDIT----------

Using the interface. Now getting :

java.lang.IllegalStateException: No resolver for argument [0] of type [javax.servlet.http.HttpServletRequest] on method (rest is same)

like image 202
Dexter Avatar asked Nov 01 '16 13:11

Dexter


People also ask

How do I get HttpServletRequest in Webflux?

The code to get it is as follows. ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder. getRequestAttributes(); // get the request HttpServletRequest request = requestAttributes. getRequest();

How do I get HttpServletRequest in spring?

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder. getRequestAttributes()) . getRequest();

What is the use of HttpServletRequest in spring boot?

Spring Boot HttpServletRequest Logging Filter. A Request Logging Filter for Spring Boot applications, that allows you to read the request body multiple times. The request body is cached using an overridden HttpServletRequestWrapper. Then a reader that allows the client to read the body multiple times is returned.

How do I pass HttpServletRequest in Java?

Pass it to the constructor: public class XmlParser{ final private HttpServletRequest request; public XmlParser(HttpServletRequest request) { this. request = request; } // use it in othe methods... }


1 Answers

You should never use the Servlet API in a Spring Reactive Web application. This is not supported and this is making your app container-dependent, whereas Spring Web Reactive can work with non-Servlet runtimes such as Netty.

Instead you should use the HTTP API provided by Spring; here's your code sample with a few changes:

import org.springframework.http.server.reactive.ServletServerHttpRequest;  @RestController public class GreetingController {      @GetMapping("/greetings")     public Mono<Greeting> greeting(ServerHttpRequest request) {          return Mono.just(new Greeting("Hello..." + request.getURI().toString()));     } } 

You can inject either ServerWebExchange or directly ServerHttpRequest / ServerHttpResponse.

like image 163
Brian Clozel Avatar answered Sep 24 '22 23:09

Brian Clozel