在Spring Webflux中处理条件响应的正确方法是什么

酷酷:

我刚刚开始学习spring网络流量。对于如何在反应式编程而不是命令式编程中完成工作有完全的改变或观点。

因此,我想实现一个非常简单的输出。

我有响应类,其中包含字段成功,消息和列表数据。

@Data
@Accessors(chain = true)
public class Response {

    private boolean success;
    private String message;
    private List data;
}

和一个请求类

@Data
@Accessors(chain = true)
public class LoginRequest {

    private String email;
    private String password;
}

我也有带webFlux的userRepository。

Mono<User> findUserByEmail(String email);

我有这样的登录操作。

@PostMapping("/login")
public Mono<Response> login(@RequestBody Mono<LoginRequest> request) {
}

现在,我必须根据userRepository给我的信息返回响应。

  • 如果没有用户,则可能返回null
  • 如果找到用户,它可以给我User类对象
  • 现在我必须检查密码是否与LoginRequest中给出的密码匹配

所以我必须根据用户存储库更改响应,例如如果找不到用户

  • 如果找到的用户密码无效,我必须返回成功= false和消息=“找不到用户”的响应
  • 我必须返回成功= false和消息=“无效密码”的响应,如果一切正常,则
  • 我必须返回成功= true,消息=“欢迎”,并使用用户名,电子邮件等列出。

我尝试了很多方法,但最终我未能实现这一目标。

亚当·比克福德(Adam Bickford):

您不需要将Mono作为控制器的参数,可以从Spring进行标准数据绑定后接受该值。查看Spring文档中的示例:https : //docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-controller

您也不应从您的存储库中获取null,如果找不到该用户,您会得到一个空的Mono(因此.map.filter不会调用,等等)。在这种情况下,您可以.switchIfEmpty代替null检查。

如果您获得数据,则可以将其简单地设置.map为所需的内容,因为您无需阻塞任何其他数据:

public Mono<Response> login(LoginRequest request) {
        return repo.findUserByEmail(request.getEmail())
            .map(user ->
                Objects.equals(request.getPassword(), user.getPassword())
                    ? new Response(true, "Welcome", Collections.emptyList())//populate list here
                    : new Response(false, "invalid password", Collections.emptyList()))
            //user wasn't found in the repo
            .switchIfEmpty(Mono.just(new Response(false, "No user found", Collections.emptyList())));
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

有什么方法可以在Spring Webflux中实现分页和Spring数据响应

在Spring Boot中添加属性值的正确方法是什么

在 Spring 中返回 List 的正确方法是什么

在Spring Boot中处理异常的最佳方法是什么?

在Spring Webflux中捕获响应

Spring webflux 中的异常处理

那么Spring Webflux中的Empty,Many和flatMapMany是什么?

用Spring和DBCP处理JDBC连接的正确方法是什么?

在Spring Boot中处理异常的正确方法

在Spring MVC 3中指定HTTP“位置”响应标头的首选方法是什么?

在Spring Data中查找按字段排序的所有实体的正确方法是什么?

在Spring Beans中初始化字段的正确方法是什么?

在Spring MVC +安全性中拒绝访问特定资源的正确方法是什么

在Spring Boot和JPA中更新n-m关系的正确方法是什么?

在Spring Web应用程序中创建数据源的正确方法是什么?

Spring控制器处理程序方法中未注释参数的目的是什么?

在 Spring AMQP 中处理 RabbitMQ DLQ 消息的最佳方法是什么

在Spring WebFlux中处理全球方案

会话关闭时使用Spring WebSocketConnectionManager的正确方法是什么

将ReactJS与Spring Boot集成的正确方法是什么?

Spring Boot 2.1.5,WebFlux,Reactor:如何正确处理MDC

Spring WebFlux-为什么我必须等待WebClient响应?

Spring中的JavaConfig是什么?

Spring Webflux非阻塞响应

调用Spring RestController时,使用Spring的RestTemplate转义URL变量的正确方法是什么?

确保 Spring Webflux 中的方法执行

使用Spring Security时,在bean中获取当前用户名(即SecurityContext)信息的正确方法是什么?

定义一个 bean 的正确方法是什么,该 bean 包含从 Spring 中的映射创建的对象列表

Spring Boot Webflux:避免在处理程序中调用线程阻塞方法