I ran into the same problem, but in my case you can duplicate one or more fields (username or email address). Therefore, org.hibernate.exception.ConstraintViolationException is not specific enough to say whether a username or letter was caused by this exception and which message was displayed last.
I just looked at danny.lesnik’s answer , but it’s not great, as it just redirects to the “highlighted” page. Assuming you were simply redirecting the user of the page, he would avoid creating a new page that you would say. However, I suppose you already have a Spring validator doing some form validation work. Therefore, in my case, I decided to simply perform duplicate field checks (username and email address) in one place (in the validator). It seems like a more appropriate, consistent (located with the rest of the check) and cleaner solution.
Here is some code to illustrate:
My controller
@Controller public class WebController { @Autowired private UserServiceImpl userService; @Autowired private CustomUserDetailsValidator customUserDetailsValidator; ... @RequestMapping(value = "/login/create-account", method = RequestMethod.POST) public String createAccount(@ModelAttribute("user") CustomUserDetails user, BindingResult result, Model model, SessionStatus status) { customUserDetailsValidator.validate(user, result); if(result.hasErrors()){ model.addAttribute("user", user); // Print the errors to the console - FIXME: log error instead System.out.println("Validation errors:"); for (FieldError error : result.getFieldErrors()) { System.out.println(error.getField() + " - " + error.getDefaultMessage()); } return "login/create-account"; } else{ userService.registerUser(user); return "redirect:/login/create-account-success"; } } ... }
My validator
public class CustomUserDetailsValidator implements Validator { @Autowired private UserServiceImpl userService; ... @Override public void validate(Object target, Errors errors) {
I'm not sure if this is the best way to do this, but I thought that my solution would increase the extension (you can add various checks for any other restriction).
Hope this helps others, and it would also be interesting to know more about this developer.
source share