Controller : 쉽게말해 자동응답기 !
[Timeline Service API]
| 기능 | Method | URL | Return |
| 메모 생성 | POST | /api/memos | Memo |
| 메모 조회 | GET | /api/memos | List<Memo> |
| 메모 변경 | PUT | /api/memos/{id} | Long |
| 메모 삭제 | DELETE | /api/memos/{id} | Long |
위 네가지 기능을 자동응답기에 넣어줘야 한다.
일단 controller package 생성하고 ~

[MemoController.java 클래스]
repository 와 Service를 선언 (필수적인 멤버변수이므로 private final 을 붙여줌)
@RequiredArgsConstructor
@RestController
public class MemoController {
private final MemoRepository memoRepository;
private final MemoService memoService;
}
* annotation :
@RestController (new MemoController를 대신해주는 스프링 기능)
@RequiredArgsConstructor (RestController 만들때 요것들도 같이 넣어준다)
◎ 메모 생성 기능 추가 [MemoController.java 안에!]
@PostMapping("/api/memos")
public Memo createMemo(@RequestBody MemoRequestDto requestDto) {
Memo memo = new Memo(requestDto);
return memoRepository.save(memo);
}
상단 표에서 메모 생성하기 Return type은 → Memo (public Memo~ )
받을 데이터 : MemoRequestDto
POST 방식으로 메모 생성 요청이 들어온다. (RestController)
@PostMapping("/api/memos")
memo를 저장할 클래스 생성 (재료) : Memo memo = new Memo(requestDto);
(Memo.java에서 생성자에서 requestDto 받아서 바로 정보 넣어서 생성해주는거 만들었었던거 써먹기)
@RequestBody : Request가 날아올 때 (post) body에 있는거를 고대로 저장해 달라는 의미
저장작업 : return memoRepository.save(memo);
◎ 메모 조회 기능 추가 [MemoController.java 안에!]
@GetMapping("/api/memos")
public List<Memo> getMemos() {
return memoRepository.findAllByOrderByModifiedAtDesc();
}
상단 표에서 메모 조회하기 Return type은 → List<Memo>
readMemo() (getMemos())
찾을 때 memoRepository에서 findAllByOrderByModifiedAtDesc를 드디어 써먹는다. (내림차순 / 최신순)
return만 써주면 list가 자동반환되니까 더 할게없다.
◎ 메모 수정 기능 추가 [MemoController.java 안에!]
@PutMapping("/api/memos/{id}")
public Long updateMemo(@PathVariable Long id, @RequestBody MemoRequestDto requestDto) {
memoService.update(id,requestDto);
return id;
}
변경되는 친구의 id를 돌려줘야 하니까 Long type
@RequestBody : body라는 애를 넣어줘야되는구나! 스프링이 알게 해 줌
@PathVariable : 어떤 id 가져와야되는지 알려주는 어노테이션
update는 Service단이니까, memoService
◎ 메모 삭제 기능 추가 [MemoController.java 안에!]
@DeleteMapping("/api/memos/{id}")
public Long deleteMemo(@PathVariable Long id) {
memoRepository.deleteById(id);
return id;
}
어떤친구를 삭제해야되는지 -> {id}
Repository에서 deleteById라는 애를 넣어주면 ~!
근데 id가 뭔지 모른다 → @PathVariable : 경로에 있는 변수
[ARC로 기능 확인하기]
Advanced REST client 설치

☞ 조회
URL입력 ▶ localhost:8080/api/memos

└ 오류없이 빈 목록이 잘 조회된다.
☞ 생성
Method를 POST로 바꾸고,
ADD HEADER : Header name : Content-Type | Header value : application/json 설정
Body 부분에 메모 넣어본다.

잘 입력됨. 아까 메모 생성기능 추가할때 넣어준 어노테이션 @RequestBody 가 없으면 오류가 난다.
☞ 삭제
먼저 아이디가 1인 메모 조회해보기
GET 방식으로 localhost:8080/api/memos 조회
Method를 DELETE 로 바꿔주고 localhost:8080/api/memos/1
삭제할 해당 아이디 1 을 지워보기

└ 잘 지워졌돠
'study > spring | java' 카테고리의 다른 글
| [Timeline Service] 타임라인 서비스 만들기 5. 메모 조회 (getMessage) (0) | 2021.06.06 |
|---|---|
| [Timeline Service] 타임라인 서비스 만들기 4. 메모 작성 (writePost) (0) | 2021.06.06 |
| [Timeline Service] 타임라인 서비스 만들기 2. Service (0) | 2021.06.05 |
| [Timeline Service] 타임라인 서비스 만들기 1. Repository (0) | 2021.06.05 |
| [Spring Web Project] Security [2] - MySQL, BcryptPasswordEncoder (0) | 2021.03.01 |