首页 > 解决方案 > 如何在 Spring Webflux get 方法中传递 Java 地图参数?

问题描述

我尝试使用 Spring Webflux 制作简单的登录代码。下面的代码首先是 Webflux 处理程序和路由器代码。

处理程序类

public class UserHandler {
 
    @Autowired
    private UserReactiveMongoRepository userRepository;

    public Mono<ServerResponse> authenticate(ServerRequest request) {
        return request.bodyToMono(Map.class).flatMap(mapUser -> {
            String username = (String)mapUser.get("username");
            String password = (String)mapUser.get("password");
            
            Predicate<User> loginFilter = u -> u.getUsername().equals(username) && u.getPassword().equals(password);
            return ServerResponse.ok().body(userRepository.findAll().any(loginFilter), Boolean.class);
        });
    }

路由器类

@Configuration
@EnableWebFlux
public class BlogWebFluxEndpointRouter {
 
    @Bean 
    public RouterFunction<ServerResponse> routesUser(UserHandler handler) {
        return RouterFunctions.route(RequestPredicates.GET("/route/user/login"), handler::authenticate);
    }
}

服务器端处理程序和路由器类已成功部署。但问题是使用 webclient 类的客户端代码。我的目标是在 UserHandler 类的 authenticate 方法中传递 Java Map 类参数。

WebClient client = WebClient.builder().baseUrl("http://localhost:8080")
            .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).build();

Map<String, String> mapUser = new HashMap<String, String>();
mapUser.put("username", "joseph");
mapUser.put("password", "password");
            
client.get().uri("/route/user/login", mapUser).exchangeToMono(u -> u.bodyToMono(Map.class))
            .subscribe(obj -> System.out.println("Login Success : " + obj));

但是网络客户端代码没有响应。如何将 Java map 参数传递给 webflux 的 webclient get 方法。

更新

我更改如下代码,

路由器类

@Configuration
@EnableWebFlux
public class BlogWebFluxEndpointRouter {
     
    @Bean 
    public RouterFunction<ServerResponse> routesUser(UserHandler handler) {
        return RouterFunctions.route(RequestPredicates.POST("/route/user/login"), handler::authenticate);
    }
}

以下代码是webclient部分,

Map<String, String> mapUser = new HashMap<String, String>();
mapUser.put("username", "joseph");
mapUser.put("password", "password");
            
client.post().uri("/route/user/login").body(Mono.just(mapUser), Map.class).retrieve()
        .bodyToMono(Map.class)
        .subscribe(str -> System.out.println("Login Success : " + str));

但是代码会引发以下异常,

reactor.core.Exceptions$ErrorCallbackNotImplemented: org.springframework.core.codec.DecodingException: JSON decoding error: Cannot deserialize instance of `java.util.LinkedHashMap<java.lang.Object,java.lang.Object>` out of VALUE_TRUE token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.LinkedHashMap<java.lang.Object,java.lang.Object>` out of VALUE_TRUE token
 at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 1]
Caused by: org.springframework.core.codec.DecodingException: JSON decoding error: Cannot deserialize instance of `java.util.LinkedHashMap<java.lang.Object,java.lang.Object>` out of VALUE_TRUE token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.LinkedHashMap<java.lang.Object,java.lang.Object>` out of VALUE_TRUE token
 at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 1]
    at org.springframework.http.codec.json.AbstractJackson2Decoder.processException(AbstractJackson2Decoder.java:242) ~[spring-web-5.3.6.jar:5.3.6]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
    |_ checkpoint ⇢ Body from POST http://localhost:8080/route/user/login [DefaultClientResponse]
Stack trace:
        at org.springframework.http.codec.json.AbstractJackson2Decoder.processException(AbstractJackson2Decoder.java:242) ~[spring-web-5.3.6.jar:5.3.6]
        
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.LinkedHashMap<java.lang.Object,java.lang.Object>` out of VALUE_TRUE token
 at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 1]

标签: javaspring-webflux

解决方案


推荐阅读