有人可以向我解释如何在Spring WebFlux和Thymeleaf中实现 post-redirect-get 模式吗? 什么订阅了数据库保存方法?
@GetMapping("/register")
public String showRegisterForm(Model model) {
model.addAttribute("user", new User());
return "register";
}
@PostMapping
public String processRegisterForm(@Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "register";
} else {
userRepository.save(user); //what subscribes on this?
//how to redirect on e.g. "/login"?
}
}
答案 0 :(得分:2)
您可以使控制器方法返回类似以下的反应型:
@PostMapping
public Mono<String> processRegisterForm(@Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return Mono.just("register");
} else {
return userRepository.save(user).thenReturn("redirect:/login");
}
}
答案 1 :(得分:1)
出于记录目的,我推荐Brian编写的解决方案更好地表达了意图。但是,如果您想打动您的朋友。这里有些没有if语句。
@PostMapping
public Mono<String> processRegisterForm(@Valid User user, BindingResult bindingResult) {
return Mono
.just(bindingResult.hasErrors())
.filter(t -> t)
.flatMap( t-> Mono.just("register"))
.switchIfEmpty(userRepository.save(user).thenReturn("redirect:/login"));
}