@Controller
, @RestController
모두 Spring 컨트롤러 지정 어노테이션.
클라이언트 HTTP요청에 대한 HTTP 응답에 포함되는 Response Body 생성 방식에 따른 차이가 있다.
@Controller
@Controller
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/products")
public String productsPage(Model model) {
var products = productService.getAllProducts();
model.addAttribute("products", products);
return "product-list";
}
}
@Controller 어노테이션을 통해 Spring MVC를 구현하는 경우,
view를 전달하게 된다.
@ResponseBody
@Controller
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/products")
public @ReponseBody Product productsPage(Model model) {
return ResponseEntity.ok(productService.getAllProducts());
}
}
@RestController
@RestController
public class ProductRestController {
private final ProductService productService;
public ProductRestController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/api/v1/products")
public List<Product> productList(@RequestParam Optional<Category> category) {
return category
.map(productService::getProductsByCategory)
.orElse(productService.getAllProducts());
}
}