@GetMapping
application/json 요청이므로 DispatcherServlet이 내부적으로 jsonMessageConvert를 사용해 Map 객체를 json으로 변환해 전송
@PostMapping
guestbook 객체로 반환된 것이 json으로 변환되어 client로 전달
@DeleteMapping("/{id}")
id는 pathVariable, 메소드 성공 시 Map객체 생성, 키값은 success, value값은 boolean인 Map 객체 반환
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") //APPI클래스 내에서 같은 매핑으로 여러 메소드를 수행
public class GuestbookApiController {
@Autowired
GuestbookService guestbookService;
@GetMapping //RequestMapping을 위에 사용했으므로 path 설정 안해도됨
//
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) {
//IP 주소 구함
String clientIp=request.getRemoteAddr();
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");
}
}