Web MVC in Spring Framework 

Web MVC in Spring Framework

In this article, I am going to discuss Web MVC in Spring Framework with Examples. Please read our previous article, where we discussed Spring Framework Declarative Transaction Management.

What is Web MVC in Spring Framework?

In Spring, the Web MVC (Model-View-Controller) framework is a part of the larger Spring Framework that provides a structured approach to building web applications. It follows the MVC architectural pattern, which separates an application into three main components: the Model, the View, and the Controller.

  • Model: The Model represents the data and business logic of the application. It typically consists of Java classes that encapsulate the application’s data and provide methods to access and manipulate it. In the context of Spring MVC, the Model objects are typically represented as POJOs (Plain Old Java Objects) or JavaBeans.
  • View: The View is responsible for rendering the user interface or presentation layer of the application. It is responsible for displaying the data to the user in a meaningful way. In the case of Spring MVC, the view is usually implemented using JSP (JavaServer Pages), Thymeleaf, or other templating technologies.
  • Controller: The Controller acts as an intermediary between the Model and the View. It receives the user’s requests, processes them, and determines the appropriate response. In Spring MVC, the Controller is implemented as a Java class that handles incoming requests, performs necessary processing, interacts with the Model to fetch or update data, and selects an appropriate View to render the response.

The flow of a typical Spring MVC application starts with the user’s request being intercepted by the DispatcherServlet, which acts as the front controller. The DispatcherServlet delegates the request to the appropriate Controller based on the URL mapping configuration. The Controller processes the request, invokes the necessary business logic by interacting with the Model, and then prepares the Model data to be displayed. Finally, the Controller selects an appropriate View and passes the Model data to it for rendering. The View then generates the HTML output, which is sent back to the user’s browser as the response.

The Spring Web MVC framework provides various features and components to simplify the development of web applications, including request mapping, form handling, data binding, validation, and more. It also promotes loose coupling and separation of concerns, making the application more modular, maintainable, and testable.

Benefits of Web MVC in Spring Framework
  • Separation of Concerns: The MVC pattern promotes a clear separation of concerns between different components of the application. The Model represents the data and business logic, the View handles the presentation, and the Controller manages the flow and interaction between the Model and View. This separation enhances code modularity, maintainability, and reusability.
  • Testability: The MVC pattern, when implemented correctly, makes it easier to write unit tests for individual components. The separation of concerns allows for independent testing of the Model, View, and Controller. Unit testing can help identify issues early in the development process and ensure that each component works as expected.
  • Reusability: With the MVC pattern, the Model and business logic are decoupled from the presentation layer (View and Controller). This separation enables reusing the business logic across multiple views and controllers. It also allows for different views to be used for different clients (e.g., web, mobile, API) without affecting the underlying business logic.
  • Flexibility: The Spring Web MVC framework provides flexibility in choosing the technologies for implementing views. Developers can use JSP, Thymeleaf, FreeMarker, or other view technologies based on their preferences or project requirements. This flexibility allows for easier integration with existing systems or the adoption of new technologies in the future.
  • Request Mapping: Spring MVC offers robust request mapping capabilities, allowing developers to define flexible URL patterns and map them to appropriate controllers. This feature simplifies the routing of requests to specific controllers and methods, making it easier to handle different types of requests (GET, POST, PUT, DELETE) and request parameters.
  • Validation and Data Binding: Spring MVC provides built-in support for data binding and validation. It simplifies the process of binding request parameters to objects and automatically performs validation based on predefined rules. This feature helps ensure data integrity and reduces the amount of boilerplate code required for handling form submissions.
  • Integration with other Spring features: Spring MVC seamlessly integrates with other Spring features, such as dependency injection (IoC), aspect-oriented programming (AOP), security, and transaction management. This integration allows developers to leverage the full power of the Spring ecosystem while building web applications.
Drawbacks of Web MVC in Spring Framework:
  • Complexity: While the MVC pattern itself promotes the separation of concerns, the implementation of a complex application using Spring MVC can become intricate. With multiple components (Models, Views, Controllers), it is important to properly manage the interactions and dependencies between them. Inexperienced developers may find it challenging to grasp the overall architecture and maintain a clean design.
  • Learning Curve: Spring MVC has a learning curve, especially for developers who are new to the Spring Framework. Understanding the framework’s concepts, configuration, and best practices may require some time and effort. However, once developers become familiar with Spring MVC, they can benefit from its power and productivity.
  • Overhead: The use of the MVC pattern introduces some overhead in terms of additional code and layers. The separation of concerns and the need to communicate between components can lead to increased complexity and potentially slower performance compared to simpler architectures. However, Spring’s optimizations and caching mechanisms mitigate these concerns to a large extent.
  • Configuration: Spring MVC requires configuration, typically in the form of XML or Java-based configuration files. While Spring Boot has made this process more streamlined with auto-configuration, complex application setups may still involve writing explicit configuration. Managing and maintaining these configuration files can become cumbersome, especially for larger projects.
  • Tight Coupling: If not designed properly, the Model, View, and Controller components in Spring MVC can become tightly coupled. This can make the codebase less flexible and harder to maintain. It is essential to follow best practices, such as using interfaces and dependency injection, to ensure loose coupling and modularity.
  • Lack of Convention: Unlike some other web frameworks, Spring MVC does not enforce strict conventions for naming or project structure. While this provides flexibility, it can lead to inconsistency across different projects and make it harder for new developers to navigate and understand the codebase.

In conclusion, the Web MVC framework in Spring offers numerous benefits, such as separation of concerns, testability, reusability, flexibility, and powerful features like request mapping and validation. However, developers should be aware of potential drawbacks, including increased complexity, learning curve, configuration overhead, tight coupling if not properly designed, and the need for explicit testing setups. With proper understanding and adherence to best practices, the advantages of Spring MVC can outweigh its limitations, resulting in well-structured, maintainable, and scalable web applications.

What is DispatcherServlet?

The DispatcherServlet is a key component of the Spring Web MVC framework. It follows a dispatching process to handle requests. It acts as the front controller for incoming web requests in a Spring MVC application. The primary responsibility of the DispatcherServlet is to receive requests, process them, and dispatch them to the appropriate handlers for further processing.

When a request is made to a Spring MVC application, it first goes through the DispatcherServlet. The DispatcherServlet examines the incoming request and determines the appropriate handler (controller) to handle the request based on the configuration specified in the application.

How DispatcherServlet Works?
  • Request Reception: The DispatcherServlet receives an incoming HTTP request from the client.
  • Handler Mapping: The DispatcherServlet consults the configured HandlerMapping(s) to determine the appropriate handler (controller) for the request. HandlerMapping(s) typically map URLs or other request attributes to specific controllers.
  • Handler Execution: Once the appropriate handler is determined, the DispatcherServlet calls the handler’s methods to execute the desired functionality. The handler performs any necessary processing, such as retrieving data from a database, manipulating it, and preparing a response.
  • View Resolution: After the handler has processed the request, it returns a logical view name or a View object. The DispatcherServlet then uses the configured ViewResolver(s) to resolve the logical view name to an actual View implementation, which can generate the response.
  • View Rendering: The resolved View takes the model data provided by the handler and generates the appropriate response, such as an HTML page, JSON, XML, or any other format. The DispatcherServlet passes the model to the View, which renders the response and prepares it to be sent back to the client.
  • Response Handling: The rendered response is sent back to the client as the final result of the request.

The DispatcherServlet also provides various extension points and hooks for customization. For example, developers can define their own HandlerMappings to handle custom URL patterns, or they can implement their own ViewResolvers to support different view technologies.

In summary, the DispatcherServlet is a central component in the Spring MVC framework that receives requests, determines the appropriate handlers and views, and orchestrates the processing of those requests. It plays a crucial role in the overall request-handling flow of a Spring MVC application.

Setting Up the Project for Web MVC in Spring Framework

Up until now, we have been using a set of JAR files. When using Spring MVC, we shall require some other JAR files. They can be downloaded from the following links:

https://repo1.maven.org/maven2/commons-logging/commons-logging/1.2/commons-logging-1.2.jar

https://repo1.maven.org/maven2/org/springframework/spring-asm/3.1.4.RELEASE/spring-asm-3.1.4.RELEASE.jar

https://repo1.maven.org/maven2/org/springframework/spring-beans/6.0.10/spring-beans-6.0.10.jar

https://repo1.maven.org/maven2/org/springframework/spring-context/6.0.10/spring-context-6.0.10.jar

https://repo1.maven.org/maven2/org/springframework/spring-core/6.0.10/spring-core-6.0.10.jar

https://repo1.maven.org/maven2/org/springframework/spring-expression/6.0.10/spring-expression-6.0.10.jar

https://repo1.maven.org/maven2/org/springframework/spring-web/6.0.10/spring-web-6.0.10.jar

Implementing Hello World using Web MVC in Spring Framework

Before starting the project, ensure that the required JAR files are in the project’s “Referenced Libraries” folder.

Implementing Hello World using Web MVC in Spring Framework

Step 1: Create a new file called HelloController.java in the src/ directory. Add the following content to the file:

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/hello")
public class HelloController
{
    @RequestMapping(method = RequestMethod.GET)
    public String printHelloWorld(ModelMap mm)
    {
        mm.addAttribute("message", "Hello World! from Spring MVC");
        return "Hello World";
    }
}

Step 2: Create a new file called web.xml in the src/ directory. Add the following content to the file:

<web-app id = "WebApp_ID" version = "2.4"
   xmlns = "http://java.sun.com/xml/ns/j2ee" 
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

   <display-name>Spring Framework Web MVC Application</display-name>
   <servlet>
      <servlet-name>HelloWeb</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>HelloWeb</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

This file is responsible for creating the servlet that will print the Hello World text.

Step 3: Create a new file called HelloWeb-servlet.xml in the src/ directory. Add the following content to the file:

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:context = "http://www.springframework.org/schema/context"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name = "prefix" value = "/WEB-INF/jsp/" />
      <property name = "suffix" value = ".jsp" />
   </bean>
</beans>

This file is responsible for loading the JSP file. JSP stands for JavaServer Pages. It is a technology used for developing dynamic web pages in Java. JSP allows developers to embed Java code within HTML pages, which are then processed on the server to generate dynamic content that can be sent to the client’s web browser.

Step 4: Create a new file called hello.jsp in the src/ directory. Add the following content to the file:

<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
   <head>
      <title>Hello World</title>
   </head>
   
   <body>
      <h2>${message}</h2>
   </body>
</html>

This file represents the HTML file that will be shown to the user.

Step 5: Compile and execute this application. Open your browser and log into the webpage http://localhost:8080/HelloWeb/hello. You may replace HelloWeb with your application name and hello with the name set in the @RequestMapping attribute. The following output must be visible:

Web MVC in Spring Framework with Examples

Congratulations! You have completed the Web MVC application in Spring Framework!

In the next article, I am going to discuss Spring Framework Logging with Log4J. Here, in this article, I try to explain Web MVC in Spring Framework with Examples. I hope you enjoy this Spring Framework Web MVC article.

1 thought on “Web MVC in Spring Framework ”

Leave a Reply

Your email address will not be published. Required fields are marked *