ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Bean Validation 처리
    [공부] 프로그래밍/Spring・Spring Boot (JAVA) 2024. 3. 1. 11:21
    반응형

     

    Bean Validation 처리

     

    Bean Validation은 자바 애플리케이션에서 데이터의 유효성을 검사하는 기능을 말한다. 이는 자바 클래스(빈)의 속성에 대한 제약 조건을 정의하고, 해당 제약 조건을 검사하여 데이터가 기대한 형식과 규칙에 부합하는지 확인한다.

    간단히 말해, Bean Validation은 자바 클래스의 속성에 대한 규칙을 정의하고, 이를 통해 데이터가 유효한지 여부를 검사하는 것이다. 

     


     

    Service 작성

     

    @Service
    public class TestServiceImpl implements TestService {
    
        private static final Logger LOG = LoggerFactory.getLogger(TestServiceImpl.class);
    
        // Validation 체크 실행 서비스
        private final ValidateService validateService;
    
        // Validation 체크 메세지 취득 서비스
        private final CreateErrorMessageService createErrorMessageService;
    
        public MemberManagementMasterUploadServiceImpl(ValidateService validateService, CreateErrorMessageService createErrorMessageService) {
            this.validateService = validateService;
            this.createErrorMessageService = createErrorMessageService;
        }
        
        public Map<String, Object> check() {
    
            try {
            
                Map<String, Object> rtnmap = new HashMap<>();
                // 에러 메세지 리스트
                List<String> errorList = new ArrayList<>();
                rtnmap.put("errorList", errorList);
                
                // 입력체크
                TestForm testForm = new TestForm("test1", "test2");
                Set<ConstraintViolation<TestForm>> validatedPersonEntity = validateService.validate(testForm);
    
                // Validation 체크에 해당되는 경우, 에러 메세지 작성
                if (!validatedPersonEntity.isEmpty()) {
                    errorList.add(createErrorMessageService.createErrorMessage(validatedPersonEntity, testForm).toString());
                }
                
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
    
            return rtnmap;
        }
    }

     

    ValidateService 작성

     

    @Service
    public class ValidateService {
    
        public <T> Set<ConstraintViolation<T>> validate(T target) {
    
            // Validator 생성
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            Validator validator = factory.getValidator();
    
            return validator.validate(target);
        }
    }

     

    CreateErrorMessageService 작성

     

    @Service
    public class CreateErrorMessageService {
    
        public <T> List<String> createErrorMessage(
                Set<ConstraintViolation<T>> constraintViolations, TestForm testForm) {
    
            List<String> errorMessageList = new ArrayList<>();
    
            for (ConstraintViolation<T> violation : constraintViolations) {
                errorMessageList.add(violation.getMessage());
            }
    
            return errorMessageList;
        }
    }

     

    Form 작성

     

    @Getter
    @Setter
    @AllArgsConstructor
    public class TestForm {
    
        /**
         * test1
         */
        @NotBlank(message = "test1 is a required field.")
        @Size(max = 20, message = "Please keep your test1 within 20 characters.")
        @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "Please use half-width characters for your test1.")
        private String test1;
    
        /**
         * test2
         */
        @Size(max = 255, message = "Please keep your test2 within 255 characters.")
        @Pattern(regexp = "^$|^[^\\\\x20-\\\\x7e]*$", message = "Please use full-width characters for your test2.")
        private String test2;
    }

     

    반응형

    '[공부] 프로그래밍 > Spring・Spring Boot (JAVA)' 카테고리의 다른 글

    enum  (0) 2024.03.05
    Repository 테이블 조작  (0) 2024.03.01
    Enum에 해당 값 존재 여부 체크 처리  (1) 2023.10.10
    JWT 토큰 인증 처리  (0) 2023.09.11
    MAP 데이터를 JSON으로 변환  (0) 2023.09.10
Designed by Tistory.