728x90

RestApi method

 

GET 서버의 리소스에 접근
POST 서버에 데이터 전송
PUT 서버의 리소스를 갱신
DELETE 서버의 리소스 삭제

 

URI 맵핑 

site/items/sub-items/pk

 기존에 uri를 설계할 때는 'site/items_service' 처럼 자원과 그 행위를 표현하는 방식을 많이 사용했는데 

RestApi는 행위는 RequestMethod로 충분하고

- URI는 자원을 표현한다. 

- /은 자원의 계층관계를 나타내고 URI 마지막에 붙이지 않는다. 

- _은 사용하지 않는다. -은 가독성을 위해 사용할 수 있다.

-  소문자를 사용한다. 

- 파일 확장자.xx는 사용하지 않는다. 

- 컬렉션(집합)자원은 s(복수형)을 붙이고, 다큐먼트(객체) 자원은 단수형을 사용하면 직관적인 설계가 될 수 있다.

 

 

HTTP 응답상태 코드 

- 2xx : 정상적 응답

- 301 : redirect 된 경우 

- 4xx : 클라이언트의 부적절한 요청에 대한 응답 

- 500 : 서버측에 문제 발생

 

RestController

@GetMapping(value = "/guests",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

public Map<String,Object> guest_list()throws Exception{

Map<String, Object> resultMap=new HashMap<String, Object>();

int status=1;

String msg="성공";

List<Guest> data=new ArrayList<Guest>();

data=guestService.selectAll();

resultMap.put("status", status);

resultMap.put("msg", msg);

resultMap.put("data", data);

 

return resultMap;

}

@GetMapping(value = "/guests/{guest_no}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

public Map<String,Object> guest_detail(@PathVariable(value = "guest_no") int guest_no )throws Exception{

Map<String, Object> resultMap=new HashMap<String, Object>();

int status=1;

String msg="성공";

List<Guest> data=new ArrayList<Guest>();

Guest guest=guestService.selectByNo(guest_no);

if(guest!=null) {

data.add(guest);

}else {

status=2;

msg="게시물이 존재하지않습니다.";

}

 

resultMap.put("status", status);

resultMap.put("msg", msg);

resultMap.put("data", data);

 

return resultMap;

}

guests URI 에 파라메터를 받아서 queryString으로 맵핑하지 않고 

guests/{guest_no}로 guest_no를 URI PathVariable로 받아서 맵핑한다. 

@PostMapping(value = "/guests",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

public Map<String,Object> guest_write_action(@RequestBody Guest guest){

Map<String, Object> resultMap=new HashMap<String, Object>();

int status=1;

String msg="성공";

List<Guest> data=new ArrayList<Guest>();

try {

int insert_guest_no=guestService.insertGuest(guest);

status=1;

msg="성공";

Guest newGuest=guestService.selectByNo(insert_guest_no);

data.add(newGuest);

} catch (Exception e) {

status=2;

msg="방명록쓰기실패";

e.printStackTrace();

}

 

resultMap.put("status", status);

resultMap.put("msg", msg);

resultMap.put("data", data);

return resultMap;

}

동일한 guests URI에 POST 방식으로 요청을 보내는 컨트롤러 

Model이나 Request Param이 아닌 

RequestBody 어노테이션을 사용

@Operation(summary = "방명록수정",description = "전송되는아이디에해당하는 게시물수정")

@Parameter(name = "guest_no",description = "방명록의번호")

@PutMapping(value = "/guests/{guest_no}")

public Map<String,Object> guest_modify_action( @PathVariable("guest_no") int guest_no,

@RequestBody Guest guest)throws Exception{

Map<String, Object> resultMap=new HashMap<String, Object>();

int status=1;

String msg="성공";

List<Guest> data=new ArrayList<Guest>();

guest.setGuest_no(guest_no);

guestService.updateGuest(guest);

data.add(guest);

 

resultMap.put("status", status);

resultMap.put("msg", msg);

resultMap.put("data", data);

 

return resultMap;

}

Put 방식으로 맵핑

//@ExceptionHandler(Exception.class)

public Map<String,Object> exceptionHandler(Exception e){

Map<String, Object> resultMap=new HashMap<String, Object>();

int status=3;

String msg="알수없는예외";

List data=new ArrayList();

data.add(e.getMessage());

 

resultMap.put("status", status);

resultMap.put("msg", msg);

resultMap.put("data", data);

return resultMap;

}

Exception이 발생할 때 처리할 Controller도 다른 RestController와 같은 형식을 갖는다. 

 

 

 

HTTP 요청시 Content-Type 

 - text타입 : text/css, text/plain, text/javascript, text/html

 - file : multipart/form-data

 - application : application/json, application/x-www-urlencoded

 

application/json 

{key : value}

 

application/x-www-urlencoded

key=value&key=value

html의 form의 기본 content-type 

'Java > Spring Boot' 카테고리의 다른 글

JPA 계층형 게시판  (0) 2023.10.10
Spring Data JPA begins  (0) 2023.10.06
Spring addViewControllers  (0) 2023.09.14
Thymeleaf in Spring  (0) 2023.09.14
Spring Interceptor  (0) 2023.09.14

+ Recent posts