Spring MVC Tutorial for Beginners

This Spring MVC tutorial designed for Java beginners to quickly understand Spring MVC framework basics and you will learn how to develop Spring MVC web application with Java-based configuration.

Before getting started with Spring MVC, let's first understand what is MVC?

What is MVC (Model-View-Controller)?

MVC is a commonly used pattern in implementing the presentation layer of an application. The main principle of the MVC pattern is to define an architecture with clear responsibilities for different components. As its name implies, there are three participants within the MVC pattern:
  1. The Model Layer - This is the data layer which contains the business logic of the system, and also represents the state of the application. It’s independent of the presentation layer, the controller fetches the data from the Model layer and sends it to the View layer.
  2. The Controller Layer - The controller layer acts as an interface between View and Model. It receives requests from the View layer and processes them, including the necessary validations.
  3. The View Layer - This layer represents the output of the application, usually some form of UI. The presentation layer is used to display the Model data fetched by the Controller.
Read more about Model-View-Controller pattern at Model View Controller (MVC) Design Pattern in Java.


What is Spring MVC?

Well, basically, Spring MVC is a framework for building web applications in Java. As the name suggests, it's based on the Model-View-Controller design pattern.

And also, the nice thing about it is that it leverages the features of the core Spring Framework such as inversion of control and dependency of injection.

In the Spring Framework, the Spring MVC module provides comprehensive support for the MVC pattern, with support for other features (for example, theming, i18n, validation, and type conversion and formatting) that ease the implementation of the presentation layer.

Read more about the Spring MVC framework at the official documentation.

The DispatcherServlet

Spring MVC, like many other web frameworks, is designed around the front controller pattern where a central Servlet, the DispatcherServlet, provides a shared algorithm for request processing, while actual work is performed by configurable delegate components. This model is flexible and supports diverse workflows.

The DispatcherServlet, as any Servlet, needs to be declared and mapped according to the Servlet specification by using Java configuration or in web.xml.

The following example of the Java configuration registers and initializes the DispatcherServlet, which is auto-detected by the Servlet container:
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletCxt) {

        // Load Spring web application configuration
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        ac.register(AppConfig.class);
        ac.refresh();

        // Create and register the DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(ac);
        ServletRegistration.Dynamic registration = servletCxt.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/app/*");
    }
}

In addition to using the ServletContext API directly, you can also extend AbstractAnnotationConfigDispatcherServletInitializer and override specific methods. 

For example: Create a SpringMvcDispatcherServletInitializer class by extending the AbstractAnnotationConfigDispatcherServletInitializer class as follows.
package net.javaguides.springmvc.helloworld.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * @author Ramesh Fadatare
 */
public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class <?> [] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected Class <?> [] getServletConfigClasses() {
        return new Class[] {
            AppConfig.class
        };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {
            "/"
        };
    }
}
The following example of web.xml configuration registers and initializes the DispatcherServlet:
<web-app>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-context.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>app</servlet-name>
        <url-pattern>/app/*</url-pattern>
    </servlet-mapping>
</web-app>

Spring MVC WebApplicationContext Hierarchy

In Spring MVC, DispatcherServlet is the central servlet that receives requests and dispatches them to
the appropriate controllers. In a Spring MVC application, there can be any number of DispatcherServlet instances for various purposes (for example, handling user interface requests and RESTful-WS requests), and each DispatcherServlet has its own WebApplicationContext configuration, which defines the servlet level characteristics, such as controllers supporting the servlet, handler mapping, view resolving, i18n, theming, validation, and type conversion and formatting.

Underneath the servlet-level WebApplicationContext configurations, Spring MVC maintains a root
WebApplicationContext, which includes the application-level configurations such as the back-end data source, security, and service and persistence layer configuration. The root WebApplicationContext will be available to all servlet-level WebApplicationContexts.

 The following image shows this relationship:
The following example configures a WebApplicationContext hierarchy:
package net.javaguides.springmvc.helloworld.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * @author Ramesh Fadatare
 */
public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class <?> [] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected Class <?> [] getServletConfigClasses() {
        return new Class[] {
            AppConfig.class
        };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {
            "/"
        };
    }
}
The following example shows the web.xml equivalent:
<web-app>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>app1</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/app1-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>app1</servlet-name>
        <url-pattern>/app1/*</url-pattern>
    </servlet-mapping>

</web-app>

Build Spring MVC Hello World Application

Let's learn how to create a simple Spring MVC web application using Java-based configuration that is we configure the Spring DispatcherServlet and spring beans configuration using all Java Code (no XML).

Tools and technologies used

Here are the tools and technologies that we will be using to build a simple Spring MVC web application:
  • Spring MVC - 5.1.0 RELEASE
  • JDK - 1.8 or later
  • Maven - 3.5.1
  • Apache Tomcat - 8.5
  • IDE - STS/Eclipse Neon.3
  • JSTL - 1.2.1

Spring MVC Hello World Application Flow

The following image shows the typical request-response flow in Spring MVC application:


Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −
  • After receiving an HTTP request, The Front controller or DispatcherServlet consults the HandlerMapping to call the appropriate Controller. 
  • The Controller takes the request and calls the appropriate service methods based on the used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.
  • The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request.
  • Once a view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers.

Development Steps

  1. Create a Maven Web Application
  2. Add Dependencies - pom.xml File
  3. Project Structure
  4. Spring Configuration - AppConfig.java
  5. Servlet Container Initialization - MySpringMvcDispatcherServletInitializer.java
  6. Model Class - HelloWorld.java
  7. Controller Class - HelloWorldController.java
  8. View - helloworld.jsp
  9. Build + Deploy + Run an application
  10. Demo

1. Create a Maven Web Application

Let's create a Maven-based web application either using a command line or from Eclipse IDE.
1.  Use Guide to Create a Maven Web Application link to create a maven project using a command line. 
2. Use Create Maven Web Application using the Eclipse IDE link to create a maven web application using IDE Eclipse.
Once you created a maven web application, refer below pom.xml file jar dependencies.

2. Add Dependencies - pom.xml File

Refer the following pom.xml file and add jar dependencies to your pom.xml.
<project xmlns="https://maven.apache.org/POM/4.0.0"
 xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.springmvc</groupId>
    <artifactId>springmvc5-helloworld-exmaple</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>springmvc5-helloworld-exmaple Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
       <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.0.RELEASE</version>
        </dependency>

        <!-- JSTL Dependency -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <!-- Servlet Dependency -->
        <dependency>
             <groupId>javax.servlet</groupId>
             <artifactId>javax.servlet-api</artifactId>
             <version>3.1.0</version>
             <scope>provided</scope>
        </dependency>

        <!-- JSP Dependency -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>
     </dependencies>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
     </build>
</project>
Note that we are using spring-webmvc dependency for a Spring MVC web application.
Next, let's create a standard project structure, please refer below diagram.

3. Project Structure

Standard project structure for your reference -
As the name suggests Spring MVC, look at the diagram we are using the Model-View-Controller approach.
Model - HelloWorld.java
View - helloworld.java
Controller - HelloWorldController.java
Next step, we will configure Spring beans using Java-based configuration. 

4. Spring Configuration - AppConfig.java

Create an AppConfig class and annotated with @Configuration@EnableWebMvc, and @ComponentScan annotations as follows.
package net.javaguides.springmvc.helloworld.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * @author Ramesh Fadatare
 */

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {
    "net.javaguides.springmvc.helloworld"
})
public class AppConfig {

    @Bean
    public InternalResourceViewResolver resolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}
Let's understand few important annotations as below:
  • The @Configuration is a class-level annotation indicating that an object is a source of bean definitions.
  • The @EnableWebMvc enables default Spring MVC configuration and provides the functionality equivalent to mvc:annotation-driven/ element in XML based configuration.
  • The @ComponentScan scans the stereotype annotations (@Controller, @Service etc...) in a package specified by basePackages attribute.

InternalResourceViewResolver

This ViewResolver allows us to set properties such as prefix or suffix to the view name to generate the final view page URL:
    @Bean
    public InternalResourceViewResolver resolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
We only need a simple JSP page, placed in the /WEB-INF/view folder. In this example, we have used helloworld.jsp as the view - /WEB-INF/views/helloworld.jsp.

5. Servlet Container Initialization - SpringMvcDispatcherServletInitializer.java

Let's configure Spring MVC DispatcherServlet and set up URL mappings to Spring MVC DispatcherServlet.
Create a SpringMvcDispatcherServletInitializer class by extending the AbstractAnnotationConfigDispatcherServletInitializer class as follows.
package net.javaguides.springmvc.helloworld.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * @author Ramesh Fadatare
 */
public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class <?> [] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected Class <?> [] getServletConfigClasses() {
        return new Class[] {
            AppConfig.class
        };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {
            "/"
        };
    }
}

6. Model Class - HelloWorld.java

As we know that Spring MVC uses a model-view-controller design pattern. Let's create a model - HelloWorld.java with message and DateTime fields. This model data will be rendered on a view (JSP file).
package net.javaguides.springmvc.helloworld.model;

public class HelloWorld {
    private String message;
    private String dateTime;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getDateTime() {
        return dateTime;
    }
    public void setDateTime(String dateTime) {
        this.dateTime = dateTime;
    }
}
Next, we will create a Controller to handle a request, populate the model with some data and returns the view to a browser.

7. Controller Class - HelloWorldController.java

Create a HelloWorldController class annotated with @Controller annotation under net.javaguides.springmvc.helloworld.controller package and write the following code in it.
package net.javaguides.springmvc.helloworld.controller;

import java.time.LocalDateTime;

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

import net.javaguides.springmvc.helloworld.model.HelloWorld;

/**
 * @author Ramesh Fadatare
 */
@Controller
public class HelloWorldController {

    @RequestMapping("/helloworld")
    public String handler(Model model) {

        HelloWorld helloWorld = new HelloWorld();
        helloWorld.setMessage("Hello World Example Using Spring MVC 5!!!");
        helloWorld.setDateTime(LocalDateTime.now().toString());
        model.addAttribute("helloWorld", helloWorld);
        return "helloworld";
    }
}

8. View - helloworld.jsp

Let's create an helloworld.jsp file under src/main/webapp/WEB-INF/views folder and write the following code in it.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head><%@ page isELIgnored="false" %>
<meta charset="ISO-8859-1">
<title>Spring 5 MVC - Hello World Example | javaguides.net</title>
</head>
   <body>
      <h2>${helloWorld.message}</h2>
      <h4>Server date time is : ${helloWorld.dateTime}</h4>
   </body>
</html>

9. Build + Deploy + Run an application

As we are using maven build tool so first, we will need to build this application using the following maven command:
clean install
Once build success, then we will run this application on tomcat server 8.5 in IDE or we can also deploy war file on the external tomcat webapps folder and run the application.

10. Demo

Once an application is up and running in tomcat then hit this link into browser: http://localhost:8080/springmvc5-helloworld-exmaple/helloworld
We will see below the page on the browser with the current date-time and a message from a model.

That's all. Now we have developed a very simple Spring MVC web application.

Advanced Spring MVC Tutorials and Examples

Use below spring MVC tutorials and examples to learn more about Spring MVC framework:

Spring MVC Getting Started/Basics

  • Spring MVC 5 - Hello World Example - In this article, we will learn how to create a simple Hello World Spring MVC Application using Spring MVC 5 +, JSP, Maven build tool and Eclipse IDE
  • Spring MVC 5 - Sign Up Form Handling Example - In this article, we will learn how to create and submit a simple form (signup form) in Spring MVC application using Spring MVC 5+, Maven build tool, JSP and Eclipse IDE or STS.
  • Spring MVC JSP Form Tags Tutorial - In this tutorial, we're going discuss all Spring MVC form tags and we will use important spring MVC form tags such as form tag, text fields tag, select tag, check-box(s), radio box(s), password tag, button tag, errors tag, etc.

Spring MVC 5 and Hibernate 5 Integration

  • Spring MVC 5 + Hibernate 5 + JSP + MySQL CRUD Tutorial - In this spring hibernate integration tutorial, we will learn how to create Spring MVC 5 web application, handle form submission, integrate hibernate 5 to connect to the backend database. In this tutorial, we will integrate Spring MVC 5+ with the Hibernate ORM framework using Java-based configuration without any XML configuration.

Spring MVC + Spring Boot Articles

  • Spring Boot 2 - Spring MVC + Thymeleaf Input Form Validation - In this quick article, we will discuss the process of configuring a web application form to support validation. We will use the latest Spring boot 2.0.5 RELEASE, Hibernate validator with Thymeleaf to develop a simple Spring MVC web application. We get Hibernate Validator for free when we use Spring Boot Starter Web.

Spring MVC + Spring Boot  + Spring Security

Check out complete Spring MVC tutorial at https://www.javaguides.net/p/spring-mvc-tutorial.html.

Comments