使用Spring Webflux和WebTestClient获取请求属性

时间:2018-07-24 16:08:12

标签: java spring-webflux

使用Spring WebFlux时,我无法将自己从WebTestClient设置的属性绑定到RestController

我尝试了两种可以想到的方式。

首先使用@RequestAttribute注解,我得到了:

  

无法处理请求[GET / attributes / annotation]:响应状态400,原因为“缺少类型为String的请求属性'attribute'”

然后,我尝试使用ServerWebExchange,结果是null

这是我的控制者:

@RestController
@RequestMapping("/attributes")
public class MyController {

    @GetMapping("/annotation")
    public Mono<String> getUsingAnnotation(@RequestAttribute("attribute") String attribute) {
        return Mono.just(attribute);
    }

    @GetMapping("/exchange")
    public Mono<String> getUsingExchange(ServerWebExchange exchange) {
        return Mono.just(exchange.getRequiredAttribute("attribute"));
    }
}

这是我失败的考试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyControllerTest {

    @Autowired
    ApplicationContext context;

    WebTestClient webClient;

    @Before
    public void setup() {
        webClient = WebTestClient.bindToApplicationContext(context)
                .configureClient()
                .build();
    }

    @Test
    public void testGetAttributeUsingAnnotation() {
        webClient.get()
                .uri("/attributes/annotation")
                .attribute("attribute", "value")
                .exchange()
                .expectStatus()
                .isOk();
    }

    @Test
    public void testGetAttributeUsingExchange() {
        webClient.get()
                .uri("/attributes/exchange")
                .attribute("attribute", "value")
                .exchange()
                .expectStatus()
                .isOk();
    }

}

在我的真实应用程序中,我有一个SecurityContextRepository,它可以从(已解码的)标头值中设置一些属性,而我想获取这些属性。

1 个答案:

答案 0 :(得分:0)

在服务器端和客户端,请求属性都应视为类似于Map的数据结构,可用于在客户端/服务器内传输信息(用于过滤器,编解码器等)。

该信息不会通过网络发送。

如果要将信息从客户端发送到服务器,则应查看请求参数或请求主体本身。