spring mvc nested model validation

前端 未结 4 1819
梦毁少年i
梦毁少年i 2020-12-18 10:01

I have two models : User,Project

public class Project{
    private int id;
    @NotEmpty(message=\"Project Name can not be empty\")
    private          


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-18 10:50

    Here's one possible solution.

    Create the class below :

    ...
    import org.springframework.validation.Validator;
    ...
    
    @Component
    public class ProjectValidator implements Validator {
    
        @Override
        public boolean supports(Class clazz) {
            return Project.class.equals(clazz);
        }
    
        @Override
        public void validate(Object target, Errors errors) {
            Project project = (Project) target;
    
            /* Do your checks here */
            ...
    
            if (managerIdDoesNotMatch) {
                errors.rejectValue("manager.id", "your_error_code");
            }
    
            ...
    
            if (operatorIdDoesNotMatch) {
                errors.rejectValue("operator.id", "your_error_code");
            }
    
            ...
        }
    }
    

    And in your controller do something like :

    ...
    public class ProjectController {
    
        @Autowired
        ProjectValidator projectValidator;
    
        ...
    
        @RequestMapping(...)
        public String yourCreateMethod(..., @ModelAttribute @Valid Project project, BindingResult result) {
            projectValidator.validate(project, result);           
    
            if (result.hasErrors()){
              // do something
            }
            else {
              // do something else
            }
        }
    
    }
    

    This should get you started. You could instantiate/set the validator differently, have a a user sub-validator, but you get the general idea.

    References :

    • Latest Spring validation documentation
    • This Stack Overflow post about how to perform validation

提交回复
热议问题