Spring/JPA + Security
[Spring Data JPA] 댓글 구현하기 -5 유효성 검사하기(null 체크)
pyogowoon
2023. 1. 15. 14:20
@Data
public class CommentDto {
//NotNull = null값 체크
//@NotEmpty 빈값이거나 null을 체크
//NotBlank = 빈값이거나 null체크 그리고 빈 공백(스페이스) 까지
@NotBlank
private String content;
@NotNull
private Integer imageId;
// toEntity가 필요없다
}
Dto 에서 int - Integer로 바꿔주었다.
@PostMapping("/api/comment")
public ResponseEntity<?> commentSave(@Valid @RequestBody CommentDto commentDto, BindingResult bindingResult, @AuthenticationPrincipal PrincipalDetails principalDetails){
// System.out.println(commentDto);
if(bindingResult.hasErrors()){
Map<String , String> errorMap = new HashMap<>();
for(FieldError error : bindingResult.getFieldErrors()){
errorMap.put(error.getField(), error.getDefaultMessage());
}
throw new CustomValidationApiException("유효성 검사 실패함" , errorMap);
}
Comment comment = commentService.댓글쓰기(commentDto.getContent(),commentDto.getImageId() , principalDetails.getUser().getId());
return new ResponseEntity<>(new CMRespDto<>(1,"댓글쓰기성공",comment), HttpStatus.OK);
}
@valid 어노테이션을 선언하고 BindingResult 를 매개변수 선언 후
import 해서 customValidationApiException 을 사용
function addComment(imageId) {
let commentInput = $(`#storyCommentInput-${imageId}`);
let commentList = $(`#storyCommentList-${imageId}`);
let data = {
imageId : imageId,
content: commentInput.val()
}
// console.log(data);
// console.log(JSON.stringify(data));
// return;
//
// if (data.content === "") {
// alert("댓글을 작성해주세요!");
// return;
}
$.ajax({
type:"post",
url:"/api/comment",
data:JSON.stringify(data),
contentType:"application/json; charset=utf-8",
dataType:"json"
}).done(res =>{
// console.log("성공",res)
let comment = res.data;
let content = `
<div class="sl__item__contents__comment" id="storyCommentItem-${comment.id}">
<p>
<b>${comment.user.username} :</b>
${comment.content}
</p>
<button onclick="deleteComment(${comment.id})">
<i class="fas fa-times"></i>
</button>
</div>
`;
commentList.prepend(content); // append= 뒤에다가 넣는거 prepend는 앞에다가넣음 최신댓글이 위로 올라와야하니까
}).fail(error => {
console.log("오류",error.responseJSON.data.content);
alert(error.responseJSON.data.content);
});
commentInput.val(""); // 인풋 필드 깨끗하게 비워준다.
}
원래 있던
// if (data.content === "") {
// alert("댓글을 작성해주세요!");
// return;
부분을 주석처리하고 ( 프론트에서 유효성검사 하는 로직이라서 잠시 주석처리하고 테스트해보려고 주석처리 한것
테스트가 끝나면 다시 주석 해제.)
그리고 fail 펑션에 에러를 띄우는 alert를 추가하면 끝.
백엔드 단에서도 잘 잡아준다.