这是我customer.java
类使用 for 作为 bean
package com.zeeshan.form;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Customer {
private String firstName;
@NotNull(message="is required")
@Size(min=1)
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
CustomerController.java
package com.zeeshan.form;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/customer")
public class CustomerController {
@RequestMapping("/showForm")
public String showFormModel(Model theModel) {
theModel.addAttribute("customer", new Customer());
return "customer-form";
}
@RequestMapping("/processForm")
public String processForm(@ModelAttribute("customer") @Valid Customer theCustomer, BindingResult theBindingresult) {
if(theBindingresult.hasErrors()) {
return "customer-form";
}
else {
return "customer-confirmation";
}
}
}
customer-form.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.error{
color: red;
}
</style>
</head>
<body>
<h2>Customer Registeration Form</h2>
<form:form action="processForm" modelAttribute="customer">
First Name : <form:input path="firstName"/>
<br><br>
Last Name (*) : <form:input path="lastName"/>
<form:errors path="lastName" cssClass="error" />
<br><br>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
休眠验证器不起作用。 我的代码运行正常,但没有显示任何错误 我正在附加文件结构
正在使用以下库
hibernate version 6.0.2
spring version 5.0.6
代码看起来不错。阅读您的问题,似乎您可能会在这两者之间感到有些困惑:
Hibernate ORM
: 实施JPA
Hibernate Validator
: 实施Bean Validation
因此,要使Bean Validation
正常工作,您需要在类路径中添加Hibernate Validator
。意味着只需将其添加到build.gradle
/pom.xml
的依赖项中,即构建工具的构建脚本。