package com.std.sbb;
import lombok.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
/*
* 요청 : http://localhost:8080/person/add?name=홍길동&age=11
응답 : 1번 사람이 추가되었습니다.
요청 : http://localhost:8080/person/add?name=홍길순&age=22
응답 : 2번 사람이 추가되었습니다.
요청 : http://localhost:8080/person/add?name=임꺽정&age=33
응답 : 3번 사람이 추가되었습니다.
요청 : http://localhost:8080/person/people
응답
* */
@Controller // SpringBoot request/response 첫 시작점임을 알리는 곳
public class PersonController {
int lastId;
List<Person> people;
PersonController() {
lastId = 0; // person에 고유 ID를 부여하기 위한 일종의 COUNTER 선언
people = new ArrayList<>(); // 등록되는 사람들을 저장하기 위한 리스트
}
@GetMapping("/person/add") // 웹의 요청 처리
@ResponseBody
public String addPerson( // URL 파라미터로 name, age를 받아서 새로운 Person 객체를 생성
@RequestParam("name") String name,
@RequestParam("age") int age) {
lastId++;
// Person p = new Person(lastId, name, age);// error
Person p = new Person(lastId, age, name);// 사람의 정보를 담는 클래스 모델을 호출
// Person 클래스의 생성자 순서를 지켜야 함 (id, age, name)
people.add(p); // 웹 화면에서 서버로 Request 가 생길 때 마다 people 리스트에 추가됨
return String.format("%d번째 사람이 추가되었습니다.", p.getId());
}
@GetMapping("/person/people")
@ResponseBody
public List<Person>getPeople() { // 등록된 모든 사람 목록을 JSON 형태로 반환
// @ToString 덕분에 System.out.println(people) 출력 시 사람이 가진 값들이 잘 보임
System.out.println(people);
return people; // lombok @ToString이 적용됨
}
}
/*
@AllArgsConstructor //모든 필드를 받는 생성자 자동 등록
@Getter // 각 필드에 대한 getter/setter 자동 생성
@Setter
@ToString // - 객체를 출력할 때 주소값이 아닌 실제 필드 값을 보여줌 instance address info가 아닌 real value를 가져오기 위해
class Person { // 사람의 정보를 담는 데이터 모델 클래스
private int id;
private int age;
private String name;
}
*/
/*
// @AllArgsConstructor @Getter, @Setter 를 사용하지 않은 경우 직접 작성
// @ToString 관련 객체의 값을 반환할 때 instance address가 아닌 real value 를 반환하기 위해 적용
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// Getter methods
public int getId() { return id; }
public String getName() { return name; }
public int getAge() { return age; }
*/