Web/Spring

Spring boot - RESTful API(2)

dev_sr 2020. 9. 17. 17:03

어제 연습한 코드 수정

이전에 작성한 코드는 post를 한 뒤 user/all 이 아닌 user/{id}로 조회를 할 경우 값이 나오지 않음.

 

url 설계가 잘못 되었다는 피드백을 받고

url에서 데이터를 다 받게 하지 않고 body에서 json 형태로 데이터를 주고 받는 형식으로 수정함

RESTful API uri 설계에 대해서도 알아봐야겠다.

 

body에서 json 데이터가 올 경우 이를 내가 원하는 타입으로 역직렬화 해야하는데 

jackson이라는 라이브러리가 제공하는 ObjectMapper 기능이 필요함

 

Getting Started with Deserialization in Jackson | Baeldung

Use Jackson to map custom JSON to any java entity graph with full control over the deserialization process.

www.baeldung.com

 

 

Convert a Map<string, string=""> to a POJO</string,>

I've been looking at Jackson, but is seems I would have to convert the Map to JSON, and then the resulting JSON to the POJO. Is there a way to convert a Map directly to a POJO?

stackoverflow.com

 

라이브러리를 설치하려면 버전을 잘 맞춰야 제대로 동작하는데

여기서 자신의 sts 버전에 맞는 Dependency 버전을 찾아서 설치해야한다.

 

Dependency versions

The following table provides details of all of the dependency versions that are provided by Spring Boot in its CLI (Command Line Interface), Maven dependency management, and Gradle plugin. When you declare a dependency on one of these artifacts without dec

docs.spring.io

 

 

Maven Repository: com.fasterxml.jackson.core » jackson-core

Core Jackson processing abstractions (aka Streaming API), implementation for JSON VersionRepositoryUsagesDate2.11.x2.11.2Central193Aug, 20202.11.1Central299Jun, 20202.11.0Central373Apr, 20202.11.0.rc1Central33Mar, 20202.10.x2.10.5Central57Jul, 20202.10.4Ce

mvnrepository.com

 

pom.xml에 dependency를 복사해서 넣어주면 jackson 라이브러리가 다운된다.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.3.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.Study</groupId>
	<artifactId>Study01</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Study01</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.11.2</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

 

 

package com.Study.Study01.controller;

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

import javax.annotation.PostConstruct;

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

import com.Study.Study01.model.UserProfile;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class UserController {

	private Map<String, UserProfile> userMap;
	
	@PostConstruct
	public void init() {
		userMap = new HashMap<String, UserProfile>();
	}
	
	@GetMapping("/user/{id}")
	public UserProfile getUserProfile(@PathVariable("id") String id) {
		System.out.println(id);
		return userMap.get(id);
	}
	
	
	@GetMapping("/user/all")
	public List<UserProfile> getAllUserProfile() {
		return new ArrayList<UserProfile>(userMap.values());
	}
	
	@ResponseBody
	@PostMapping("/user")
	public String addUserProfile(@RequestBody HashMap<String, Object> map) {
		ObjectMapper objectMapper = new ObjectMapper();
		UserProfile profile = objectMapper.convertValue(map, UserProfile.class);

		userMap.put(profile.id,profile);
		
		return "생성완료";
	}
	
	@PutMapping("/user/")
	public String updateUserProfile(@RequestBody HashMap<String, Object> map) {
		ObjectMapper objectMapper = new ObjectMapper();
		UserProfile profile = objectMapper.convertValue(map, UserProfile.class);
		UserProfile userProfile = userMap.get(profile.id);	
		
		userProfile.id=profile.id;
		userProfile.name = profile.name;
		userProfile.phone = profile.phone;
		userProfile.address=profile.address;
		
		return "갱신 완료";
	}
	
	@DeleteMapping("/user/")
	public String deleteUserProfile(@RequestBody HashMap<String, Object> map) {
		ObjectMapper objectMapper = new ObjectMapper();
		UserProfile profile = objectMapper.convertValue(map, UserProfile.class);
		UserProfile userProfile = userMap.get(profile.id);	
		userMap.remove(userProfile.id);
		return "삭제 완료";
	}
	
}

 

Jackson 라이브러리를 사용하기 위해서는 매핑되는 클래스를 pojo 형태로 고쳐야한다.

 

Java Json library jackson 사용법

2.7 버전부터는 JDK 7 이상이 필요하며 JDK6 을 지원하는 마지막 버전은 2.6.7.1 임

www.lesstif.com

package com.Study.Study01.model;

public class UserProfile {
	public String id;
	public String name;
	public String phone;
	public String address;
	

}

 

POST

id 1에 해당하는 json 내용을 넣고 포스트 하는 경우

 

GET

user/all로 get할 경우

 

POST->GET

id 2에 해당하는 데이터를 하나 더 추가

 

PUT->GET

id 1 데이터를 수정함

 

DELETE->GET

id 2번을 삭제

 

 

*새 프로젝트를 만들 때는 체크한 세 개를 설치해준다 

Spring Boot DevTools를 설치하면 서버를 껐다 켰다 안해도 됨

start.spring.io/