RestController를 이용한 Web API 작성

oyeon·2021년 1월 27일
0

레이어드 아키텍처(Layered Architecture) 실습5에서 이어짐

  • GuestbookApiController.java 작성
package kr.or.connect.guestbook.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import kr.or.connect.guestbook.dto.Guestbook;
import kr.or.connect.guestbook.service.GuestbookService;

@RestController
@RequestMapping(path="/guestbooks")
public class GuestbookApiController {
	@Autowired
	GuestbookService guestbookService;
	
	/* 1. path가 /guestbooks라고 시작
	 * 2. Content-Type이 application/json  
	 * 3. GET 방식으로 요청이 들어오면
	 * 아래 메서드가 실행후 map 객체를 반환
	 * DispatcherServlet은 jsonMessageConverter를 내부적으로 사용해서
	 * 해당 Map 객체를 json으로 변환해서 클라이언트에게 전송 한다.
	 * (클라이언트에게 응답이 갈 때는 json으로 바뀌어서 간다.)
	 */
	@GetMapping
	public Map<String, Object> list(@RequestParam(name="start", required=false, defaultValue="0") int start) {
		
		List<Guestbook> list = guestbookService.getGuestbooks(start);
		
		int count = guestbookService.getCount();
		int pageCount = count / GuestbookService.LIMIT;
		if(count % GuestbookService.LIMIT > 0)
			pageCount++;
		
		List<Integer> pageStartList = new ArrayList<>();
		for(int i = 0; i < pageCount; i++) {
			pageStartList.add(i * GuestbookService.LIMIT);
		}
		
		Map<String, Object> map = new HashMap<>();
		map.put("list", list);
		map.put("count", count);
		map.put("pageStartList", pageStartList);
		
		return map;
	}
	
	@PostMapping
	public Guestbook write(@RequestBody Guestbook guestbook,
						HttpServletRequest request) {
		String clientIp = request.getRemoteAddr();
		// id가 입력된 guestbook이 반환된다.
		Guestbook resultGuestbook = guestbookService.addGuestbook(guestbook, clientIp);
		return resultGuestbook;
	}
	
	/* path가 /guestbooks/{id} 형식
	 * @PathVariable로 id값을 읽어들인다.
	 */
	@DeleteMapping("/{id}")
	public Map<String, String> delete(@PathVariable(name="id") Long id,
			HttpServletRequest request) {
		String clientIp = request.getRemoteAddr();
		
		int deleteCount = guestbookService.deleteGuestbook(id, clientIp);
		return Collections.singletonMap("success", deleteCount > 0 ? "true" : "false");
	}
}

Rest API를 테스트 하기 위한 클라이언트 tool - 구글 확장 프로그램 Talend API Tester 사용

1. METHOD : GET

SCHEME :// HOST : http://localhost:8080/guestbook/guestbooks
HEADERS : Content-Type, application/json

2. METHOD : GET

SCHEME :// HOST : http://localhost:8080/guestbook/guestbooks?start=5
HEADERS : Content-Type, application/json

3. METHOD : POST

SCHEME :// HOST : http://localhost:8080/guestbook/guestbooks
HEADERS : Content-Type, application/json
BODY : {
"name": "스폰지밥",
"content": "뚱아뚱아뚱아뚱아"
}

  • DB에도 값이 저장되었다.

4. METHOD : DELETE

SCHEME :// HOST : http://localhost:8080/guestbook/guestbooks/13
HEADERS : Content-Type, application/json

  • DB에서 id 13값이 삭제된 것을 확인할 수 있다.
profile
Enjoy to study

0개의 댓글