티스토리 뷰
1. 클라이언트로부터 요청을 받는 4가지 방법
- @RequestBody
:: JSON 값을 받음
:: Body에 JSON or XML 등을 DTO 객체로 받음 - @PathVariable
:: URI 상의 가변 변수
Ex) /api/users/{id} - @RequestParam
:: 단일 파라미터
Ex) /api/users?key=value - @ModelArribute
:: 다수의 파라미터(DTO 객체로 받기)
Ex) /api/users?key1=value1&key2=value2
4. 관련 이슈
- 관련 실습 코드를 이용해 PUT 요청을 보내던 중, 값이 모두 null이 되는 상황이 나왔다.
@PutMapping("/update/{id}")
public MemberResponseDto update (@PathVariable Integer id , @ModelAttribute MemberCreateRequestDto dto) {
return memberService.update(id , dto);
}

당시에 @PathVariable를 사용했기 때문에 뒤에 다중 쿼리가 아닌 Body-JSON에 값을 보냈지만 NULL이 들어가는 모습이 보여진다
검색을 해봤는데, @ModelArribute를 이용해 Body에 값을 넣어 보내기 위해서는 데이터 형식이 raw가 아닌
form을 위해 만들어진 x-www-form-urlenconded를 사용해야 한다는 것이다....

그런데 이렇게 Body를 쓸거면 따로 준비된 @RequestBody가 있으니,
해당을 이용해 프론트 요청에서 헤더를 직접 조작을 최소화 하도록 하자..
2. @Controller 값 반환과 예외 처리
2.0 API의 결과
- API는 2가지 방식으로 결과의 성공 or 실패에 대한 정보를 제공
1. HTTP Response Status
10X : 정보성 응답 ← Informational Response
20X : 성공 (응답 완료) ← Successful Response
30X : 리다이렉션 ←Redirection
40X : 권한 혹은 잘못된 접근 (유저의 잘못) ← Client Error
50X : 서버 내부 문제 ← Server Error
200 OK : 요청 성공
201 Created : 새로운 자원이 성공적으로 생성
400 Bad Request : 잘못된 요청
401 Unauthorized : 인증 실패 = 유저가 제출한 인증정보 불충분
403 Forbidden : 인가 실패 = 인증은 됐는데 적절한 권한이 없어서 거절됨
404 Not Found : 요청한 자원을 찾을 수 없음
500 Internal Server Error : 서버 내부 오류
2. 커스텀 상태코드
:: A01 타입 에러, A02 입력 에러, B01 외부 서버 통신 에러 등
:: 기획자보다는 기술 리드나 개발자들이 모인 기술팀에서 결정하는 에러 코드
2.1 ResponseEntity
:: HTTP Status Code를 갖는 반환 클래스
:: 표준 HTTP Status Code를 활용하여 결과를 반환하기 위한 Wrapper Class
- 구성
1. HTTP 상태 코드 (HttpStatus) :: 응답 상태
2. HTTP 응답 헤더 (optional) :: Content-Type, Location 등등..
3. 응답 본문 (optional) :: 실제 반환 데이터 - Ex)
:: 주로 @RestController나 @Controller에서 사용
// Ex 1) ResponseEntity를 사용하여 HTTP 응답 반환
@RestController
public class MyController {
@GetMapping("/success")
public ResponseEntity<String> success() {
// 200 OK 상태 코드와 본문으로 "Operation was successful" 메시지 반환
return new ResponseEntity<>("Operation was successful", HttpStatus.OK);
}
@GetMapping("/notFound")
public ResponseEntity<String> notFound() {
// 404 Not Found 상태 코드와 본문으로 "Resource not found" 메시지 반환
return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND);
}
@GetMapping("/created")
public ResponseEntity<Object> created() {
// 201 Created 상태 코드와 본문으로 새 리소스 객체 반환
MyResource resource = new MyResource("New resource");
return new ResponseEntity<>(resource, HttpStatus.CREATED);
}
}
==> 제네릭 사용 시,
@GetMapping("/user")
public ResponseEntity<User> getUser() {
User user = new User("John", 30);
return new ResponseEntity<>(user, HttpStatus.OK); // user 객체를 내용으로 반환
}
- 헤더 추가 시,
@GetMapping("/createdWithLocation")
public ResponseEntity<MyResource> createdWithLocation() {
MyResource resource = new MyResource("New resource");
HttpHeaders headers = new HttpHeaders(); // Location 헤더 추가
headers.add("Location", "/resources/123");
return new ResponseEntity<>(resource, headers, HttpStatus.CREATED);
}
3. 예외처리 방법
2025.02.19 - [정리용/SpringBoot] - [Spring] 5. Spring - 예외처리
[Spring] 5. Spring - 예외처리
1. ResponseEntity@ExceptionHandler(Exception.class)public ResponseEntity handleException(Exception ex) { // 예외 발생 시 500 Internal Server Error와 오류 메시지 반환 return new ResponseEntity("Internal Server Error: " + ex.getMessage(), HttpSt
hee-ya07.tistory.com
참조
ASAC 7기 수업자료
'정리용 > SpringBoot' 카테고리의 다른 글
[Spring] 5. Spring - 예외처리 2 (0) | 2025.02.21 |
---|---|
[Spring] 5. Spring - 예외처리 (0) | 2025.02.19 |
[Spring] 4. 3-Layered Architecture Pattern (0) | 2025.02.19 |
[Spring] 3. SpringContext - Bean 주입 (0) | 2025.02.19 |
[Spring] 3. SpringContext - Bean 등록 (1) | 2025.02.19 |
- Total
- Today
- Yesterday
- asac7#asac
- react
- ASAC
- useState
- useContext
- ssh
- useReducer
- useRef
- memo
- asac7기
- useCallback
- acac
- asac#asac7기
- acas#acas7기
- useLayoutEffect
- useMemo
- asac7
- useEffect
- Nginx
- git
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |