@Controller와 RestController의 차이점

이진섭·2022년 10월 24일
0

Spring_boot

목록 보기
4/16

Spring에서 @Controller와 @RestController의 차이점
1. @Controller는 클래스를 Spring MVC 컨트롤러로 표시하는데 사용되고,
@RestController는 RESTful 웹 서비스에서 사용되는 특수 컨트롤러이며 @Controller + @Response와 동일하다.

  1. @Controller와 @RestController의 주요 차이점 중 하나는 @RestController를 표시하면 모든 메소드가 뷰 대신 객체로 작성된다.

  2. @Controller는 @Component 주석이 달려있고, @RestController는 아래와 같이 @Controller와 @ResponseBody 주석이 달린 편의 컨트롤러이다.
    출처: https://dev-coco.tistory.com/84 [슬기로운 개발생활:티스토리]

@Controller
public class Controllerprac {
    @GetMapping("/home") //home으로 Get요청이들어오면
    public String homepage(){
        return "home.html"; //home.html생성
    }
}

@RestController // JSON으로 데이터를 주고받음을 선언합니다.
public class ProductRestController {

    private final ProductService productService;
    private final ProductRepository productRepository;

    // 등록된 전체 상품 목록 조회
    @GetMapping("/api/products")
    public List<Product> getProducts() {
        return productRepository.findAll();
    }
}
profile
하루하루성장하기

0개의 댓글