티스토리 뷰

1. JSR-303

  • JSR- 303는 자바플랫폼의 유효성 검사 제약사항 선언과 메타데이터를 표준화한다. JSR-303 API를 사용해서 선언적인 유효성 제약사항으로 도에인 모델 프로퍼티에 어노테이션을 붙히고 런타임시에 이를 강제할 수 있다. 사용할 만한 다수의 내장 제약사항이 존재한다. 물론 자신만의 커스텀 제약사항도 정의할 수 있다.

 

2. JSR-303 Specification

  • 검증은 Field 및 Collection에 사용할 수 있다.
 Annotation Specification
 @NotNull validates that the annotated property value is not null
 @AssertTrue validates that the annotated property value is true
 @Size validates that the annotated property value has a size between the attributes min and max; can be applied to String, Collection, Map, and array properties
 @Min vValidates that the annotated property has a value no smaller than the value attribute
 @Max validates that the annotated property has a value no larger than the value attribute
 @Email validates that the annotated property is a valid email address
  • additional annotation
 Annotation Specification
 @NotEmpty validates that the property is not null or empty; can be applied to String, Collection, Map or Array values
 @NotBlank can be applied only to text values and validated that the property is not null or whitespace
 @Positive and @PositiveOrZero apply to numeric values and validate that they are strictly positive, or positive including 0
 @Negative and @NegativeOrZero apply to numeric values and validate that they are strictly negative, or negative including 0
 @Past and @PastOrPresent validate that a date value is in the past or the past including the present; can be applied to date types including those added in Java 8
 @Future and @FutureOrPresent validates that a date value is in the future, or in the future including the present

 

3. JSR-303 Implement Dependency

  • java
    • compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
  • hibernate
    • compile group: 'org.hibernate.validator', name: 'hibernate-validator', version: '6.0.16.Final'
    • compile group: 'org.hibernate.validator', name: 'hibernate-validator-annotation-processor', version: '6.0.16.Final'

 

4. Custom Validatior

public class AlphabetAndNumberValidator implements ConstraintValidator<AlphabetAndNumber, String> {

    @Override
    public void initialize(AlphabetAndNumber constraintAnnotation) {
        //nothing
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if ( value == null) {
            return false;
        }

        Matcher matcher = Pattern.compile("[a-zA-Z]+").matcher(value);
        boolean isExistAlphabet = matcher.find();
        matcher = Pattern.compile("[0-9]+").matcher(value);
        boolean isExistNumber = matcher.find();

        if ( isExistAlphabet && isExistNumber) {
            return true;
        } else {
            return false;
        }
    }
}

 

5. Custom Validate Annotation

@ConstraintComposition(CompositionType.AND)
@Target({ METHOD, FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = AlphabetAndNumberValidator.class)
public @interface AlphabetAndNumber {
     public abstract String message() default "{please. use only alphabet and number}";

     public abstract Class<?>[] groups() default {};

     public abstract Class<? extends Payload>[] payload() default {};
}

6. Target DTO

@Getter
@ToString
public class MemberDto {
    private Long id;

    @AlphabetAndNumber(message = "name only allow alphabet and number")
    @NotNull(message = "name is empty")
    @Size(min = 1, max = 50, message = "member name max length is 50")
    private String name;

    @NotNull(message = "address is empty")
    @Size(min = 1, max = 500, message = "member name max length is 100")
    private String address;

    @NotNull(message = "email is empty")
    @Size(min = 1, max = 1000, message = "email max length is 1000")
    private String email;
}

 

7. Target Controller

@RequestMapping(value = "/member", method = RequestMethod.PUT)
public MemberDto modifyMember(@RequestBody @Valid MemberDto memberDto, BindingResult result) {

	log.debug("#### modifyMember [PUT] - memberDto : {}", memberDto);

	if (result.hasErrors()) {
		return failResponse(result.getAllErrors());
	}

	Member member = memberModifier.modify(
		memberDto.getId(), 
		memberDto.getName(), 
		memberDto.getAddress(), 
		memberDto.getEmail());

	MemberDto modifiedMemberDto = toDto(member);

	return modifiedMemberDto;
}

 

'Programming > Spring' 카테고리의 다른 글

@Enable + Registrar  (0) 2019.04.11
ControllerAdvice  (1) 2019.04.01
AOP  (0) 2019.03.27
Request Proxy  (0) 2019.03.27
Argument Resolver  (0) 2019.03.27
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함