Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 백준온라인저지
- 가운데를말해요
- BOJ
- KT포트포워딩
- 백준평범한배낭
- 합성곱연산
- 백준스택
- 백준10828
- 백준가운데를말해요
- 확인문제
- 코드트리
- 이것이자바다확인문제
- 코딩테스트실력진단
- 냅색알고리즘
- 카카오코테
- 백준
- java
- 2019카카오코테
- 백준9012
- 스파르타코딩클럽
- 컴퓨터비전
- 웹개발기초
- 백준괄호
- 이것이자바다
- BOJ1655
- 이것이자바다9장
- 코테
- 윤곽선검출
- 운영체제
- 딥러닝
Archives
- Today
- Total
코딩하는 락커
[Spring Boot를 이용한 RESTful Web Services 개발] 18~19강 본문
🍃 Spring/🌱 Spring Boot를 이용한 RESTful Web Service
[Spring Boot를 이용한 RESTful Web Services 개발] 18~19강
락꿈사 2022. 2. 8. 15:34유효성 체크를 위한 Validation API 사용
- 사용자가 입력한 데이터에 대한 유효성 체크 기능
- JDK에 포함된 Validation 기능과 Hibernate 라이브러리에 포함된 Hibernate Validation 기능 사용
- Hibernate는 Java에서 Database관련 기능을 개발하기 위해 사용하는 API로 Java의 객체와 Database의 Entity와 매핑하기 위한 프레임워크 제공
- UserDomain 클래스에 저장하려고 하는 name, joinDate 속성의 유효성 체크
- Validation 의존성 추가 (강의에서는 바로 됐는데 나는 에러뜨길래 pom.xml에 의존성 추가해줌. 찾아보니까 Srping boot 2.3 version 이상부터는 Spring-boot-starter-web 의존성 내부에 있던 validation이 사라졌다고 함 (https://wildeveloperetrain.tistory.com/25 <- 링크 참고)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.5.2</version>
</dependency>
- User 클래스에 @Size, @Past 어노테이션을 추가
- @Past 어노테이션은 회원 가입 날짜가 현재 시간과 현재 시간 이전의 날짜만 올 수 있고 미래 데이터는 입력할 수 없도록 지정해주는 기능을 함
package com.example.restfulwebservice.user;
import lombok.AllArgsConstructor;
import lombok.Data;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import java.util.Date;
@Data
@AllArgsConstructor
public class User {
private Integer id;
@Size(min=2)
private String name;
@Past
private Date joinDate;
}
- UserController 클래스의 매개변수에 @Valid 어노테이션 추가
- @Valid 어노테이션은 사용자가 전달하는 user 값을 Validation 체크를 하는 기능
@PostMapping("/users")
public ResponseEntity<User> createUser(@Valid @RequestBody User user){
User savedUser = service.save(user);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedUser.getId())
.toUri();
return ResponseEntity.created(location).build();
}
잘못된 입력을 했을 때 Body에 적절한 에러 메시지 출력하기
- ResponseBodyExceptionHandler 클래스의 handleMethodArgumentNotValid 메소드를 오버라이딩하기
- @Override 어노테이션을 추가하여 Override 된 것 명시
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
// 이전에 만들었던 ExceptionResponse 클래스의 인스턴스를 만들기
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), ex.getBindingResult().toString());
// 위에서 만든 ExceptionResponse 값을 ResponseEntity의 형태로 인스턴스 만들어 반환
return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);
}
- 에러 메시지가 너무 긴 문제를 수정. 간단하게 "Validation Failed"만 출력하기로 함
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
// 이전에 만들었던 ExceptionResponse 클래스의 인스턴스를 만들기
ExceptionResponse exceptionResponse = new ExceptionResponse
(new Date(), "Validation Failed", ex.getBindingResult().toString());
// 위에서 만든 ExceptionResponse 값을 ResponseEntity의 형태로 인스턴스 만들어 반환
return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);
}
유효성 메시지 추가하기
- @Size(message="~")로 유효성 메시지 추가
package com.example.restfulwebservice.user;
import lombok.AllArgsConstructor;
import lombok.Data;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import java.util.Date;
@Data
@AllArgsConstructor
public class User {
private Integer id;
@Size(min=2, message = "Name은 2글자 이상 입력해주세요.")
private String name;
@Past
private Date joinDate;
}
'🍃 Spring > 🌱 Spring Boot를 이용한 RESTful Web Service' 카테고리의 다른 글
[Spring Boot를 이용한 RESTful Web Services 개발] 22~24강 (0) | 2022.02.09 |
---|---|
[Spring Boot를 이용한 RESTful Web Services 개발] 20~21강 (0) | 2022.02.08 |
[Spring Boot를 이용한 RESTful Web Services 개발] 17강 (0) | 2022.02.07 |
[Spring Boot를 이용한 RESTful Web Services 개발] 16강 (0) | 2022.02.07 |
[Spring Boot를 이용한 RESTful Web Services 개발] 13~15강 (0) | 2022.02.06 |
Comments