📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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:- 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.
- 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.
- 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.
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
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/*"); } }
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[] {
"/"
};
}
}
<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
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[] { "/" }; } }
<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
Tools and technologies used
- 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
- 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
- Create a Maven Web Application
- Add Dependencies - pom.xml File
- Project Structure
- Spring Configuration - AppConfig.java
- Servlet Container Initialization - MySpringMvcDispatcherServletInitializer.java
- Model Class - HelloWorld.java
- Controller Class - HelloWorldController.java
- View - helloworld.jsp
- Build + Deploy + Run an application
- Demo
1. Create a Maven Web Application
2. Add Dependencies - pom.xml File
<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>
3. Project Structure
4. Spring Configuration - AppConfig.java
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;
}
}
- 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
@Bean public InternalResourceViewResolver resolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setViewClass(JstlView.class); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; }
5. Servlet Container Initialization - SpringMvcDispatcherServletInitializer.java
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
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;
}
}
7. Controller Class - HelloWorldController.java
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
<%@ 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
clean install
10. Demo
Advanced Spring MVC Tutorials and Examples
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 Form Validation with Annotations Tutorial - In this quick tutorial, we're going to learn about Spring MVC form validation using annotations like @NotNull, @Size, @Min, @Max, @Email, @Pattern, 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 5 + Spring Data JPA + Hibernate 5 + JSP + MySQL Tutorial - In this tutorial, we will discuss the integration of Spring MVC 5, Spring Data JPA, Hibernate 5 and MySQL CRUD example. We will demonstrate CRUD(Create, Retrieve, Update, Delete) operations on a Customer entity as well as a display list of customers from the MySQL database.
- Spring MVC + Spring Boot2 + JSP + JPA + Hibernate 5 + MySQL Example - In this article, we will learn how to develop a Spring MVC web application using Spring MVC, Spring boot 2, JSP, Hibernate 5, JPA, Maven, and MySQL database.
- Spring Boot 2 MVC Web Application Thymeleaf JPA MySQL Example - In this article, we will learn how to develop a Spring MVC web application using Spring boot 2, Thymeleaf, Hibernate 5, JPA, Maven, and MySQL database.
- Spring MVC 5 + Hibernate 5 XML Based Configuration Example - In this tutorial, we will integrate Spring MVC with Hibernate ORM framework using XML-based configuration.
Spring MVC + Spring Boot Articles
- Spring MVC Thymeleaf CRUD Example Tutorial - In this tutorial, we’ll learn how to develop a CRUD web application with Spring MVC and Thymeleaf.
- Spring MVC + Spring Boot2 + JSP + JPA + Hibernate 5 + MySQL Example - In this article, we will learn how to develop a Spring MVC web application using Spring MVC, Spring boot 2, JSP, Hibernate 5, JPA, Maven, and MySQL database.
- Spring Boot 2 MVC Web Application Thymeleaf JPA MySQL Example - In this article, we will learn how to develop a Spring MVC web application using Spring boot 2, Thymeleaf, Hibernate 5, JPA, Maven, and MySQL database.
- 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
- Spring Boot 2 + Spring MVC + Role-Based Spring Security + JPA + Thymeleaf + MySQL Tutorial -In this tutorial, we will learn how to use the Spring Boot Security Starter to secure SpringMVC-based web applications. We will develop step by step Message Storing Spring MVC web application(securing with spring security) using spring boot, spring MVC, role-based spring-security, JPA, Thymeleaf, and MySQL.
- Authenticating a User with LDAP using Spring Boot and Spring Security - This guide walks you through the process creating an application and securing it with the Spring Security LDAP module.
- User Registration Module using Spring Boot 2 + Spring MVC + Spring Security + Hibernate 5 + Thymeleaf + MySQL - In this article, we discuss how to create a user registration form with Spring Boot, Spring Security, Hibernate and Thymeleaf. We validate the user registration fields with hibernate validator annotations and a custom field matching validator to validate if the email and/or password fields match. We will create Role-based Spring security with a MySQL database.
GitHub Repository
Check out complete Spring MVC tutorial at https://www.javaguides.net/p/spring-mvc-tutorial.html.
Comments
Post a Comment
Leave Comment