티스토리 뷰
[API Specification(API 명세)]
1. HTTP Method → GET
2. HTTP Path → /user
3. 쿼리 없음
4. API 반환 결과 → [{"id" : Long, "name" : String, "age" : Integer}, ...] → JSON 형
* Controller에서 getter가 있는 객체를 반환하면 JSON이 된다.
- Spring이 자체적으로 getter를 JSON 형식으로 변환해주는 것이다.
- 이것은 @RestController Annotation을 붙였기에 가능한 것이다.
@RestController = @Controller + @ResponseBody
[Controller]
@RestController
public class UserController {
private final List<User> users = new ArrayList<User>();
@PostMapping("/user")
public void saveUser(@RequestBody UserCreateRequest request) {
users.add(new User(request.getName(), request.getAge()));
}
@GetMapping("/user")
public List<UserResponse> getUsers() {
List<UserResponse> responses = new ArrayList<>();
for (int i = 0; i < users.size(); i++) {
responses.add(new UserResponse((i + 1), users.get(i)));
}
return responses;
}
}
[DTO]
public class UserResponse {
private long id;
private String name;
private Integer age;
public UserResponse(long id, User user) {
this.id = id;
this.name = user.getName();
this.age = user.getAge();
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
}
[domain]
public class User {
private String name;
private Integer age;
public User(String name, Integer age) {
if(name == null || name.isBlank()) throw new IllegalArgumentException(String.format("잘못된 name(%s)이 들어왔습니다.", name));
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}


'Backend > Spring' 카테고리의 다른 글
| #12 MySQL - CRUD with DML (0) | 2023.08.14 |
|---|---|
| #11 MySQL - CREATE TABLE (0) | 2023.08.13 |
| #9 유저 생성 API (0) | 2023.08.11 |
| #8 GET API의 DTO와 POST API의 DTO가 차이가 나는 이유 (0) | 2023.08.09 |
| #7 DTO와 VO(Entity는 링크한 글을 보자) (0) | 2023.08.04 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 빅데이터
- Phaser
- node.js
- Java8
- nosql
- SQL
- 자료구조
- java
- Spring Boot
- spring
- 코테
- MongoDB
- 코딩테스트
- 운영체제
- 프로세스
- API
- Phaser3
- 빅데이터 분석기사
- MySQL
- db
- SpringBoot
- DART
- 메모리
- git
- OS
- 프로그래머스
- 알고리즘
- Advanced Stream
- Stream
- jpa
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
글 보관함
