2020년 5월 19일 화요일

[Spring] Validator Validates Command Object Values

Validation

 For people who use the web application to sign up, they must enter a value on the specified form. However, validation should inform the user of the incorrect value because that value can be incorrect. Then let's try applying the Validator to validate the command object below.

MemberVO.java
public class MemberVO {
 
    private String userId;
    private String userPassword;
    private String userEmail;
            ...
}


Validator, Errors 

 Vaildator is the interface that you use to validate the value of an object, and Errors is the class that sends the verification results.

Extends Validator 
public class A implements Validator {

    @Override 
    public boolean supports(Class<?> clazz) {
    
    }
    
    @Override
    public void validate(Object target, Errors errors) {
    
    }
 First, create one class that implements the Validator interface. And override support, validation methods. The support methods help ensure that the Validator is the type that can be verified. The first parameter in the validation method also indicates the object to be verified.

public class MemberVaildator implements Validator {
    
    @Override 
    public boolean supports(Class<?> clazz) {
     return MemberVO.class.isAssignableFrom(clazz);
    }
    
    @Override
    public void validate(Object target, Errors errors) {
     MemberVO memberVO = (MemberVO) target;
        
        if (memberVO.getUserId() == null || memberVO.getUserId().length()<10) {
         errors.rejectValue("userId", "required");
        }
    }
 The support methods are written in the form of a validation object.class.isAssignableFrom (clazz), and return the contents of the support method to ensure that the object is of the type that can be Then, if the condition is satisfied using an if statement in the validation method, the rejectValue method in Errors will cause an error in the userId field with the required property.



Running the MemberVaildator

MemberController.java
@Controller
public class MemberController {
 
    public String MemberInit(@ModelAttribute MemberVO memberVO, BindingResult bindingResult) {
     new MemeberValidator().validate(memberVO, bindingResult);
        
        if(bindingResult.hasErrors()){ //validator에 에러가 있으면,
            return "login";  //이 페이지로 이동.
        }
    }
 Receives BindingResult as a parameter to the controller method and passes the bindingResult and the object to be verified by the forward factor of the validator. Next, under the terms of the if statement, determine whether the validation fails by using the hasError method to determine if an error is present in the validator.

댓글 없음:

댓글 쓰기