REST API 구현하기


HTTP Method GET


1. GET 메소드 구현하기



com.example.test 아래에 controller 패키지를 생성하고 GetAPIController.java 파일을 생성한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.example.test.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
@RestController // 여기는 컨트롤러라고 알려주는 @RestController 어노테이션 사용
@RequestMapping("/api"// 여기로 들어올 path를 지정할 @RequestMapping 어노테이션 사용 localhost:8080/api
public class GetAPIController {
 
    @RequestMapping(method = RequestMethod.GET, path = "/getRequest")   // localhost:8080/api/getRequest
    public String getRequest(){
        return "this is getRequest";
    }
 
}
cs


GetAPIController.java 의 내용을 위와 같이 넣어준다.

그리고 웹브라우저를 통해 http://localhost:8080/api/getRequest로 접속하여 결과가 나오는지 테스트한다.




결과가 잘 나오는 것을 확인했다.


하지만 GET Method는 웹에서 파라미터가 뒤에 계속 붙으면서 보여진다.

이런식으로 http://localhost:8080/api/getRequest?id=shlee0882&email=shlee0882@gmail.com

요청해야하는데 파라미터를 받아서 처리해보자.


2. 파라미터 받아서 GET 메소드 처리하기


1
2
3
4
5
    // GetMapping은 RequestMapping과는 다르게 메소드유형 없이 주소만 지정해주면된다.
    @GetMapping("/getParameters")  // localhost:8080/api/getParameters?id=shlee0882&email=shlee0882@gmail.com
    public String getParameters(@RequestParam String id, @RequestParam String email){
        return "아이디는 "+id+" 이메일은 "+email;
    }
cs


@GetMapping이라는 어노테이션을 사용했다.

@GetMapping은 @RequestMapping과 다르게 메소드유형 없이 path만 지정해 주면 된다.

메소드로 받을 인자값 2개를 설정해 주었다.

웹브라우저를 통해 파람값을 붙여서 요청했다.

http://localhost:8080/api/getRequest?id=shlee0882&email=shlee0882@gmail.com

결과가 잘 나오는 것을 확인했다.



위의 메소드는 인자값이 Request 파라미터값이 되기 때문에

메소드의 인자값을 바꿔주고 싶을때는 RequestParam의 name을 지정해주고 

받아온 param값의 변수를 새롭게 지정하여 활용할 수 있다.


1
2
3
4
5
    @GetMapping("/getParameters")  
    public String getParameters(@RequestParam(name = "id"String userId
                              , @RequestParam(name = "email"String userEmail){
        return "아이디는 "+userId+" 이메일은 "+userEmail;
    }
cs


하지만 만약 프론트에서 넘어온 데이터 RequestParam값이 10개 이상이면 

매번 RequestParam을 선언해주며 인자를 만들수는 없다.


이럴경우 모델(Model) 객체를 활용하여 받아올수 있다.



model 패키지를 생성하여 SearchVO.java를 만든다.


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
package com.example.test.model;
 
public class SearchVO {
    private String id;
    private String email;
    private int page;
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public int getPage() {
        return page;
    }
 
    public void setPage(int page) {
        this.page = page;
    }
}
cs


SearchVO.java의 Getter, Setter 메소드 모델을 작성해준다.


1
2
3
4
    @GetMapping("/getMultiParameters")
    public String getMultiParameters(SearchVO searchVo) {
        return "VO사용 아이디는 "+searchVo.getId()+" 이메일은 "+searchVo.getEmail();
    }
cs


http://localhost:8080/api/getMultiParameters?id=shlee0882&email=shlee0882@gmail.com 요청한다.



객체를 사용하여 인자 1개만으로 여러개의 파라미터를 받아 처리하여 결과가 잘 나온것 확인했다.


하지만 API는 대부분 요청에 대한 응답 결과값을 json형태로 받는다.

결과값을 json 형태 { id : shlee0882, email : shlee0882@gmail.com } 이런식으로 return 받으려면 다음과 같이 작성할 수 있다. 


1
2
3
4
    @GetMapping("/getMultiParametersRtnJson")
    public SearchVO getMultiParametersRtnJson(SearchVO searchVo) {
        return searchVo;
    }
cs


http://localhost:8080/api/getMultiParametersRtnJson?id=shlee0882&email=shlee0882@gmail.com 요청한다.



결과가 json으로 받아지는 것을 확인했다.


Spring Boot 프로젝트 만들기 - 1


1. IntelliJ에서 프로젝트 생성하기


- JDK 12 설치


인텔리J를 사용하려면 높은 JDK버전이 필요하므로 JDK 12를 설치한다.


https://www.oracle.com/technetwork/java/javase/downloads/jdk12-downloads-5295953.html



- Intellij 설치




https://www.jetbrains.com/idea/download/#section=windows


인텔리J IDEA Ultimate 버전을 다운받는다.

평가판으로 일정기간 무료로 사용할수 있다.




위와 같이 체크해준다.

64비트, Update Path variable, 

Add "Open Folder as Project", .java, Download install JBR x86 (젯브레인에서 제공하는 라이브러리도 설치) 한다.


설치가 완료되면 바탕화면에 바로가기 아이콘이 생성되고 intellij를 실행한다.



기본설정을 선택하고 OK버튼을 누른다.



본인이 원하는 테마를 선택하고 다음 설정으로 넘어간다.



커스터마이징 하는부분인데 기본설정으로 다음으로 넘어간다.



다음버튼을 누른다.



30일 평가판으로 설치한다.



설치가 완료되면 다음과 같이 나타난다.

Create New Project를 누른다.



Project SDK가 JDK 12로 잡혀져있는지 확인한다.

왼쪽 메뉴에 Spring Initializer를 선택하고 Next를 누른다.



이름은 test로 Gradle Project를 선택하고 기본셋팅으로 Next를 누른다.



새 프로젝트를 어떻게 구성할지 체크해서 시작할수 있다.

간단하게 Web > Spring Web Starter를 체크하여 Next 버튼을 누른다.



Finsh 버튼을 누른다.



그러면 다음과 같이 import Module from Gradle 이라는 창이 뜨고

Use auto-import, Use default Gradle wrapper를 선택해주고 OK버튼을 누른다.



sync가 finished 되면 프로젝트를 실행시켜본다. 

Shift+F10 단축키나 TestApplication.java 파일로 접근하여 실행버튼을 누르면 된다.



Tomcat started on port 8080이 나타나면 성공이다.

Spring Boot 개발환경 설정을 완료했다.



2. Spring Initializer 활용하여 생성하기


https://start.spring.io/ 로 접속한다.



Dependencies에서 필요한 것들을 추가한 다음

Generate the project로 생성한다.


zip파일로 다운 되는데 압축을 푼다.


intelliJ를 실행하여 File > Open 으로 압축푼 폴더를 지정한다.




Use-auto-import를 체크해주고 OK 버튼을 누른다.




생성이 완료 되고 프로젝트를 실행하면 잘 구동되는 것을 확인 했다.

+ Recent posts