![](/img/trans.png)
[英]How to end request and send proper response using Spring WebFlux WebFilter?
[英]What is the proper way to deal with conditional response in Spring webflux
我刚开始学习 spring web 助焊剂。 并且对于如何在反应式编程而不是命令式编程中完成工作有完全的改变或观点。
所以,我想实现一个非常简单的 output。
我有响应 class 字段成功,消息和列表数据。
@Data
@Accessors(chain = true)
public class Response {
private boolean success;
private String message;
private List data;
}
和一个请求 class
@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 给我的内容返回响应。
所以我必须根据用户存储库更改响应,比如找不到用户
我尝试了很多方法,但最后我未能实现这一目标。
您不需要 Mono 作为 controller 的参数,您可以从 Spring 接受标准数据绑定后的值。 查看 Spring 文档以获取示例: https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html
您也不应该从您的存储库中获取 null,如果找不到用户,您将得到一个空的.filter
(所以.map
,不会被称为等) 在这种情况下,您可以使用.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())));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.