用户定义对象的Spring表单验证

时间:2018-06-16 07:36:18

标签: java spring forms spring-mvc bean-validation

    i have a Employee class with the following content:

    public class Employee {

        @NotNull(message="Field Cannot be Empty")
        private String epfno;

        @NotNull(message="Field Cannot be Empty")
        private String empno;

        @NotNull(message="Field Cannot be Empty")
        private String empfullname;

        @NotNull(message="Field Cannot be Empty")
        private Address address;

       ****GETTERS AND SETTERS****

    }

    Address class class with the following content:

    public class Address {

        private int addressid;
        private Employee employee;

        @NotNull(message="Field Cannot be Empty")
        private String description;

       ****Getters and SETTERS****
    }

控制器类,包含以下内容:   当我尝试验证地址字段时,表单实际返回null。而不是抛出一个非null错误消息。我在控制器中进行了调试以捕获它         @RequestMapping(value =" / Form / Employee / Submit",method = RequestMethod.POST)         public String SubmitEmployeeForm(@Valid @ModelAttribute(" Employee")Employee Employee,BindingResult br){

        if(br.hasErrors())
        {
            logger.info("Form Validation Errors have Occured");
            return "Homepage";
        }

        else {

            // Does not through error instead sends null when field is empty 

            System.out.println(Employee.getAddress().getDescription()); // Null
            return "Homepage";
        }


    }

How can i get the address field to get populated with a not null error message instead of it passing the value null ? thanks 

1 个答案:

答案 0 :(得分:0)

    I figured it out. after adding the @valid annotation on the address object it worked 
    fine.

        public class Employee {

        @NotNull(message="Field Cannot be Empty")
        @valid
        private Address address;

       ****GETTERS AND SETTERS****

    }