fbpx

Spring MVC (Model-View-Controller)

Spring MVC is a powerful and flexible web framework provided by the Spring Framework for building robust and scalable Java web applications. It follows the Model-View-Controller (MVC) architectural pattern, which separates the concerns of an application into three main components: the Model (business logic and data), the View (presentation layer), and the Controller (handles user input and manages the flow of the application).

Key Components of Spring MVC:

1. Model:

The Model represents the business logic and data of the application. It is responsible for processing and managing data, as well as interacting with the database. In Spring MVC, the model is typically represented by Java objects (POJOs) or Spring beans.

2. View:

The View is responsible for presenting the data to the user. It generates the user interface and displays the information processed by the Model. Views can be implemented using technologies like JavaServer Pages (JSP), Thymeleaf, or FreeMarker in Spring MVC.

3. Controller:

The Controller handles user input, processes requests, and manages the flow of the application. It receives input from the user, interacts with the Model to process the data, and selects the appropriate View to render the result. Controllers are implemented as Java classes and are responsible for mapping URLs to specific methods.

Request Processing Lifecycle in Spring MVC:

User Sends Request:

  • The user interacts with the web application by sending an HTTP request to a specific URL.

DispatcherServlet Receives Request:

  • The central component, DispatcherServlet, receives the incoming request.

Handler Mapping:

  • The DispatcherServlet consults the configured HandlerMapping to determine which controller should handle the request based on the URL.

Controller Handles Request:

  • The selected controller processes the request and invokes the appropriate business logic in the Model.

Model Processing:

  • The Model processes the data, performs any required operations, and prepares the data to be displayed.

View Resolution:

  • The Controller selects the appropriate View based on the logical view name returned by the handler method.

Render View:

  • The View is rendered, and the final HTML response is generated.

DispatcherServlet Sends Response:

  • The DispatcherServlet sends the HTML response back to the user’s browser.

Key Components and Annotations in Spring MVC:

1. Controller:

  • Controllers handle user requests and are annotated with @Controller.
  • Request mappings are specified using @RequestMapping.
@Controller
@RequestMapping("/products")
public class ProductController {

    @GetMapping("/list")
    public String listProducts(Model model) {
        // Business logic to retrieve and process product data
        return "productList"; // View name
    }
}

2. Model:

  • The Model is represented by the Model interface or ModelMap class.
  • Data is added to the model using the addAttribute method.
@GetMapping("/details")
public String showProductDetails(@RequestParam("id") Long productId, Model model) {
    // Business logic to retrieve product details by ID
    Product product = productService.getProductById(productId);

    // Add product to the model
    model.addAttribute("product", product);

    return "productDetails"; // View name
}

3. View:

  • Views are typically implemented using technologies like JSP, Thymeleaf, or FreeMarker.
  • The logical view name is returned by the controller method.
// JSP View example
@RequestMapping("/details")
public String showProductDetails(@RequestParam("id") Long productId, Model model) {
    // Business logic to retrieve product details by ID
    Product product = productService.getProductById(productId);

    // Add product to the model
    model.addAttribute("product", product);

    return "productDetails"; // View name
}

4. DispatcherServlet:

  • The DispatcherServlet is the front controller that receives and manages incoming requests.
<!-- web.xml configuration for DispatcherServlet -->
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

5. RequestMapping:

  • The @RequestMapping annotation is used to map URLs to controller methods.
  • It can be applied at the class level and method level.
@Controller
@RequestMapping("/products")
public class ProductController {

    @GetMapping("/list")
    public String listProducts(Model model) {
        // Business logic to retrieve and process product data
        return "productList"; // View name
    }
}

Configuring Spring MVC:

1. XML Configuration:

  • Configure the DispatcherServlet and application context in a web.xml file.

“`xml

dispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/spring-mvc.xml 1


dispatcher