我正在开发一个小型 Spring MVC 项目。
package...
imports...
@Controller
@RequestMapping("/auth")
public class AuthenticationController {
private final UserService userService;
public AuthenticationController(UserService userService) {
this.userService = userService;
}
@GetMapping("/login")
public String showLoginPage() {
System.out.println("Login form");
return "authentication/login-page";
}
@GetMapping("/register")
public String showRegisterPage(Model model) {
UserModel userModel = new UserModel();
model.addAttribute("userModel", userModel);
System.out.println("Register form");
return "authentication/register-page";
}
@PostMapping("/register")
public String processRegistration(@Valid @ModelAttribute("userModel") UserModel userModel,
BindingResult bindingResult, RedirectAttributes redirectAttributes) {
// if (userService.findByEmail(userModel.getEmail()) != null) {
// bindingResult.rejectValue("email",null,
// "Account with this email already exists.");
// return "authentication/register-page";
// }
//
// if (userService.findByUsername(userModel.getUsername()) != null) {
// bindingResult.rejectValue("username",null,
// "Account with this username already exists.");
// return "authentication/register-page";
// }
if (!userModel.getPassword().equals(userModel.getConfirmPassword())) {
bindingResult.rejectValue("confirmPassword",null,
"Password and confirm password do not match.");
return "authentication/register-page";
}
if (bindingResult.hasErrors()) {
System.err.println("Error registering");
return "authentication/register-page";
}
System.out.println("Successfully registered");
redirectAttributes.addFlashAttribute("registrationComplete", "registrationComplete");
return "redirect:/auth/login";
}
}
这是处理请求的控制器,我正在谈论 @PostMapping 部分 - 问题是当我取消注释检查用户是否存在的代码时,它不会运行 sout() 和 addFlashAttribute() 方法,但是为什么?
System.out.println("Successfully registered");
redirectAttributes.addFlashAttribute("registrationComplete", "200");
第一个 if 语句之后的每一行代码都没有执行,即使尝试调试它,它也没有捕获断点,也尝试了 sout-ing 到控制台,也不起作用。 :( 控制台也没有错误。 这个问题有点奇怪,我尝试google了一下,但没有找到任何东西,希望大家能帮助我! 预先感谢您!
发现问题了,如果在 Service 类中找不到用户,我就会抛出异常,但有趣的是为什么控制台中没有任何关于它的信息。所以现在我要弄清楚如何检查用户是否存在..