Model-View-Controller(MVC) admin, March 1, 2025 MVC in Spring Boot (Spring MVC) Spring Boot follows the Model-View-Controller (MVC) design pattern, which helps in developing loosely coupled, maintainable, and scalable web applications. Spring MVC is a part of the Spring Framework that simplifies web development by providing powerful features like dependency injection, request handling, and view resolution. 1. Key Components of Spring MVC 1.1 Model The Model represents the business logic and data of the application. It interacts with the database and processes the data. Typically implemented using POJOs (Plain Old Java Objects), JPA Entities, or DTOs (Data Transfer Objects). Example: javaCopyEditpublic class User { private Long id; private String name; private String email; // Getters and Setters } 1.2 View The View is responsible for rendering the UI (User Interface). Spring MVC supports multiple view technologies like Thymeleaf, JSP, FreeMarker, and Mustache. Uses Spring’s ViewResolver to map logical view names to actual view files. Example (Thymeleaf Template): htmlCopyEdit<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Users</title> </head> <body> <h1>User List</h1> <ul> <li th:each="user : ${users}" th:text="${user.name}"></li> </ul> </body> </html> 1.3 Controller The Controller handles incoming HTTP requests, processes them, and returns a response. Uses @Controller or @RestController annotation. Example: javaCopyEditimport org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.util.List; @Controller public class UserController { @GetMapping("/users") public String getUsers(Model model) { List<String> users = List.of("Alice", "Bob", "Charlie"); model.addAttribute("users", users); return "user-list"; // Refers to user-list.html (Thymeleaf template) } } If using REST APIs, use @RestController: javaCopyEditimport org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api") public class UserRestController { @GetMapping("/users") public List<String> getUsers() { return List.of("Alice", "Bob", "Charlie"); } } 2. How Spring MVC Works? The DispatcherServlet receives the HTTP request. It forwards the request to the appropriate Controller. The Controller processes the request and interacts with the Model. The Model retrieves or manipulates data and returns it to the Controller. The Controller sends the data to the appropriate View. The ViewResolver resolves the view and generates the final HTML response. Diagram: pgsqlCopyEditClient → DispatcherServlet → Controller → Service → Repository → Database ↓ View Resolver → View 3. Important Spring MVC Annotations AnnotationDescription@ControllerDefines a Spring MVC controller (used for web pages).@RestControllerDefines a REST controller (returns JSON/XML instead of views).@RequestMappingMaps HTTP requests to handler methods.@GetMappingHandles HTTP GET requests.@PostMappingHandles HTTP POST requests.@PutMappingHandles HTTP PUT requests.@DeleteMappingHandles HTTP DELETE requests.@PathVariableExtracts values from URL path parameters.@RequestParamExtracts query parameters from URL.@ModelAttributeBinds form data to a model object.@ResponseBodyReturns response directly instead of a view.@ExceptionHandlerHandles exceptions globally in a controller. Example: javaCopyEdit@GetMapping("/users/{id}") public String getUser(@PathVariable Long id) { return "User ID: " + id; } 4. Spring Boot MVC Configuration Spring Boot simplifies MVC setup with Spring Boot Starter Web dependency. 4.1 Add Dependencies in pom.xml xmlCopyEdit<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> 5. Example: Complete Spring Boot MVC Application 5.1 Create a Spring Boot Application javaCopyEditimport org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MvcApplication { public static void main(String[] args) { SpringApplication.run(MvcApplication.class, args); } } 5.2 Create Model javaCopyEditpublic class User { private Long id; private String name; private String email; // Getters, Setters, Constructors } 5.3 Create Controller javaCopyEditimport org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.util.List; @Controller public class UserController { @GetMapping("/users") public String showUsers(Model model) { List<User> users = List.of( new User(1L, "Alice", "alice@example.com"), new User(2L, "Bob", "bob@example.com") ); model.addAttribute("users", users); return "user-list"; // Maps to user-list.html } } 5.4 Create View (src/main/resources/templates/user-list.html) htmlCopyEdit<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Users</title> </head> <body> <h1>User List</h1> <ul> <li th:each="user : ${users}"> <span th:text="${user.name}"></span> - <span th:text="${user.email}"></span> </li> </ul> </body> </html> 6. Running the Application Run the Spring Boot application. Open the browser and visit:http://localhost:8080/users It will display the list of users on the webpage. 7. REST API Example If building a REST API, modify the controller: javaCopyEdit@RestController @RequestMapping("/api") public class UserRestController { @GetMapping("/users") public List<User> getUsers() { return List.of( new User(1L, "Alice", "alice@example.com"), new User(2L, "Bob", "bob@example.com") ); } } Now, accessing http://localhost:8080/api/users returns JSON data: jsonCopyEdit[ {"id":1,"name":"Alice","email":"alice@example.com"}, {"id":2,"name":"Bob","email":"bob@example.com"} ] 8. Conclusion Spring Boot MVC provides a clean, scalable, and easy-to-use architecture for web applications. It follows the DispatcherServlet-based MVC pattern. Supports multiple view technologies (Thymeleaf, JSP). Simplifies REST API development using @RestController. Reduces boilerplate code with Spring Boot starters. Spring Boot