How to use Bean Validation in Spring MVC

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
public class ValidationModel {    @NotEmpty
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Controller
@RequestMapping("/model/validation")
public class ModelValidationController {

private static final Logger LOGGER
= LoggerFactory
.getLogger(ModelValidationController.class);

private static String PAGE = "validate";

@GetMapping
public String initValidation(Model model) {
ValidationModel validationModel = new ValidationModel();
model.addAttribute("validationModel", validationModel);

return PAGE;
}

@PostMapping
public String validate(
@ModelAttribute("validationModel")
@Valid ValidationModel validationModel,
Errors errors) {

LOGGER.info("Errors = {}", errors.hasErrors());

return PAGE;
}

}
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
<%@ taglib prefix="form" 
uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Validation</title>
</head>
<body>
<h1>Validation</h1>
<form:form
action="/model/validation"
method="post"
modelAttribute="validationModel">
<div>
<div>
<form:input
path="name"
id="name"
cssErrorClass="error"/>
<form:errors path="name"
cssClass="errors"/>
</div>
<div>
<button type="submit"
name="submit">
OK
</button>
</div>
</div>
</form:form>
</body>
<style>
body {
margin-left: 5%;
}
form div div span {
margin: 0px 0px 0px 5px
}
form div div {
margin: 0px 0px 5px 0px;
}
.errors {
color: red;
}
.error {
border-width: 1px;
border-color: red;
}
</style>
</html>
public @interface NotEmpty {

...message()
..."{javax.validation.constraints.NotEmpty.message}";
@NotEmpty(message = "Name is required")
private String name;
@NotEmpty(message = "{validation.model.name.required}")
private String name;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store