본문 바로가기
공부/Spring

Spring Rest API 만들기

by Luna_O 2020. 9. 17.

Rest API GET, POST, PUT, DELETE 등을 만들어 보았다

처음에는 Param으로 받아와서 했는데 Body Json으로 입력해서 넘겨 Object로 받아서 

변환하고 저장하는 걸로 바꿨다.

여기서 Json 사용하려면 Jackson이란 라이브러리를 추가해야 한다. (Jackson JSON 데이터 구조를 처리해주는 라이브러리)

STS4 버전을 사용중이고 Spring Dependency Versions 들어가서 Jackson 검색했더니 2.11.2 버전이 나왔다

mvnrepository 들어가서 Jackson 2.11.2 버전에 맞는 maven 복사해서 pom.xml <dependency>부분에 추가했다.

 

package com.example.demo.controller;

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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.UserProfile;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;

import javax.annotation.PostConstruct;

@RestController
public class UserProfileController {
	private Map<String, UserProfile> userMap;
	
	@PostConstruct
    public void init() {
		userMap = new HashMap<String, UserProfile>();
	}
	
	@GetMapping("/user/{id}")
	public UserProfile getUserProfile(@PathVariable("id") String id) {
		return userMap.get(id);
	}
	
	@GetMapping("/user/all")
	public List<UserProfile> getUserProfileAll(){
		return new ArrayList<UserProfile>(userMap.values());
	}
	
	@ResponseBody
	@PostMapping("/user")
	public void addUserProfile(@RequestBody HashMap<String, Object> map) {
		ObjectMapper objectMapper = new ObjectMapper();
		UserProfile profile = objectMapper.convertValue(map, UserProfile.class);
		userMap.put(profile.id, profile);
	}
	
	@ResponseBody
	@PutMapping("/user")
	public void updateUserProfile(@RequestBody HashMap<String, Object> map) {
		ObjectMapper objectMapper = new ObjectMapper();
		UserProfile profile = objectMapper.convertValue(map, UserProfile.class);
		UserProfile user = userMap.get(profile.id);
		user.name = profile.name;
		user.phone = profile.phone;
		user.address = profile.address;
	}
	
	@DeleteMapping("/user")
	public void deleteUserProfile(@RequestParam String id) {
		userMap.remove(id);
	}
}

'공부 > Spring' 카테고리의 다른 글

Spring boot 공부 시작  (0) 2020.09.16
STS(Spring Tool Suite) 설치 및 설정  (0) 2020.09.16