tech.

Spring Interview Prep 02

Created on

About Spring MVC

Spring MVC (Model-View-Controller) is a framework within the Spring Framework that is used for building web applications. It follows the MVC design pattern, which separates an application into three interconnected components:

Model

Represents the application's data or business logic.

Responsible for retrieving, processing, and storing data.

Example: A database entity or a service class.

View

Represents the presentation layer or the user interface.

Displays data to the user and captures user input.

Example: JSP, Thymeleaf, or any other templating engine.

Controller

Acts as an intermediary between the Model and the View.

Handles user input, processes it (often using the Model), and determines what to display in the View.

Example: A Spring MVC controller annotated with @Controller or @RestController.

Key Features of Spring MVC

DispatcherServlet

The central component in Spring MVC, it handles all incoming HTTP requests and dispatches them to the appropriate handlers (controllers).

Annotations

Uses annotations like @Controller, @RequestMapping, @GetMapping, and @PostMapping to simplify routing and request handling.

View Resolvers

Configures how views are resolved (e.g., JSP, Thymeleaf, etc.).

Data Binding and Validation

Maps HTTP request parameters to objects and validates input using annotations like @Valid.

Exception Handling

Centralized error handling with @ControllerAdvice and @ExceptionHandler.

Flexible Configuration

Can be configured with XML or Java-based annotations.

Example Workflow:

  1. A user sends a request to the application (e.g., GET /users).
  2. The DispatcherServlet receives the request.
  3. The request is routed to a Controller based on mappings.
  4. The Controller processes the request, interacts with the Model (e.g., fetches data from the database), and returns a response.
  5. The response is rendered by a View and sent back to the user.

Example Code:

Controller:

@Controller
public class UserController {

    @GetMapping("/users")
    public String getUsers(Model model) {
        List<String> users = List.of("Alice", "Bob", "Charlie");
        model.addAttribute("users", users);
        return "userList"; // View name
    }
}

View (Thymeleaf):

<!DOCTYPE html>
<html>
<body>
<h1>Users</h1>
<ul>
    <li th:each="user : ${users}">${user}</li>
</ul>
</body>
</html>

Spring MVC is widely used for building scalable, maintainable, and testable web applications. It integrates seamlessly with other Spring projects, such as Spring Security, Spring Data, and Spring Boot.