Java 使用SpringWebFlux和WebTestClient获取请求属性
使用Spring WebFlux时,我无法将我正在从Java 使用SpringWebFlux和WebTestClient获取请求属性,java,spring-webflux,Java,Spring Webflux,使用Spring WebFlux时,我无法将我正在从WebTestClient设置的属性绑定到RestController 我尝试了我能想到的两种方法 首先使用@RequestAttribute注释,我得到: 无法处理请求[GET/attributes/annotation]:响应状态400,原因为“缺少字符串类型的请求属性” 然后我尝试使用ServerWebExchange,结果是null 这是我的控制器: @RestController @RequestMapping("/attribute
WebTestClient
设置的属性绑定到RestController
我尝试了我能想到的两种方法
首先使用@RequestAttribute
注释,我得到:
无法处理请求[GET/attributes/annotation]:响应状态400,原因为“缺少字符串类型的请求属性”
然后我尝试使用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"));
}
}
在我的实际应用程序中,我有一个SecurityContextRepository,它根据(解码的)头值设置一些属性,我希望获得这些属性。在服务器端和客户端,请求属性都应该被视为类似于映射的数据结构,可用于在客户端/服务器内传输信息(用于过滤器、编解码器等) 这些信息不是通过网络发送的
如果您想将该信息从客户端发送到服务器,您应该查看请求参数或请求正文本身。谢谢您的回答。我知道此属性是通过解码头(JWT)在服务器端设置的当我发送标题时,我可以使用
ServerWebExchange
成功地获取属性。但是,我想通过直接设置属性来简化测试,就像我在webflux之前使用MockMvc
所做的那样:mvc.perform(get(…).requestAttr(“foo”,“bar”)
,这过去工作正常。
@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();
}
}