SPRING/WEBSERVICE

[Restuful 학습] - PostMapping 설명 및 예제

JUMP개발자 2020. 8. 3. 21:47
package com.example.demo.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Service;

@Service
public class UserDaoService {

	private static List<User> users = new ArrayList<>();
	private static int usersCount =3;
	
	static {
		
		users.add(new User(1, "bins1",new Date(),"pass1","701010-1111111"));
		users.add(new User(2, "bins2",new Date(),"pass2","801010-1111111"));
		users.add(new User(3, "bins3",new Date(),"pass3","901010-1111111"));
	}
	
	public User save(User user) {
		if(user.getId() == null) {
			user.setId(++ usersCount);
		}
		users.add(user);
		return user; 
	}
	
}
​
package com.example.demo.user;

import java.net.URI;
import java.util.List;

import org.springframework.http.ResponseEntity;
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.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;

@RestController
public class UserController {

	private UserDaoService service;
	
	public UserController(UserDaoService service) {
		this.service = service;
	}
	
	@PostMapping("/users")
	public ResponseEntity<User> createUser(@Valid @RequestBody User user) {

		User savedUser = service.save(user);

		URI location = ServletUriComponentsBuilder.fromCurrentRequest()
		.path("/{id}")
		.buildAndExpand(savedUser.getId())
		.toUri();
		
		return ResponseEntity.created(location).build();
	}
	
}

 

위 소스는 새로운 User를 생성할 때 호출하는 createUser 메서드 로직이다.

@PostMapping을 사용하여, POST방식 통신으로 Request가 왔을 때 메서드가 수행된다.

 

URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedUser.getId())
.toUri();

의 location은 로컬에서 실행시 아래와 같이 찍힌다.

location -> http://localhost:8080/users/5 

 

ResponseEntity는 Http 응답에 대한 정보를 갖고 있는 객체이다.

.created를 통하여 201번 응답을 내려준다.