RestController를 이용하여 web api작성하기

최준영·2021년 10월 1일
0

실습 코드

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;

  @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;
  }
  
  @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");
  }
}
  • 클래스 자체에 RequestMapping을 선언하면 안쪽의 것들을 공통으로 사용할 수 있다.
    • 내부의 Mapping어노테이션에 path를 안붙여도 된다.
profile
do for me

0개의 댓글