我有以下代碼
目的
package com.example.demo;
import javax.validation.constraints.*;
public class Customer {
@NotEmpty(message="first name should contain a value")
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
控制器
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.validation.BindingResult;
import javax.validation.Valid;
@Controller
@RequestMapping("/customer")
public class CustomerController {
private static int counter = 0;
@RequestMapping("/showForm")
public String showForm(Model model) {
model.addAttribute("customer", new Customer());
return "customer-form";
}
@RequestMapping("/processForm")
public String processForm(@Valid @ModelAttribute("customer") Customer customer, BindingResult bindingResult) {
return "customer-form";
}
}
jsp檔案中的表格
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head></head>
<body>
<form:form method="POST" action="processForm" modelAttribute="customer">
<form:label path="firstName">Name</form:label>
<form:input path="firstName" />
<form:errors path="firstName"/>
<button type="submit">Submit</button>
</form:form>
</body>
</html>
我已經進行了一些除錯,當我單擊提交按鈕時,該方法processForm被正確呼叫,但 bindingResult 沒有錯誤。firstName 變數為空。為什么驗證不起作用?
uj5u.com熱心網友回復:
確保您已在 pom.xml 中宣告了 Hibernate Validator 依賴項(如果您使用 maven)
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.4.Final</version>
</dependency>
驗證約束可以在其他庫的類路徑中,但驗證處理器依賴于上面
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/482255.html
