我是Spring Webflux / Reactor Core的新手,我正在尝试执行以下功能:
调用userservice.LoginWebApp()
如果返回用户,请返回类型" User"的ResponseEntity。如果为空,则返回类型"字符串"
以下代码给出了类型错误,因为.defaultIfEmpty()需要类型为user的ResponseEntity。您能否告知正确的操作员/方法以实现此功能。
@PostMapping("api/user/login/webApp")
public Mono<ResponseEntity> login(@RequestBody Credentials credentials, ServerWebExchange serverWebExchange) {
return userService.loginWebApp(credentials, serverWebExchange)
.map(user -> ResponseEntity.status(HttpStatus.OK).body(user))
.defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password"));
}
答案 0 :(得分:2)
您可以使用cast
运算符向下转发泛型,我相信WebFlux仍然可以整理User
和String
:
@PostMapping("api/user/login/webApp")
public Mono<ResponseEntity> login(@RequestBody Credentials credentials, ServerWebExchange serverWebExchange) {
return userService.loginWebApp(credentials, serverWebExchange)
.map(user -> ResponseEntity.status(HttpStatus.OK).body(user))
.cast(ResponseEntity.class)
.defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password"));
}
答案 1 :(得分:1)
我会做以下事情:
为回复制作基类
abstract class Response {
}
为每种响应创建单独的类(如UserResponse,ErrorResponse,NotFoundResponse等),并从基类Response
类扩展它们
class UserResponse extends Response {
private String login;
private String password;
public UserResponse(String login, String password) {
this.login = login;
this.password = password;
}
@JsonGetter("login")
public String getLogin() {
return login;
}
@JsonSetter("login")
public void setLogin(String login) {
this.login = login;
}
@JsonGetter("password")
public String getPassword() {
return password;
}
@JsonSetter("password")
public void setPassword(String password) {
this.password = password;
}
}
class ErrorResponse extends Response {
private String errorMessage;
public ErrorResponse(String errorMessage) {
this.errorMessage = errorMessage;
}
@JsonGetter("error_message")
public String getErrorMessage() {
return errorMessage;
}
@JsonSetter("error_message")
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
明确设置返回值Mono<ResponseEntity<Response>>
的类型
就是这样。
@GetMapping("/test/{login}")
public Mono<ResponseEntity<Response>> test(@PathVariable(value = "login") String login) {
return loginWebApp(login)
.map(userResponse -> ResponseEntity.status(HttpStatus.OK).body(userResponse))
.defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new ErrorResponse("bad login")));
}
现在让我们尝试登录错误:
好登录:
可以找到完整代码here