본문 바로가기
Framework & Library/Spring & Egov

(스크랩)Spring에서 REST방식 이용하기

by 뒹굴거리는프로도 2018. 1. 17.
반응형

https://appear.github.io/2017/12/20/Spring/spring-05/


Rest

Rest(Representational State Transfer)의 약자입니다. 하나의 URI는 고유한 리소스를 대표하도록 설계하는 것 입니다.
기기의 종류들이 다양해지면서 데이터 통신방식의 혼란이 왔습니다. 공통된 규칙으로 데이터를 처리하기위해 REST라는 방식을 대안으로 사용합니다.

정리해보자면 Rest란 하나의 URI가 고유한 리소스를 다루는 공통적인 규칙을 가지는 방식입니다.

하나의 URI는 고유한 리소스를 가진다는 말은

1
2
ex)
board/2 => board라는 값은 게시판의 리소스를 가진다. /2는 게시판의 2번째 글을 달라

이런 규칙을 가질 수 있습니다.

Rest방식으로 제공되는 URI를 Rest API라고 하고 Open API에서 많이 사용되고 있습니다.

RestController

스프링에서는 @RestController 을 이용해서 Rest API를 만들 수 있습니다.
기존의 컨트롤러처럼 뷰를 만들어내는 것이 목적이아닌, 데이터처리를 위한 컨트롤러를 만들수 있습니다.

1
2
3
4
5
@RestController
@RequestMapping("/sample/*")
public class SampleController {
}

문자열의 경우

1
2
3
4
5
6
7
8
@RestController
@RequestMapping("/sample/*")
public class SampleController {
@RequestMapping("/hello")
public String hello(){
return "Hello Rest"
}
}

rest

문자열의경우 브라우저에서 text/html 로 처리된다는걸 알 수 있습니다.
rest

객체의 경우

1
2
3
4
5
6
7
8
public class SampleVO {
private Integer mno;
private String firstName;
private String lastName;
//.. getter, setter 생략...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RestController
@RequestMapping("/sample/*")
public class SampleController {
@RequestMapping("/hello")
public String sayHello() {
return "Hello Rest";
}
@RequestMapping("/sendVO")
public SampleVO sendVO() {
SampleVO vo = new SampleVO();
vo.setMno(0);
vo.setFirstName("짱");
vo.setLastName("구");
return vo;
}

객체의 경우 Json으로 반환이됩니다. Json을 다루기 위해서는 Jackson 라이브러리가 필요합니다.

1
2
3
4
5
6
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.4</version>
</dependency>

rest
rest

컬렉션 객체의 경우

List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@RestController
@RequestMapping("/sample/*")
public class SampleController {
@RequestMapping("/hello")
public String sayHello() {
return "Hello Rest";
}
@RequestMapping("/sendVO")
public SampleVO sendVO() {
SampleVO vo = new SampleVO();
vo.setMno(0);
vo.setFirstName("짱");
vo.setLastName("구");
return vo;
}
@RequestMapping("/sendList")
public List<SampleVO> sendList() {
List<SampleVO> list = new ArrayList<SampleVO>();
for (int i = 0; i < 10; i += 1) {
SampleVO vo = new SampleVO();
vo.setMno(i);
vo.setFirstName("짱");
vo.setLastName("구");
list.add(vo);
}
return list;
}
}

rest

Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@RestController
@RequestMapping("/sample/*")
public class SampleController {
@RequestMapping("/hello")
public String sayHello() {
return "Hello Rest";
}
@RequestMapping("/sendVO")
public SampleVO sendVO() {
SampleVO vo = new SampleVO();
vo.setMno(0);
vo.setFirstName("짱");
vo.setLastName("구");
return vo;
}
@RequestMapping("/sendList")
public List<SampleVO> sendList() {
List<SampleVO> list = new ArrayList<SampleVO>();
for (int i = 0; i < 10; i += 1) {
SampleVO vo = new SampleVO();
vo.setMno(i);
vo.setFirstName("짱");
vo.setLastName("구");
list.add(vo);
}
return list;
}
@RequestMapping("/sendMap")
public Map<Integer, SampleVO> sendMap() {
Map<Integer, SampleVO> map = new HashMap<Integer, SampleVO>();
for (int i = 0; i < 10; i += 1) {
SampleVO vo = new SampleVO();
vo.setMno(i);
vo.setFirstName("짱");
vo.setLastName("구");
map.put(i, vo);
}
return map;
}
}

rest

@PathVariable

@PathVariable는 URL경로에서 원하는 데이터를 추출할 수 있습니다.

/all/{bno} => /all/3 => 3을 추출하고 싶을때 아래와 같이 할 수 있습니다.

1
2
3
4
@RequestMapping(value= "/all/{bno}", method = RequestMethod.GET)
public Integer list(@PathVariable("bno") Integer bno) throws Exception{
logger.info(bno);
}

@RequestBody

@RequestBody는 전송된 JSON 데이터를 객체로 변환해줍니다. @ModelAttribute와 유사한 역할을 합니다. JSON을 다룬다는 점에서 다릅니다.

1
2
3
public void update(@RequestBody ReplyVO vo){
logger.info(vo.toString());
}

Rest방식으로 Ajax 요청

Ajax가 뭔지 모르시겠다면 여기를 참고해주세요

요청단계

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$.ajax({
type : 'put',
url : '/replies/' + rno,
headers : {
"Content-Type" : "application/json",
"X-HTTP-Method-Override" : "PUT" // put, delete
},
data : JSON.stringify({replytext : replytext}),
dataType : 'text'
}).done(function(result){
console.log("result", result);
if(result == "SUCCESS"){
alert("수정 완료!");
}
});


반응형