[SPRING] 데이터를 Client에 반환

야부엉·2023년 11월 2일
0

SPRING

목록 보기
9/45

1. 최근 트렌드

  • 프론트 엔드와 백엔드 간의 느슨하게 결합하는 방식이 최근에 더 채택이 많이 된다.
  • 초기 요청에 프론트엔드가 html을 response하고, 그 이후 ajax 방식으로 JSON 형태로 데이터를 반환한다.

Ajax

  • 브라우저가 가지고 있는 XMLHttpRequest 객체를 이용해서 전체 페이지를 새로 고치지 않고 페이지의 일부만을 로드하는 기법
  • 비동기 통신이며, 클라이언트와 서버간에 XML 데이터를 주고받는 기술
  • 즉, 최근에 XML 대신 JSON의 형태로 데이터만 주고 받으면서 필요 부분만 새롭게 갱신하는 기법.

2. JSON 데이터 반환하는 방법

1. @ResponseBody

  • SpringBoot에서는 타임리프 설정으로 인해 Default로 String 반환시 templates 폴데 .html 반환 -> 메서드에 @ResponseBody 설정 함으로써 데이터만 반환
import lombok.Getter;

@Getter
public class Star {
    String name;
    int age;

    public Star(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Star() {}
}


@Controller
@RequestMapping("/response")
public class responseController {
    // json 형태는 자바에 존재하지 않는다.
    // json 형태로 생긴 String 타입으로 반환한다.
    // Content-type(HTTP로 요청할때 데이터 타입도 알려준다) : text/html
    // Response body
    // {"name": "Robbie", "age" : 95}
    @GetMapping("/json/string")
    @ResponseBody
    public String helloStringJson() {
        return "{\"name\":\"Robbie\",\"age\":95}";
    }

    // Response Header
    // Content Type : application/json
    // Response Body
    // {"name": "Robbie", "age" : 95}
    // Spring 내부적으로 자바의 객체를 json형태로 변환한다.
    // Star 클래스의 필드 이름을 json의 key로 담겨 있는 데이터를 value로 반환한다.
    @GetMapping("/json/class")
    @ResponseBody
    public Star helloClassJson(){
        return new Star("Robbie",95);
    }

2. @RestController

  • @RestController = @Controller + @ResponseBody
//@rsponsebody를 따로 안달아도 해당 클래스의 메서드는 자동으로 다 적용된다.
@RestController
@RequestMapping("/response/rest")
public class ResponseRestController {
    // [Response header]
    //   Content-Type: text/html
    // [Response body]
    //   {"name":"Robbie","age":95}
    @GetMapping("/json/string")
    public String helloStringJson() {
        return "{\"name\":\"Robbie\",\"age\":95}";
    }

    // [Response header]
    //   Content-Type: application/json
    // [Response body]
    //   {"name":"Robbie","age":95}
    @GetMapping("/json/class")
    public Star helloClassJson() {
        return new Star("Robbie", 95);
    }
}

출처

Spring Master 강의
Ajax 정리

profile
밤낮없는개발자

0개의 댓글