MVC Architecture (Model-View-Controller)
MVC (Model-View-Controller) is a software architectural pattern commonly used in web and application development. It separates concerns into three interconnected components, improving code organization and maintainability.
Model (M)
Represents the data and business logic.
Manages database interactions, computations, and rules.
Example: A User class that retrieves and updates user data in a database.
View (V)
Handles UI/UX and presentation logic.
Displays data from the Model and takes user input.
Example: A webpage that displays user information.
Controller (C)
Manages user input and updates Model/View accordingly.
Acts as an intermediary between Model and View.
Example: A UserController that fetches user data and passes it to the view.
How MVC Works
User interacts with the View (e.g., clicking a button).
Controller processes input and requests data from the Model.
Model retrieves or updates data and sends it back.
Controller updates the View with the new data.
Benefits of MVC
✅ Separation of Concerns – Each component has a clear responsibility.
✅ Code Reusability – UI and business logic remain independent.
✅ Scalability – Easier to manage and extend.
✅ Unit Testing Friendly – Testing becomes more structured.
@Controller
Used in traditional MVC applications.
Returns view templates (like Thymeleaf, JSP).
Must use @ResponseBody to return raw data.
When to Use @RequestMapping?
When you need flexibility (supports multiple HTTP methods).
For class-level mappings (e.g., @RequestMapping("/users")).
When to Use @GetMapping?
✔ When handling GET requests.
✔ When fetching data (like users, products, etc.).
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/home")
public class Homepagecontroller {
@GetMapping("/display")
public String display_home_page() {
System.out.println("welcome to spring");
return "index.html";
}
@GetMapping("/test")
public void test_home_page() {
System.out.println("welcome to spring");
}
}