hibernate validtor不工作,bindingresult.haserrors在spring boot中始终返回false

q5iwbnjs  于 2021-08-20  发布在  Java
关注(0)|答案(0)|浏览(279)

我试图简化验证,但问题是没有应用约束。这是我的模型级客户。

package mvc;

import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;

public class Customer {

    private String firstName;

    @NotNull(message="is required")
    @Size(min=1, message="is required")
    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;
    }

}

这是我的控制器。问题是bindingResult.haserrors()总是返回false

package 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) {

        System.out.println("Last name: |" + theCustomer.getLastName() + "|");

        if (theBindingResult.hasErrors()) {
            return "customer-form";
        }
        else {
            return "customer-confirmation";
        }
    }
}

这是我的customer-form.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>
<head>
    <title>Customer Registiration form</title>
    <style type="text/css">
        .error{color: red}
    </style>
</head>

<body>
    <form:form action="processForm" modelAttribute="customer">
        FirstName: <form:input path="firstName"/>
        <br><br>
        LastName (*): <form:input path="lastName"/>
        <form:errors path="lastName" cssClass="error"/>

        <input type="submit" value="Submit" />
    </form:form>
</body>
</html>

这是我的customer-confirmation.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
    <title>Customer confirmation</title>
</head>
<body>
    The customer is confirmed: ${customer.firstName} ${customer.lastName}
</body>
</html>

注意:我添加了HibernateValidator7JAR。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题