잘못 기입된 값을 받으면 400(Bad Request)를 반환하도록 ValidationCheck 로직 추가
CreateNromalDto
@NotBlank, @Size 등 Validation을 확인하는 어노테이션 추가
ValidationCheck에서 실패 시 MehthodArgumentNotValidException 발생
package com.portfolio.Dto;
import com.portfolio.entity.NormalBoard;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
/**
* 일반 게시판 생성 DTO
date : 2024.07.26
author : 김만기
====== Annotation description ======
Schema: swagger 문서 작성을 위한 annotation
Validation 관련 Annotation(조건에 부합하지않느다면 MethodArgumentNotValidException 발생)
NotBlank: null, "" 체크
Size: 길이 체크
====== field description ======
title: 게시판 제목
content: 게시판 내용
====== method description ======
toEntity: DTO를 DB에 적재하기 위한 Entity로 변환
====== etc description ======
entity를 사용하고 싶었으나 entity를 사용하면 Swagger의 example Value가 모든 필드를 표기하는 문제가 있어서 DTO를 사용
*/
@Getter
@Setter
public class CreateNormalBoardDto {
@Schema(description = "게시판 제목", example = "게시판 제목")
@NotBlank(message = "제목은 필수 입니다.")
@Size(max = 30, message = "제목은 최대 30자 입니다.")
private String title;
@Schema(description = "게시판 내용", example = "게시판 내용")
@NotBlank(message = "내용은 필수 입니다.")
private String content;
public NormalBoard toEntity() {
return NormalBoard.builder()
.title(title)
.content(content)
.build();
}
}
ControllerExceptionHandler
Controller의 Exceltion을 처리하는 Handler
MehthodArgumentNotValidException만 처리하는 메소드 handleValidationException
package com.portfolio.exception.handler;
import com.portfolio.dto.ApiResultDto;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/*
* 컨트롤러 예외처리 핸들러
* date: 2024-07-29
* author: 김만기
*
* ====== Annotation description ======
* RestControllerAdvice: RestController에서 발생하는 예외를 처리하기 위한 annotation
* ExceptionHandler: 특정 예외를 처리하기 위한 annotation
*
* ====== method description ======
* handleValidationExceptions: @size, @notnull 등에서 발생하는 예외를 처리
* 400 Bad Request로 응답하고, data에는 @size 등에서 지정한 message=''를 담아서 전달
*/
@RestControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiResultDto<String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
ApiResultDto<String> result = new ApiResultDto<>();
result.setResultCode("400");
result.setResultMessage("Validation Error");
result.setData(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return ResponseEntity.badRequest().body(result);
}
}
프로젝트의 build.gradle
module-normal-board의 build.gralde
// 빌드 시 bootJar로 생성하지않음
bootJar { enabled = false }
// 다른 모듈의 라이브러리 형태가 될 것이기 때문에 jar 형태로 진행
jar { enabled = true }
dependencies {
// common 모듈에 의존
implementation project(":module-common")
implementation group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '3.4.0'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '3.3.0'
}
module-common의 build.gradle
bootJar { enabled = false }
jar { enabled = true }
dependencies {
/*
* jpa: DB ORM
* validation: Controller 등, validation Check
* */
implementation group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '3.4.0'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '3.3.0'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation', version: '2.5.2'
}
Sweager 조회 및 validation 테스트
request Body에 미리 적어둔 example 적용 완료
shcema에는 validation 내용 및 description 확인
validation에 맞지 않는 데이터 테스트 및 결과
400 badRequest 및 @size에 함께 작성한 message 출력 확인
https://github.com/Kmmanki/portfolio_was
GitHub - Kmmanki/portfolio_was: portfolio
portfolio. Contribute to Kmmanki/portfolio_was development by creating an account on GitHub.
github.com
'웹 정리 > 웹 포트폴리오 만들기' 카테고리의 다른 글
WAS 8차 게시물 조회 API 만들기 (0) | 2024.10.28 |
---|---|
WAS 7차 boot jar 만들어보기 (0) | 2024.09.03 |
WAS 5차 (JPA, Swagger 설정을 사용한 게시물 등록) (0) | 2024.07.26 |
WAS 4차 (ELK, Logback, Jenkins를 사용한 배치 컨트롤 및 로그수집)_긴급 (0) | 2024.06.13 |
WAS 3차 (docker maria DB 세팅) (0) | 2024.06.01 |