所以我做 Spring 和休眠课程,并得到了@NotNull和@size章.我实现了休眠jar文件1,2,34,5,6,7,我没有得到任何代码错误,但@NotNull和@Size不工作,有另一个关于这个问题的职位,我看到没有解决方案,所以我不得不作出新的职位.
我实现的Hibernate验证器是hibernate-validator-7.0.3。最终版和spring使用的是spring-framework-5.3.9
package com.luv2code.springdemo.mvc;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class Customer {
private String firstName;
@Size(min = 1, message ="is required")
@NotNull( message ="is required")
private String lastName;
public Customer() {
}
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;
}
}
/
<%@ taglib prefix= "form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title> Customer registration form</title>
<style>
.error{color:red}
</style>
</head>
<body>
<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>
/
package com.luv2code.springdemo.mvc;
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;
import jakarta.validation.Valid;
@Controller
@RequestMapping("/customer")
public class CustomerController {
@RequestMapping("/showForm")
public String showForm(Model theModel) {
theModel.addAttribute("customer", new Customer());
return "customer-form";
}
@RequestMapping("/processForm")
public String processForm(@Valid @ModelAttribute("customer") Customer theCustomer,
BindingResult theBindingResult) {
if(theBindingResult.hasErrors()) {
return "customer-form";
} else {
return "customer-confirmation";
}
}
}
3条答案
按热度按时间2q5ifsrm1#
我也遇到过同样的问题,在尝试了许多解决方案后,对我有效的是一个简单的修改,没有配置或修改其他任何东西。
我只需要将
@field
装饰器放在类的属性中进行验证。ui7jx7zq2#
尝试在此序列中使用@NotNull @NotBlank @Size
如果希望空格作为有效字符串,请使用@NotEmpty
8ljdwjyq3#
我也有类似的问题。
替换:
与
以及
与
帮了我