为什么 spring 验证注释不起作用?

时间:2021-03-22 15:30:37

标签: java spring hibernate spring-mvc spring-validator

嗨,我坚持了几个星期,我搜索了很多,但没有找到答案,所以如果可以,请帮助我:

这是我的客户类:

public class Customer {
private String firstName;
@Valid

@NotNull(message="")

private String lastName;


@Min(value=0 , message="bigger than zero")
@Max(value=10 , message="less than ten")
private int freePasses;

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;
}

public int getFreePasses() {
    return freePasses;
}

public void setFreePasses(int freePasses) {
    this.freePasses = freePasses;
}   

这是我的控制器:

public class CustomerController {

@RequestMapping("/showForm")
public String showForm(Model model) {
     Customer thecustomer=new Customer();
     model.addAttribute("customer",thecustomer);
     //first one is name and the second one is value 
     return "customer-form";
}

@RequestMapping("/processForm")
 public String processForm(@Valid @ModelAttribute("customer")  Customer thecustomer,BindingResult theresult,Errors error)
{
    System.out.println(thecustomer.getLastName());
    if(theresult.hasErrors()) {
        System.out.println("!!!");
        return "customer-form";}
    else {
        return "customer-confirmation";}
    
    
    
}

这个条件 if(theresult.hasErrors()) 在 max,min 和 notnull 无效条件下总是返回 true :( 为什么是这样???

这是我的 html 前面,以防您想检查:

    <%@taglib prefix="form" uri="http://www.springframework.org/tags/form"  %>
<!DOCTYPE html>
<html>
<head>
<title>customer registration</title>


<style > 

.error{color:red}

</style>

</head>

<body>

<form:form action="processForm" modelAttribute="customer">
<p>firstname:</p> <form:input path="firstName"/>
<br>
<p>lastname:</p> <form:input path="lastName"  />

<form:errors path="lastName" cssClass="error"/>
<br>

 <form:input path="freePasses"  />

<form:errors path="freePasses" cssClass="error"/>





<input type="submit" value="Submit">

</form:form>

</body>

</html>

0 个答案:

没有答案
相关问题