I'm currently learning Spring MVC and data validation looks simple enough, my problem is the following: When I enter data that is not valid and press the submit button, the request mapping method does not fire at all, it sends me to "HTTP Status 400 – Bad Request". My goal is to look if there are any errors using "BindingResult" but the method body does not run if the entered data is invalid. (Using hibernate-validatior). Here is some code.
User object:
public class User {
@NotNull
@Size(min = 4, max = 25, message = "Must be between 4 and 25 characters")
private String firstName;
@NotNull
@Size(min = 4, max = 25, message = "Must be between 4 and 25 characters")
private String lastName;
@Email
private String email;
@Size(min = 8)
private String userPassword;
}
Controller: To open form page
@RequestMapping("createAccount")
public String register(Model model) {
model.addAttribute("newUser", new User());
return "register";
}
Here's the problem. This method should run when I press the submit button, and when the data is valid it does return the userinteface.jsp with all the entered data, but when the entered data is invalid it sends me straight to HTTP Status 400 - Bad Request.
@RequestMapping("signUp")
public String signUp(@Valid @ModelAttribute("newUser") User user,
Model model, BindingResult bindingResult) {
model.addAttribute("dbUser", user);
if (bindingResult.hasErrors()) return "register";
return "userinterface";
}
Here is my register.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Register</title>
<meta name="description" content="An interactive getting started guide for Brackets.">
<link rel="stylesheet" type="text/css" href="resources/css/main.css" />
<link href="https://fonts.googleapis.com/css2?family=Nova+Round&display=swap" rel="stylesheet">
</head>
<body>
<div class = "container">
<h1>- Register -</h1>
<ul>
<form:form action ="signUp" modelAttribute="newUser">
<form:input path="firstName" class = "cred" placeholder="First Name"/>
<form:errors path="firstName" cssClass="error"/><br><br>
<form:input path="lastName" class = "cred" placeholder="Last Name"/><br><br>
<form:errors path="lastName" cssClass="error"></form:errors><br><br>
<form:input path="email" class = "cred" placeholder="E-mail"/>
<form:errors path = "email" cssClass="error"/><br><br>
<form:password path="userPassword" class = "cred" placeholder="Password"></form:password><br><br>
<form:errors path="userPassword" cssClass="error"/>
<form:input path="age" type = "number" class = "cred" placeholder="Age"/><br><br>
- <input type ="submit" class = "submitButton" value = "Add User"> -<br><br>
<a href = index.jsp>cancel</a>
</form:form>
</ul>
</div>
</body>
</html>
