[Springboot]스프링부트-Web layer살펴보기

Michelle Kim·2024년 12월 2일

Springboot-Java

목록 보기
12/20

Springboot

📚 오늘 공부한 강의

93강 스프링 부트 Web layer 좀 더 살펴보기

👉 수업 목차

  1. web layer 필수 개념
  2. Web layer 실습 구현
  3. Web layer 좀 더 알아보기

👉 한 줄 수업 목표

Web Layer 필수 개념 익히고, 직접 Web Layer 구현해보자.

🧡 수업내용

@RestController와 Dispatcher Servlet

DTO(Data Transfer Object)란

DTO: 여러 데이터들을 말아서 던지는 메시지 전달하는 편지 같은 클래스

실습: Spring WEB layer 구현하기

< 준비 >
마지막에 추가한 “super-coding” 프로젝트에서 시작한다.

< 실행 >
WEB layer 요구사항 7가지 (CRUD) 를 구현한다.

< 참고 >

현재 DB쪽은 연결되지 않아, Java 인메모리로 LIST 로 구현한다.

스프링 부트 직렬화 비밀

Jackson 라이브러리: DTO <-> Json 직렬화/역직렬화 하는 라이브러리

실습: Spring 직렬화/역직렬화 좀 더 살펴보기

< 준비 >
기존 “super-coding” 프로젝트에서 시작한다.

< 실행 >
Getter와 없어도 직렬화 동작되는지 확인한다.

🟠 [실습코드]

controller.ElectronicSotreController.java

@RestController
@RequestMapping("/api")
public class ElectronicStoreController {

    private static int serialItemId = 1;
    private List<Item> items = new ArrayList<>(Arrays.asList(
            new Item(String.valueOf(serialItemId++), "Apple Iphone", "Smart Phone", 149000, "A14 Bionic", "512GB"),
            new Item(String.valueOf(serialItemId++), "Samsung Galaxy", "Smart Phone", 209000, "Galaxy cpu", "1TB")
    ));

    @GetMapping("/items")
    public List<Item> findAllItem(){
        return items;
    }
    @PostMapping("items")
    public String registerItem(@RequestBody ItemBody itemBody){
        Item newItem = new Item(serialItemId++, itemBody);
        items.add(newItem);
        return "ID: " + newItem.getId();

    }
    @GetMapping("/items/{id}")
    public Item findItemById(@PathVariable String id) {
        Item itemFounded = items.stream()
                .filter((item -> item.getId().equals(id)))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("Item with id " + id + " not found"));

        return itemFounded;
    }

    @GetMapping("/items-query")
    public Item findItemByQueryId(@RequestParam("id") String id){
            Item itemFounded = items.stream()
                    .filter((item -> item.getId().equals(id)))
                    .findFirst()
                    .orElseThrow(() -> new RuntimeException("Item with id " + id + " not found"));

            return itemFounded;

    }

    @GetMapping("/items-queries")
    public List<Item> findItemByQueryIds(@RequestParam("id") List<String> ids){
        Set<String> idSet = ids.stream().collect(Collectors.toSet());

        List<Item> itemsFound = items.stream()
                .filter((item -> idSet.contains(item.getId())))
                .collect(Collectors.toList());

        return itemsFound;

    }

    @DeleteMapping("items/{id}")
    public String deleteItemByPathId(@PathVariable String id) {
        Item itemFounded = items.stream()
                .filter((item -> item.getId().equals(id)))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("Item with id " + id + " not found"));

        items.remove(itemFounded);

        return "Object with id= " + itemFounded.getId() + " has been deleted";
    }

    @PutMapping("/items/{id}")
    public Item updateItem(@PathVariable String id, @RequestBody ItemBody itemBody){
        Item itemFounded = items.stream()
                .filter((item -> item.getId().equals(id)))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("Item with id " + id + " not found"));

        items.remove(itemFounded);

        Item itemUpdated = new Item(Integer.valueOf(id), itemBody);
        items.add(itemUpdated);

        return itemUpdated;
    }

}

dto/Item.java

public class Item {
    private String id;
    private String name;
    private String type;
    private Integer price;
    private Spec spec;

    public Item() {

    }
    public Item(Integer id, ItemBody itemBody){
        this.id = String.valueOf(id);
        this.name = itemBody.getName();
        this.type = itemBody.getType();
        this.price = itemBody.getPrice();
        this.spec = itemBody.getSpec();
    }

    public Item(String id, String name, String type, Integer price, String cpu, String capacity) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.price = price;
        this.spec = new Spec(cpu, capacity);
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getType() {
        return type;
    }

    public Integer getPrice() {
        return price;
    }

    public Spec getSpec() {
        return spec;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Item item)) return false;
        return Objects.equals(id, item.id);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id);
    }
}

dto/ItemBody.java

public class ItemBody {
    private String name;
    private String type;
    private Integer price;
    private Spec spec;

    public ItemBody() {
    }

    public String getName() {
        return name;
    }

    public String getType() {
        return type;
    }

    public Integer getPrice() {
        return price;
    }

    public Spec getSpec() {
        return spec;
    }
}

dto/Spec.java

public class Spec {
    private String cpu;
    private String capacity;

    public Spec() {
    }

    public Spec(String cpu, String capacity) {
        this.cpu = cpu;
        this.capacity = capacity;
    }

    public String getCpu() {
        return cpu;
    }

    public String getCapacity() {
        return capacity;
    }
}
profile
🇬🇧영국대학교)Computer Science학과 졸업 📚Data, AI, Backend 분야에 관심이 많습니다. 👉Email: kimbg9876@gmail.com

0개의 댓글