How to Validate different model class into one form using Spring MVC JSR-303 Validator

Deadly 提交于 2019-12-04 13:11:25

To make this work you should annotate employeeDetails with @Valid in your Employee.class like this:

@Valid
private EmployeeDetail employeeDetail;

And now in controller you should use just Employee object like this:

public String saveEmployee(@Valid Employee employee, BindingResult bindingResult) {

You should change the names of the attributes belong to EmployeeDetail from e.g. name="street" to name="employeeDetail.street"

Also, you should add a BindingResult object right behind the Employee argument as well, so that the framework can store the binding error related to Employee, the current BindingResult will apply only to EmployeeDetail instance, so

saveEmployee(@Valid Employee employee, BindingResult bindingResultEmployee,
        @Valid EmployeeDetail employeeDetail, BindingResult bindingResult) 

without it you're getting a bad request, with it, the request will actually reach the method, and the logs will show the exact binding error if set to debug level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!