어제 연습한 코드 수정
이전에 작성한 코드는 post를 한 뒤 user/all 이 아닌 user/{id}로 조회를 할 경우 값이 나오지 않음.
url 설계가 잘못 되었다는 피드백을 받고
url에서 데이터를 다 받게 하지 않고 body에서 json 형태로 데이터를 주고 받는 형식으로 수정함
RESTful API uri 설계에 대해서도 알아봐야겠다.
body에서 json 데이터가 올 경우 이를 내가 원하는 타입으로 역직렬화 해야하는데
jackson이라는 라이브러리가 제공하는 ObjectMapper 기능이 필요함
라이브러리를 설치하려면 버전을 잘 맞춰야 제대로 동작하는데
여기서 자신의 sts 버전에 맞는 Dependency 버전을 찾아서 설치해야한다.
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 형태로 고쳐야한다.
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를 설치하면 서버를 껐다 켰다 안해도 됨
'Web > Spring' 카테고리의 다른 글
Spring boot REST API, H2 DB(sql), JPA (1) + Entity, Lombok 생성자 에러 (0) | 2020.09.21 |
---|---|
Spring boot REST API + MySQL(오라클, mybatis xml 작성) (0) | 2020.09.20 |
Spring boot REST API + MySQL(오라클, mybatis) (0) | 2020.09.18 |
Spring boot - RESTful API(1) (0) | 2020.09.16 |
spring framework 설치 및 환경설정 (spring legacy project/tomcat) (0) | 2020.09.16 |