SPRING/WEBSERVICE
[Restuful 학습] - GetMapping 설명 및 예제
JUMP개발자
2020. 8. 1. 14:16
@GetMapping : @RequestMapping(method = RequestMethod.GET) 의 축약형
주로 데이터를 조회할 때 사용된다.
만약 같은 URL이여도 POST로 요청이 오면 다른 메서드(@PostMapping으로 매핑된 메서드)를
타게 된다.
아래 예제는 등록되어 있는 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;
}
@GetMapping("/users")
public List<User> retrieveAllUsers() {
return service.findAll();
}
// GET /users/1 or /users/10 -> String
@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id) {
User user =service.findOne(id);
if (user == null) {
throw new UserNotFoundException(String.format("ID[%s] not found", id));
}
return user;
}
}
소스는 UserDaoService로 User 데이터를 가져오는 findAll, finsOne 메서드가 정의되어있다.
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 List<User> findAll() {
return users;
}
public User findOne(int id) {
for (User user : users) {
if (user.getId() == id) {
return user;
}
}
return null;
}
}
아래는 UserVO 임.
lombok을 사용하였기 때문에 별도로 Getter, Setter 를 선언할 필요가 없다.
package com.example.demo.user;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
@Size(min=2, message ="Name은 2글자 이상 입력해 주세요.")
private String name;
@Past
private Date joinDate;
//@JsonIgnore
private String password;
// @JsonIgnore
private String ssn;
}
결과 :