I have just started learning Spring and stuck with form validation (There is dao/service and all the default set)
I try to make a validation task to prevent inserting into the field more than 3 symbols
@Size (min = 1, max = 3)
After that I want to insert the form data to DB and output it on my homepage, when the data satisfies my validation and consists of 1 to 3 symbols, then everything is ok, but when these conditions are not met and I try to insert 4 or more symbols, I receive HTTP STATUS 400
. No DB inserts and no view outputs. So I understand that there is validation, however I don't understand why does it show me HTTP STATUS 400
@Controller
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping(value = "addBook", method = RequestMethod.GET)
public String addUser(Model model) {
model.addAttribute("user", new ValidationField());
model.addAttribute("book", new Book());
return "addBook";
}
@RequestMapping(value = "addBook", method = RequestMethod.POST)
public String addBook( @ModelAttribute("user") @Valid ValidationField validationField, Book book, BindingResult result) {
/*this.user(book, result);*/
if (result.hasErrors()) {
return "addBook";
}
this.bookService.addBook(book);
return "redirect:/";
}
}
Validation Class
public class ValidationField {
@Size(min = 1, max = 3)
private String name;
@Size(min = 1, max = 3)
private String genre;
}
and View addBook.jsp
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<t:tamplate>
<form:form method="post" action="addBook" commandName="book" modelAttribute="user">
<form:errors path="*" cssClass="alert alert-danger" element="div" />
<table>
<tr>
<td><form:input path="name"/></td>
<td><form:errors path="name"/></td>
</tr>
<tr>
<td><form:input path="genre" /></td>
<td><form:errors path="genre"/></td>
</tr>
<tr>
<td colspan="2"> <input type="submit" value="add book"> </td>
</tr>
</table>
</form:form>
</t:tamplate>