首页 文章

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

提问于
浏览
-2
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
    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****
    
        }
    

相关问题