Spring MVC Flow Overview

In this article, we will learn about how the Spring MVC flow works along with its architecture and benefits. We will also see a sample example which will help us to understand this topic more clearly.

Spring MVC means Spring Model-View-Controller. Spring MVC is a framework that follows the Model-View-Controller design pattern. It is a framework for building Web applications in java. This framework uses all the spring core-related features like the inversion of control, dependency injection, etc.

Spring MVC architecture

Below is the high-level diagram of Spring MVC architecture and explanation.

Spring Model-View-Controller
Spring Model-View-Controller

1. The web browser triggers a request

2. The front controller catches the request and delegates the request to the appropriate custom controller. The front controller is a part of the Spring MVC framework which is already developed by the Spring development team.

Note* The front controller is also known as the dispatcher servlet which dispatches the request to appropriate controllers based on the Url patterns.

3. As soon as the request reaches the custom controller it will

  • Capture the request message
  • Create the model object. The model contains the data.
  • Perform the business or processing logic
  • Updates the model object with output data and sends that model to the appropriate view or templates

4. View will display the model object on the web browser in the form of JSP or JSTL etc.

Benefits of using Spring MVC

1. Spring MVC framework provides a set of reusable UI components which are available in the form of spring JSP custom tags.

2. We can do the session tracking or application tracking using Spring MVC as we get pre-built classes to do so.

3. Spring MVC can help to perform the validations or conversions on form data. Validation Ex. password should have alphanumeric characters and the length of the password should be greater than 10.

Note* Form is a document that stores information of a user on a web server using interactive controls. A form can contain different kinds of information like username, password, contact number, email id, etc. https://www.geeksforgeeks.org/html-design-form/

4. We can use different types of configurations on the view layer. Like JSP, JSTL, Free Marker, Velocity, etc.

Components of Spring MVC application

There are 3 components of a Spring MVC application

  • Spring Configuration which can be XML, Annotations or Java-based.
  • Spring beans to create controllers, services, dao’s etc.
  • User Interface components ( view or templates )

We will learn about these components below but before that for creating a Spring MVC application we will need a proper local environment setup. Please go through this article which will help you to configure all the required components like Editor, Server, Spring dependencies etc. https://getinputs.com/spring-environment-setup/

Spring MVC Configuration

Create a web.xml file and add the below configs to that file

1. Configure Spring MVC dispatcher servlet.
2. Set the URL mapping to this dispatcher servlet.
3. Define the context config location in the init params.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
	<display-name>spring-mvc-demo</display-name>
	<absolute-ordering />
	<!-- Spring MVC Configs -->
	<!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
	<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-demo-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

Create a context config file named spring-mvc-demo-servlet.xml which we have mentioned in the web.xml file.

In the context config file, we will add the below configs

1. Add support for component scanning. So the spring container will register the beans automatically which are annotated with special annotations like @Component and instantiate them.

2. Add support for validation, conversion and formatting.

Convert the form data – It adds support for reading and writing XML if JAXB is on the classpath. It adds support for reading and writing Json if Jackson is in the classpath

Format the form data – Ex. Format Number fields with @NumberFormat. It also adds support for formatting Date, Calendar, and Joda Time fields with @DateTimeFormat.

Validate the form data – It adds support for validating the input fields with @Valid.

3. We will also define the view resolver. Here we will know the location of template files and the format of the files.

spring-mvc-demo-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
    	http://www.springframework.org/schema/beans/spring-beans.xsd
    	http://www.springframework.org/schema/context
    	http://www.springframework.org/schema/context/spring-context.xsd
    	http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
	<!-- Step 3: Add support for component scanning -->
	<context:component-scan base-package="com.getinputs" />
	<!-- Step 4: Add support for conversion, formatting and validation support -->
	<mvc:annotation-driven/>
	<!-- Step 5: Define Spring MVC view resolver -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

When our web application will provide a view name spring will append the suffix and prepend the prefix.

Ex. View name = hello
Output = /WEB-INF/view/hello.jsp

Create a Spring bean controller

Now we will create a Spring bean and annotate the bean with @Controller annotation.

@Controller inherits from @Component and it supports scanning.

We annotate bean with @Controller annotation if it will handle web requests. This annotation is used in combination with @RequestMapping annotation. @RequestMapping annotation is used on handler methods and it maps web service URLs to the handler methods.

If you want to know more about @Controller annotation check this blog https://www.geeksforgeeks.org/spring-controller-annotation-with-example/

HomeController.java

package com.getinputs;

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

@Controller
public class HomeController {

  @RequestMapping(value = "/home")
  public String getHomePage(Model model) {

    model.addAttribute("name", "Suraj");

    return "home-page";
  }
}

View page

In the above code, we have added the name attribute to the model. We can use this model on the view page and print the name. We have returned a view name (i.e) home-page.

So the actual view path will be /WEB-INF/view/home-page.jsp

home-page.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Home Page</title>
 </head>
 <body>
  <h2>Hello ${name}</h2>
 </body>
</html>

Now we will run this web application on the tomcat server and check the web browser.

As we can see from the above image we are able to call the Web service and we are able to get the name on the template page. This is how the Spring MVC flow works.

https://github.com/getinputs/samples/tree/main/spring-mvc-demo

So this is all about how the Spring MVC flow works. I hope you found this article interesting and valuable. If you are having any concerns or questions about this article please comment below and please share it to help me grow.

Leave a Comment