Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

JustDoEat

[어노테이션/스프링] @RestController, RESTful패턴 본문

카테고리 없음

[어노테이션/스프링] @RestController, RESTful패턴

kingmusung 2023. 11. 11. 22:54

정보대SW컨테스트를 하면서, @RestController를 처음 접해보게 되었는데 무엇인지 궁금해서 찾아보았다.

몽고DB가 JSON형태로 데이터를 넘겨주다 보니 거기에 알맞는게 RestController라고 하더라.

 

1. @RestController의 특징

 

   1-1.

      RestController 어노테이션을 사용하면 메서드의 반환값이 자동으로 JSON으로 변환되어 클라이언트로 전송된다.

let chat ={
    sender: username, //여기에 ""잘못 붙혀서 코드가 실행이 안됫음.
    roomNum: roomNum,
    msg: msginput.value
//몽고디비에 내가 받아오는 데이터 형태랑 일치하게 변수를 선언해야함.
};

//fetch(url, options); fetch원형이고 url은 요청을 보낼 대상, options는 내가 무엇을 요청할껀지에 대한설명
fetch("/chat2",{
    method:"post",//내가 지금 너한테 데이터를 보낼테니까 너는 데이터베이스에 데이터를 저장해
    body:JSON.stringify(chat), //자바스크립트 객체를 서버에 직접 전달이 안되서 JSON형태 타입으로 변환하라는뜻
    headers:{
        "Content-Type":"application/json; charset=utf-8"
    }
});

 

(채팅서비스 구현 JS파일 일부.)

 

@RestController
"
코드생략
"
@CrossOrigin//자바스크립트 요청 받는 어노테이션
@PostMapping("/chat2")
public Mono<Chat2> setMsg(@RequestBody Chat2 chat2){
    chat2.setCreatedAt(LocalDateTime.now());
    return chatRepository.save(chat2); //객체를 리턴하면 JSON으로 변환(MessageConverter가 함)
}

//리턴을 다시 JSON형태로 해줌

 

(채팅서비스 구현 컨트롤러 파일 중 일부)

 

   1-2

      리소스 중심(Resource-Centric):모든 자원(데이터 또는 서비스)은 고유한URI(Uniform Resource Identifier)

      가지 며, URI를 통해 해당 자원을 식별합니다.

const eventSource=new EventSource(`http://localhost:8080/chat2/roomNum/${roomNum}`);

(채팅서비스 JS파일 일부.)

 

  1-3

      RESTful 웹 서비스에서 자주 사용되는 형식 중 하나이며, 클라이언트와 서버 간의 데이터 교환에 효율적입니다

            → 모르는 상태에서 유튜브 강의를 보고 코드를 짰는데 에게 RESTful 패턴이라고 한다. 그후 Restful이 무엇인지 궁금해졌다.

 

 

 

2. Restful 이란?

         2-1.

            Representational State Transfer(표현 상태 전이)라고 한다.

         2-2.

            RESTfulRepresentational State Transfer(표현 상태 전이)의 약자로, 웹 개발에서 자주 사용되는 아키텍처 스타일 중 하나이다.

아래는 이렇게 짰던 코드가 RESTful방식이구나 하고 기록하는용.

package com.mysite.sbb.chattt;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.time.LocalDateTime;
import java.util.concurrent.Future;


@RequiredArgsConstructor
@RestController //데이터 리턴하는 서버가 되야함.
//@Controller
//@RequestMapping("/chattt")
public class Chat2Controller {

 
   private final Chat2Repository chatRepository;

    @Autowired
    private AsyncTaskExecutor taskExecutor; // TaskExecutor를 주입받습니다.

    @CrossOrigin
    @GetMapping(value = "/sender/{sender}/receiver/{receiver}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Async
    public Future<Flux<Chat2>> getMsgAsync(@PathVariable String sender, @PathVariable String receiver) {
        return new AsyncResult<>(chatRepository.mFindBySender(sender, receiver)
                .subscribeOn(Schedulers.fromExecutor(taskExecutor)));
    }
    @CrossOrigin
    @GetMapping(value = "/chat2/roomNum/{roomNum}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Async
    public Future<Flux<Chat2>> findByRoomNum(@PathVariable Integer roomNum) {

        return new AsyncResult<>(chatRepository.mFindByRoomNum(roomNum)
                .subscribeOn(Schedulers.boundedElastic()));
    }


    @CrossOrigin//자바스크립트 요청 받는 어노테이션
    @PostMapping("/chat2")
    public Mono<Chat2> setMsg(@RequestBody Chat2 chat2){
        chat2.setCreatedAt(LocalDateTime.now());
        //setCreatedAt은 주로 객체의 생성일을 설정하는데 사용되고, 간단한 예시는 this.setCreatedAt = LocalDateTime.now();
        return chatRepository.save(chat2); //객체를 리턴하면 JSON으로 변환(MessageConverter가 함)
    }
}

(채팅서비스의 컨트롤러)

 

 

결론:

RestController는 객체를 Json형태로 반환하는 기능에 최적화가 되어있고, 클라이언트와 서버와 데이터 교환에 최적화가 되어있다.

아직 javascrip도 재대로 배우지 않고 막 들이받으면서 하는거라 추후에 비슷한 내용을 한번 더 다룬다면 이해가 더 빨라질거같다.