Web

1. Spring Boot - Starter Application by Eclipse(간단한 API 서버)

kakaroo 2022. 2. 2. 21:10
반응형

article logo

 

1. 아래 예처럼 URL을 load 했을 때 설정한 Model 정보가 나타나는 API 서버를 만들어 보겠습니다.

2. Create New Spring Starter Project

3. Run As Spring Boot App

4. Server started

4.1 Server 가 이미 사용중일 경우, cmd 창에서 아래 taskkill 명령어를 통해 서버를 강제 종료할 수 있습니다.
Web server failed to start. Port 8080 was already in use.
>netstat -ao // tomcat port(보통 8080) 사용중인 pid를 찾는다.
>taskkill /f /pid [pid]

5. 아직 API가 구현되지 않았으므로, 아래와 같은 화면이 나오는 것은 정상입니다.


6. Data를 처리하는 클래스, 즉 MVC 중 Model 패키지를 생성하고,
Model에 속해 있는 클래스도 생성한 뒤, 내부까지 구현합니다.

 

public class UserProfile {
    private String id;
    private String name;
    private String phone;
    private String address;
    public UserProfile(String id, String name, String phone, String address) {
        super();
        this.id = id;
        this.name = name;
        this.phone = phone;
        this.address = address;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

7. Client 앱이 API를 처리하는 MVC 패턴 중 C에 해당하는 Controller package를 생성합니다.
@RestController
: Spring framework 이 알아서 해당 클래스를 controller로 인식하고 instance를 생성하게 됩니다.

 

전통적인 Spring MVC의 컨트롤러인 @Controller는 주로 View를 반환하기 위해 사용합니다.
아래와 같은 과정을 통해 Spring MVC Container는 Client의 요청으로부터 View를 반환합니다.
https://kakaroo.tistory.com/10?category=1001571

하지만 Spring MVC의 컨트롤러에서도 Data를 반환해야 하는 경우도 있습니다. Spring MVC의 컨트롤러에서는 데이터를 반환하기 위해 @ResponseBody 어노테이션을 활용해주어야 합니다. 이를 통해 Controller도 Json 형태로 데이터를 반환할 수 있습니다.


@PostConstruct
: WAS(Web Application Server)가 띄워질 때 호출된다. 주로 초기화 메소드에 사용됩니다.
destroy 직전 호출이 필요할 경우, @PreDestroy annotation 을 사용합니다.

@PostConstruct public void init() {
    userMap = new HashMap<String, UserProfile>();
    userMap.put("1", new UserProfile("1", "홍길동", "111-1111", "서울시 강남구 대치1동"));
    userMap.put("2", new UserProfile("2", "홍길서", "222-2222", "서울시 강남구 대치2동"));
    userMap.put("3", new UserProfile("3", "홍길남", "3333-3333", "서울시 강남구 대치3동"));
}


@GetMapping
HTTP GET 요청을 처리하는 메서드를 맵핑(@RequestMapping) 하는 어노테이션입니다. 메서드(url)에 따라 어떤 페이지를 보여줄지 결정하는 역할을 합니다.

@GetMapping("/user/{id}") //localhost:8080/user/id 
public UserProfile getUserProfile(@PathVariable("id") String mapId) { 
	return userMap.get(mapId); 
} 
@GetMapping("/user/all") 
public List<UserProfile> getUserProfileList() { 
	return new ArrayList<UserProfile>(userMap.values());
}


<실행화면>
리턴값을 클래스로 지정할 경우 인스턴스의 내용을 json 형식으로 변환해서 텍스트로 출력하게 됩니다. 공공 데이터 API 사용시 리턴되는 값이 json/xml 형태인 것과 같습니다.





RequestMapping 통상적인 사용 예
- GetMapping : Data를 조회할 때
- PostMapping : Data를 생성할 때
- PutMapping : Data를 수정할 때
- DeleteMapping : Data를 삭제할 때

@PutMapping (Update)
Test는 일반적인 브라우저에서는 할 수 없고, RestAPI Client 프로그램(ex. postman)을 통해 사용합니다.

*RestAPI
REST API 설계 시 가장 중요한 항목은 다음의 2가지로 요약할 수 있습니다.
첫 번째, URI는 정보의 자원을 표현해야 한다.
두 번째, 자원에 대한 행위는 HTTP Method(GET, POST, PUT, DELETE)로 표현한다.
ex) Delete /member/1

 

@GetMapping("/user/{id}") //localhost:8080/user/id 
public UserProfile getUserProfile(@PathVariable("id") String mapId) {
 return userMap.get(mapId);
}
@GetMapping("/user/all")
public List<UserProfile> getUserProfileList() {
 return new ArrayList<UserProfile>(userMap.values());
}

Postman 프로그램으로 put 테스트를 해보겠습니다.

<실행 결과>


@PostMapping (Insert)

@PostMapping("/user/{id}") 
public void postUserProfile(@RequestParam("id") String id, 
	@RequestParam("name") String name, 
	@RequestParam("phone") String phone, 
	@RequestParam("address") String address) 
{
	UserProfile userProfile = userMap.get(id); 
	userProfile.setName(name); 
	userProfile.setPhone(phone); 
	userProfile.setAddress(address); 
}


@DeletMapping

@DeleteMapping("/user/{id}") 
public void deleteUserProfile(@PathVariable("id") String id) { 
	userMap.remove(id); 
}

<실행 결과> -
* DB 저장하는 게 없고 서버를 재실행했기 때문에 코드가 재실행되어 위 push/post에서 추가한 id 4번 data는 없습니다.

 

Source : https://github.com/kakarooJ/Test_SpringBoot

 

GitHub - kakarooJ/Test_SpringBoot

Contribute to kakarooJ/Test_SpringBoot development by creating an account on GitHub.

github.com

 

반응형

'Web' 카테고리의 다른 글

3. Spring Boot - MyBatis  (0) 2022.02.03
2. Spring Boot - MySQL/MyBatis 연동  (0) 2022.02.03
JSP parameter 처리  (0) 2022.02.02
Front Controller Pattern  (0) 2022.02.01
Filter / Cookie / Session (공사중..)  (0) 2022.02.01