@Controller

๐Ÿ“Œ @Controller : Client์˜ Request๋ฅผ ์ฒ˜๋ฆฌํ•œ ํ›„ โ†’ ์ •ํ•ด์ง„ View์— ๊ฐ์ฒด๋ฅผ ๋„˜๊ฒจ์คŒ

  • Client์˜ Request๊ฐ€ ์ง„์ž…ํ•˜๋Š” ์‹œ์  (entry point)

  • Request์— ๋”ฐ๋ผ ์–ด๋–ค ์ฒ˜๋ฆฌ๋ฅผ ํ•  ์ง€ ๊ฒฐ์ • โ†’ ์‹ค์งˆ์  ์ฒ˜๋ฆฌ๋Š” @Service์— ๋„˜๊ฒจ์„œ ์ฒ˜๋ฆฌํ•จ

  • ์‚ฌ์šฉ์ž์—๊ฒŒ View(or View์— Model์„ ์ ์šฉํ•œ ๊ฒƒ) โ†’ Response๋กœ ๋ณด๋‚ด์คŒ

  • ๋Œ€๊ทœ๋ชจ์„œ๋น„์Šค์—์„œ ํ•˜๋‚˜์˜ ํด๋ž˜์Šค๊ฐ€ ๋ชฐ์•„์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ โ›”๏ธ
    Controller๋ผ๋Š” ์ค‘๊ฐ„์ œ์–ด์ž ์—ญํ•  โ†’ A ์š”์ฒญ์€ A Controller๊ฐ€ ๋งก์•„ ๋กœ์ง์„ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ํ•จ โญ๏ธ

  • MVC ํŒจํ„ด (Model - View - Controller) ์ค€์ˆ˜ โœ…

๐Ÿ“ Client์˜ Get Request์— ๋Œ€ํ•ด ์ฒ˜๋ฆฌ ํ›„, View๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•จ

@Controller
public class ControllerPrac {
	@GetMapping("/home") // home path๋กœ Get ์š”์ฒญ์ด ๋“ค์–ด์˜ค๋ฉด
    public String homepage() {
    	return "home.html"; // home.html ์ƒ์„ฑ (Response)
    }
}

@ResponseBody

๐Ÿ“Œ @ResponseBody : ํ•ด๋‹น ๋ฉ”์„œ๋“œ์˜ return ๊ฐ’ โ†’ HTTP response Body์— ๋„ฃ์–ด ๋ฐ˜ํ™˜ํ•จ

1๏ธโƒฃ @ResponseBody ์‚ฌ์šฉ โŒ, @Controller ์‚ฌ์šฉ ์‹œ

โžก๏ธ Controller๋Š” Client โ†’ View, Model ๋ณ„๋„๋กœ ๋ฐ˜ํ™˜ํ•จ

์ข…๋ฅ˜์˜๋ฏธ
View๋™์ ์ธ HTML
ModelView์— ์ ์šฉํ•  ์ •๋ณด

2๏ธโƒฃ @ResponseBody ์‚ฌ์šฉ โœ…, @Controller ์‚ฌ์šฉ ์‹œ

  • ๋ฐฑ์—”๋“œ๋งŒ ๋”ฐ๋กœ ๊ฐœ๋ฐœํ•˜๋Š” ๊ฒฝ์šฐ, View๋ฅผ Client(ํ”„๋ก ํŠธ)์ชฝ์œผ๋กœ ๋ณด๋‚ผํ•„์š” โŒ
    โžก๏ธ '๋ฐ์ดํ„ฐ๋งŒ' Client์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋ณด๋‚ด์ฃผ๋ฉด ๋จ

  • โ‘  Response Body์— Controller์—์„œ ๋ฐ˜ํ™˜ํ–ˆ๋˜ ๊ฐ์ฒด โ†’ JSON ํ˜•ํƒœ๋กœ ๋“ค์–ด๊ฐ
    โžก๏ธ View ๋Œ€์‹ , JSON ํ˜•ํƒœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•จ

  • โ‘ก Client์—์„œ JSON ํ˜•ํƒœ๋กœ ๋ฐ›์€ ๋ฐ์ดํ„ฐ๋ฅผ ํ™œ์šฉ

๐Ÿ“ JSON์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ฃผ๊ณ ๋ฐ›์Œ์„ ์„ ์–ธ

@RestController
public class ProductRestController {
	private final ProductService productService;
    private final ProductRepository productRepository;
    
    // ๋“ฑ๋ก๋œ ์ „์ฒด ์ƒํ’ˆ ๋ชฉ๋ก ์กฐํšŒ
    @GetMapping("/api/products")
    public List<Product> getProducts() {
    	return productRepository.findAll();
    }
}

@RestController

๐Ÿ“Œ @RestController : @Controller + @ResponseBody

  • View ๋Œ€์‹  JSON ํ˜•ํƒœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ Client(ํ”„๋ก ํŠธ)์— ๋ฐ˜ํ™˜ํ•จ

  • ๋ฐ์ดํ„ฐ ์ž์ฒด๋ฅผ ์‘๋‹ต์œผ๋กœ ์ œ๊ณตํ•˜๋Š” RESTful API ๊ฐœ๋ฐœ ์‹œ ์ž์ฃผ ์‚ฌ์šฉ๋จ

    • Back - Front ; ๋Š์Šจํ•œ๊ฒฐํ•ฉ
  • ์ฆ‰, ๋ฐ์ดํ„ฐ(JSON)๋งŒ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋˜๋Š” Controller โ†’ @RestController ์‚ฌ์šฉ

profile
๐ŸฑSunyeon-Jeong, mallang developer๐Ÿฐ

1๊ฐœ์˜ ๋Œ“๊ธ€

comment-user-thumbnail
2023๋…„ 7์›” 19์ผ

์ •๋ง ์œ ์ตํ•œ ๊ธ€์ด์—ˆ์Šต๋‹ˆ๋‹ค.

๋‹ต๊ธ€ ๋‹ฌ๊ธฐ