Just started to learn Spring came to form validation (There are dao / service and the whole standard set)
I am trying to perform a standard task on validation that I could enter only 3 characters @Size(min = 1, max = 3) in the field @Size(min = 1, max = 3)
then the form content is transferred to the database and displayed on the main BUT the next happens ... when sending a form of 1-2-3 characters that satisfies the condition of validation, the form is sent everything is written to the database and displayed on the main one But in a situation when the conditions are not met and I I bet 4 or more characters, I don’t see validation errors, but it doesn’t write to the database, respectively, it does not write to the main record and after sending the form immediately drops via HTTP Status 400 - Who will ignore the ignorant would be grateful.
@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>