Spring Boot

SpringBoot + MariaDB 10-3 댓글 유효성 검사(@NotNull,Blank,Empty)

svdjcuwg4638 2023. 6. 15. 11:24

댓글도 유효성 검사를 추가하기위해 Valition을 작성해보자

 

CommentApiController.java

	@PostMapping("/api/comment")
	public ResponseEntity<?> commentSave(@Valid @RequestBody CommentDto commentDto,BindingResult bindingResult,@AuthenticationPrincipal PrincipalDetails principalDetails){
		if(bindingResult.hasErrors()) {
			Map<String, String>errorMap = new HashMap<>();
			for(FieldError error : bindingResult.getFieldErrors()) {
				errorMap.put(error.getField(), error.getDefaultMessage());
			}
			throw new CustomValidationApiException("유효성검사 실패함",errorMap);
		}else {
			Comment comment = commentService.댓글쓰기(commentDto.getContent(),commentDto.getImageId(),principalDetails.getUser().getId());
			return new ResponseEntity<>(new CMRespDto<>(1,"댓글쓰기성공",comment),HttpStatus.CREATED);
		}
	}

 

Comment.java

// NotNull = null값 체크
// NotEmpty = 빈값이거나 null체크
// NotBlank = 빈값이거나null 체크 그리고 빈 공백(스페이스)까지

@Data
public class CommentDto {
	
	@NotBlank // 빈값이거나 null 빈 공백 체크
	private String content;
	
	@NotNull // 빈값이거나 null체크
	private Integer imageId;
	
	//toEntity가 필요없다
}

@notBlank나 @notEmpty를 사용하니 에러를 잡지못하였다 왜냐하면 Integer은 빈값이없고 값이 없게 받으면 0이 들어오기 때문이다 그리고 Integer을 사용한이유는 int로 값을 받으면 @not을 이용한 유효성 검사가 안되니 유효성 검사를 하고싶다면 Integer자료형을 사용해주자.

 

story.js

이제 에러처리할 준비가되었으니 적용시키러 가보자 

댓글을 작성해주는 함수를 찾아 실패했을때 실패 메시지를 alert로 띄워주면 될것같다.

addComment함수 fail부분

	}).fail(err=>{
		console.log("에러",err.responseJSON.data.content);
		alert(err.responseJSON.data.content)
	});

err데이터안에서 오류 문구만 뽑아 alert로 출력시키는 모습이다.