Spring Boot Form

Form and Validation in server side

Form is typical first example of Web Application we learn.
Create Form in view side and receive parameters in server side and validate parameters
and if invalid data is coming, we want to return error message.

View

thymeleaf
src/main/resources/test.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
 	<title>just HTML</title>
 	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
	<h3>Hello! </h3>
	<form action="#" th:action="@{/form}" th:object="${person}" method="post">
			<table>
                <tr>
                    <td>Name:</td>
                    <td><input type="text" th:field="*{name}" /></td>
                    <td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td>
                </tr>
                <tr>
                    <td>Age:</td>
                    <td><input type="text" th:field="*{age}" /></td>
                    <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Name Error</td>
                </tr>
                <tr>
                    <td><button type="submit">Submit</button></td>
                </tr>
            </table>
	</form>
</body>
</html>

Result Page after validation
results.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
 	<title>Hello</title>
 	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
	<p th:text="'Hello, ' + ${person.name} + '!'"/>
</body>
</html>

Bean

@Data
public class Person {

	@Size(min=2, max=50)
	private String name;
	
	@NotNull
	@Min(18)
	private String age; 
	
	public String toString() {
        return "Person(Name: " + this.name + ", Age: " + this.age + ")";
    }
}

Bean Validation Java Documentation Oracle

Controller

@Controller
public class IndexController {
   @RequestMapping(value="/form", method=RequestMethod.GET)
    public String showForm(Person person) {
        return "test";
    }
	
	@RequestMapping(value="/form", method=RequestMethod.POST)
	public String checkPersonInfo(@Valid Person person, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "test";
        }
        return "results";
    }
}