🌱 1. MVC là gì?
MVC (Model – View – Controller)
Là một mô hình thiết kế chuẩn cho lập trình web, giúp tách riêng:
- Giao diện người dùng (View)
- Xử lý dữ liệu (Model)
- Điều phối luồng (Controller)
➡️ Tạo thành cấu trúc rõ ràng, dễ bảo trì.
🔍 2. Vai trò từng thành phần
Thành phần | Vai trò | Ứng dụng trong Spring Boot |
---|---|---|
💾 Model | Chứa dữ liệu, logic xử lý nghiệp vụ, liên kết database. | Entity + Repository. |
🎨 View | Hiển thị dữ liệu cho người dùng, giao diện frontend. | Thymeleaf, JSP hoặc React, Angular. |
🎮 Controller | Nhận yêu cầu từ người dùng, xử lý, gọi Model và trả về View. | Class @Controller + @RestController . |
📊 3. Sơ đồ Kiến trúc MVC
🔥 4. Quy trình hoạt động
1️⃣ Người dùng nhập URL / click nút → Trình duyệt gửi Request.
2️⃣ Controller nhận request → gọi đến Service / Repository.
3️⃣ Model giao tiếp với Database → trả dữ liệu cho Controller.
4️⃣ Controller trả dữ liệu qua View (file HTML).
5️⃣ View hiển thị thông tin → Trình duyệt nhận Response.
💻 5. Code Ví dụ
🏠 Model — Product.java
@Entity @Table(name="products") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private double price; }
🔗 Repository — ProductRepository.java
public interface ProductRepository extends JpaRepository<Product, Long> { }
🎮 Controller — ProductController.java
@Controller @RequestMapping("/products") public class ProductController { <pre><code>@Autowired private ProductRepository productRepository; @GetMapping public String listProducts(Model model) { model.addAttribute("products", productRepository.findAll()); return "product_list"; }</code></pre> }
🎨 View — product_list.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <h2>Danh sách sản phẩm</h2> <ul> <li th:each="p : ${products}" th:text="${p.name}"></li> </ul> </body> </html>
💡 6. Ưu điểm khi dùng MVC trong Spring Boot
Hỗ trợ nhiều View Engine: Thymeleaf, JSP, React, Angular…
Tách biệt rõ Giao diện – Logic – Điều khiển.
Dễ mở rộng, dễ bảo trì.
Code sạch và dễ hiểu.