[Spring Boot] Validation 관련 : BindingResult 클래스

2023. 4. 11. 19:39·Java/Spring Boot
728x90
728x90

#  관련 포스팅

  - Validation 개념 : https://young0105.tistory.com/194

 


BindingResult 클래스

  - @Valid에 대한 결과 값을 갖는 클래스 

      → 직접 예외에 대한 클래스를 컨트롤할 수 있음 (POST 요청에서 자주 사용됨)

  - 단독으로 매개변수에 들어가면 오류 발생

      → 반드시 유효성 검사 대상인 다른 매개변수 바로 뒤에 지정되어야 함

  - Error에 대한 정보를 담는 DTO 클래스를 따로 만들어서 DTO 형식으로 에러 정보를 보낼 수도 있음

 

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
32
33
34
35
@PostMapping("/user3")
public ResponseEntity<?> user3(@Valid @RequestBody User user,
        BindingResult bindingResult) {
    
    // 에러가 있다면
    if (bindingResult.hasErrors()) {
        // 응답 HTTP 메시지 body에 보낼 문자열
        StringBuilder sb = new StringBuilder();
        
        // 모든 에러를 담은 리스트 (스트림 연산 활용)
        // forEach()는 .stream()을 생략해도 정상 작동함
        bindingResult.getAllErrors().forEach(error -> {
            // 에러가 발생한 필드 확인
            System.out.println(error.getCode());
            
            // 에러 발생 시 메세지 확인
            System.out.println(error.getDefaultMessage());
            
            // 에러가 발생한 객체명 확인
            System.out.println(error.getObjectName());
            
            sb.append("field : " + error.getCode()); // 에러가 발생한 필드
            sb.append("\n");
            sb.append("message : " + error.getDefaultMessage()); // 에러 시 메세지
            sb.append("\n");
        });
        
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(sb.toString());
    }
    
    // 에러가 없다면
        return ResponseEntity.ok(user);
    }
    
}
Colored by Color Scripter
cs
320x100
반응형
저작자표시 비영리 변경금지 (새창열림)

'Java > Spring Boot' 카테고리의 다른 글

[Spring Boot] JSP 템플릿 엔진 연결하기  (0) 2023.04.12
[Spring Boot] 예외 처리 (exception)  (0) 2023.04.12
[Spring Boot] Validation (유효성 검사)  (0) 2023.04.11
[Spring Boot] AOP (관점 지향 프로그래밍) ★  (0) 2023.04.11
[Spring Boot] ResponseEntity  (0) 2023.04.11
'Java/Spring Boot' 카테고리의 다른 글
  • [Spring Boot] JSP 템플릿 엔진 연결하기
  • [Spring Boot] 예외 처리 (exception)
  • [Spring Boot] Validation (유효성 검사)
  • [Spring Boot] AOP (관점 지향 프로그래밍) ★
스응
스응
    반응형
    250x250
  • 스응
    이서영의 개발 블로그
    스응
  • 전체
    오늘
    어제
  • 글쓰기 관리
    • 분류 전체보기 (384)
      • Java (134)
        • Base (54)
        • Spring Boot (37)
        • JSP (16)
        • Swing (GUI) (20)
        • Design Pattern (7)
      • C# (13)
      • PHP (18)
      • SQL (27)
      • Vue.js (9)
      • Tailwind CSS (4)
      • TypeScript (7)
      • HTML & CSS (27)
      • JavaScript (26)
      • jQuery (10)
      • Android (3)
      • - - - - - - - - - - - - - - (0)
      • Hotkeys (5)
      • CS (30)
      • etc. (13)
      • Error Note (16)
      • Team Project (24)
        • Airlines Web Project (12)
        • University Web Project (6)
        • Strikers 1945 GUI Project (6)
      • My Project (18)
        • Library Web Project (8)
        • Pet Shopping Mall GUI Project (10)
  • 블로그 메뉴

    • Home
    • Write
  • 링크

    • 깃허브
  • 공지사항

  • 인기 글

  • 태그

    HTML
    Codeigniter
    Hotkeys
    SQL
    티스토리챌린지
    C#
    Wordpress
    zapier
    SpringBoot
    SEO
    CSS
    Android
    tailwindcss
    php
    typeScript
    jsp
    errorNote
    vuejs
    jQuery
    개발일지
    git
    SWAGGER
    Swing
    java
    js
    오블완
    http
    cs
    면접
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.0
스응
[Spring Boot] Validation 관련 : BindingResult 클래스
상단으로

티스토리툴바