Java Bean Validation在实际项目中如何工作?以Maven MVC登录场景为例
Let me walk you through exactly how Java Bean Validation (JSR-380) operates in your project setup—from the JSP/JSF form submission all the way to your JDBC DAO. We'll use your Student bean as the core example.
1. First: Set Up Maven Dependencies
Bean Validation needs two key pieces: the API (which defines annotations like @NotNull) and a concrete implementation (most folks use Hibernate Validator, the reference implementation). Add these to your pom.xml:
<dependencies> <!-- Bean Validation API --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> <!-- Hibernate Validator (concrete implementation) --> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.1.7.Final</version> </dependency> <!-- Optional: For EL expressions in validation messages (used in JSP/JSF) --> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.el</artifactId> <version>3.0.1-b11</version> </dependency> </dependencies>
2. Polish Your Student Bean
Your existing bean is a solid start, but let's refine it to make validation work properly. Remember: the validator needs getters/setters to access properties, and we can add more meaningful constraints (like age bounds):
import javax.validation.constraints.Email; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; public class Student { @NotNull(message = "Username cannot be null") private String uName; @NotNull(message = "Last name cannot be null") private String lname; @Email(message = "Please enter a valid email address") // @Email has a default valid pattern—only add a custom regex if you need strict, specific rules private String email; @Min(value = 16, message = "Age must be at least 16") private int age; // Getters and Setters (REQUIRED for Bean Validation to access properties!) public String getuName() { return uName; } public void setuName(String uName) { this.uName = uName; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
3. Controller Layer Validation (Spring MVC Example)
If you're using Spring MVC (a common choice for Maven MVC projects), your controller will handle form submission, trigger validation, and manage errors. Use the @Valid annotation to tell Spring to validate the Student object, and BindingResult to capture validation failures:
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import javax.validation.Valid; @Controller public class StudentController { // Inject your DAO (use @Autowired if using Spring's dependency injection) private StudentDAO studentDAO; public StudentController(StudentDAO studentDAO) { this.studentDAO = studentDAO; } @GetMapping("/student-form") public String showForm(Model model) { model.addAttribute("student", new Student()); return "student-form"; // Your JSP page name } @PostMapping("/submit-student") public String submitForm(@Valid Student student, BindingResult bindingResult, Model model) { // Check if validation failed if (bindingResult.hasErrors()) { // Send the student object back to the form, along with error messages model.addAttribute("student", student); return "student-form"; // Return to form to display errors } // If validation passes, pass the student to your DAO for persistence studentDAO.saveStudent(student); model.addAttribute("successMessage", "Student saved successfully!"); return "success-page"; // Redirect to success page } }
JSF Alternative
If you're using JSF instead of Spring MVC, validation happens automatically when the form is submitted (thanks to JSF's built-in integration with Bean Validation). Just bind your form inputs to the Student bean properties, and use JSF tags to display errors:
<!-- In your JSF page --> <h:form> <h:outputLabel for="uName">Username:</h:outputLabel> <h:inputText id="uName" value="#{studentBean.student.uName}" /> <h:message for="uName" style="color:red" /> <h:outputLabel for="lname">Last Name:</h:outputLabel> <h:inputText id="lname" value="#{studentBean.student.lname}" /> <h:message for="lname" style="color:red" /> <h:outputLabel for="email">Email:</h:outputLabel> <h:inputText id="email" value="#{studentBean.student.email}" /> <h:message for="email" style="color:red" /> <h:outputLabel for="age">Age:</h:outputLabel> <h:inputText id="age" value="#{studentBean.student.age}" /> <h:message for="age" style="color:red" /> <h:commandButton value="Submit" action="#{studentBean.saveStudent}" /> <h:messages globalOnly="true" style="color:green" /> </h:form>
Your JSF managed bean would look like this:
import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.validation.Valid; @ManagedBean @ViewScoped public class StudentBean { @Valid private Student student = new Student(); // Inject your DAO private StudentDAO studentDAO; public String saveStudent() { // JSF already validated the student object before this method runs studentDAO.saveStudent(student); return "success?faces-redirect=true"; } // Getters and Setters for student public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } }
4. Display Validation Errors in JSP (Spring MVC)
In your JSP form page, use Spring's form tags or JSTL to show error messages from BindingResult:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <body> <h2>Student Registration</h2> <form:form modelAttribute="student" action="/submit-student" method="post"> <div> <label>Username:</label> <form:input path="uName" /> <form:errors path="uName" cssClass="error" /> </div> <div> <label>Last Name:</label> <form:input path="lname" /> <form:errors path="lname" cssClass="error" /> </div> <div> <label>Email:</label> <form:input path="email" /> <form:errors path="email" cssClass="error" /> </div> <div> <label>Age:</label> <form:input path="age" /> <form:errors path="age" cssClass="error" /> </div> <button type="submit">Submit</button> </form:form> <c:if test="${not empty successMessage}"> <p style="color:green">${successMessage}</p> </c:if> </body> </html>
5. DAO Layer: Optional (But Recommended) Secondary Validation
Even if you validate at the controller/JSF layer, adding a final validation check in your DAO is a smart guardrail. It prevents invalid data from being saved if someone bypasses the frontend (e.g., via direct API calls or modified requests):
import javax.validation.Validator; import javax.validation.Validation; import javax.validation.ValidatorFactory; import java.util.Set; public class StudentDAO { private Validator validator; public StudentDAO() { // Initialize the validator ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } public void saveStudent(Student student) { // Validate before saving to the database Set<javax.validation.ConstraintViolation<Student>> violations = validator.validate(student); if (!violations.isEmpty()) { // Throw an exception or handle errors based on your project's needs throw new IllegalArgumentException("Invalid student data: " + violations); } // Proceed with your JDBC connection and save logic // Example: // try (Connection conn = DriverManager.getConnection(url, user, pass)) { // String sql = "INSERT INTO students (username, lastname, email, age) VALUES (?, ?, ?, ?)"; // try (PreparedStatement stmt = conn.prepareStatement(sql)) { // stmt.setString(1, student.getuName()); // stmt.setString(2, student.getLname()); // stmt.setString(3, student.getEmail()); // stmt.setInt(4, student.getAge()); // stmt.executeUpdate(); // } // } catch (SQLException e) { // e.printStackTrace(); // } } }
6. Full Flow Recap
- User fills out the JSP/JSF form and submits it.
- The controller/JSF managed bean receives the
Studentobject populated with form data. - The
@Validannotation triggers Bean Validation, which checks all constraints on theStudentproperties. - If validation fails:
- Spring MVC:
BindingResultcaptures errors, and the user is sent back to the form with error messages displayed. - JSF: Errors are automatically attached to form fields, and the page refreshes to show issues.
- Spring MVC:
- If validation passes:
- The
Studentobject is passed to the DAO. - (Optional) DAO runs a final validation check.
- DAO uses JDBC to save the valid
Studentdata to the database. - User is redirected to a success page.
- The
内容的提问来源于stack exchange,提问作者kristof

