[SpringBoot + JPA] API 호출 시, 404 에러

     

    개발 환경

    Vue + Spring Boot + JPA

    (API 테스트 툴 : Postman)

     

    문제 상황

    다음과 같이 api 호출시 404 에러가 리턴된다. 

    DB에는 정상적으로 insert됨 

     

    해결 방법

    Controller에 선언되어 있던 @Controller를 @RestController로 변경한다.

     

    이건 그냥 궁금해서 테스트 해봤다.

    @Controller + @ResponseBody를 사용해도 data는 insert되나, 확인해보니 Spring 4.x에서는 메서드 레벨에서 @ResponseBody를 사용하는 것이 아닌 클래스 레벨에서 @RestController 사용해야한다고 한다. 

    더보기
    When interacting with the REST API in Spring 4.x, we should use @RestController on a class level rather than @ResponseBody on a method level.

     

    @RestController is a constructed annotation with @Controller and @ResponseBody that is itself a meta-annotation.

    출처 

     

     

    원인 분석 스터디

    @RestController = @Controller + @ResponseBody이다. 따라서 REST API를 개발할 때 주로 사용한다.

    객체를 ResponseEntity로 감싸서 반환하기 때문에 동작 과정 역시 @Controller + @ResponseBody와 동일하다.

     

    @RequestBody와 @ResponseBody란?

    더보기
      @RequestBody @ResponseBody
    사용 목적 스프링 프레임워크에서 비동기 통신(=API 통신을 구현하기 위해) 사용 
    변환 대상 json 기반의 HTTP Body 자바 객체로 변환
    (json -> 자바 객체) 
    자바 객체를 json 기반의 HTTP Body 변환
    (자바 객체 -> json)
    진행 방향 클라이언트 -> 서버 서버 -> 클라이언트

     

     

    That's all about how to use Spring @RequestBody and @ResponseBody annotations in Java and Spring MVC. These annotations are crucial when using Spring and Spring Boot to develop our REST API. You can use them for parsing request data into your domain object as well as converting your domain object to HTTP response in the format your client wants like JSON, XML or TEXT. If you use @RestContorller which you should then you don't need to explicitly use @RequestBody and @ResponseBody, its already taken care. 

     

     

    실행 화면

    API 호출 시 정상적으로 return 됨

     

    Reference

    https://javarevisited.blogspot.com/2022/08/how-to-use-requestbody-and-responsebody.html#axzz7pcmIauU7

     

    How to use @RequestBody and @ResponseBody Annotations in Spring? Example Tutorial

    A blog about Java, Programming, Algorithms, Data Structure, SQL, Linux, Database, Interview questions, and my personal experience.

    javarevisited.blogspot.com

    https://mangkyu.tistory.com/49

     

    [Spring] @Controller와 @RestController 차이

    Spring에서 컨트롤러를 지정해주기 위한 어노테이션은 @Controller와 @RestController가 있습니다. 전통적인 Spring MVC의 컨트롤러인 @Controller와 Restuful 웹서비스의 컨트롤러인 @RestController의 주요한 차이점

    mangkyu.tistory.com

    https://velog.io/@nomonday/Spring-RequestBody-ResponseBody-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0

     

    [Spring] @RequestBody, @ResponseBody 이해하기

    스프링 프레임워크에서 비동기 통신, 즉 API 통신을 구현하기 위해 @RequestBody와 @ResponseBody 어노테이션을 사용한다.클라이언트 -> 서버 요청 : @RequestBody서버 -> 클라이언트 응답 : @ResponseBodyjson 기반

    velog.io

     

    728x90

    댓글