Spring MVC architecture uses the "FrontController" design pattern which is fundamental to any MVC design implementation. The DispatcherServlet is at the heart of this design whereby HTTP requests are delegated to the controller, views are resolved to the underlying view technology, in addition to providing support for uploading files. The DispatcherServlet like any regular servlet can be configured along with custom handler mappings.
Spring MVC framework enables separation of modules namely Model, View, and Control and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. The model object can be passed between view and controller using Maps. Additionally, validation for types mismatch and two-way data-binding support in the user interface is provided. Easy form-submission and data-binding in the user interface are possible with spring form tags, model objects, and annotations.
The article discusses the steps involved in developing a Spring web MVC application, explaining the initial project setup for an MVC application in Spring. JSP(Java Server Pages) is used as a view technology.
The following are the dependencies for Spring web MVC. While spring-web MVC jar would suffice for all container requirements to develop the MVC application, JSTL-jar is included for JSP:
Dependencies within pom.xml
Java
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
The DispatcherServlet would be configured in web.xml as follows. The listener class
ContextLoaderListener would load the root application context and transfer the handle to dispatcher servlet mentioned in the servlet-mapping element. All requests corresponding to the '/' URL mapping would be handled by this dispatcher servlet.
web.xml
Java
<web-app>
<display-name>SampleMVC</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>
/index.html
</welcome-file>
</welcome-file-list>
The related
WebApplicationContext for a dispatcher servlet can be found in the default location 'servletName'-servlet.xml using the context-param
contextConfigLocation. The
WebApplicationContext contains the MVC-specific configurations including view-resolvers, datasource, messagesource, multipart-resolver (file-upload), etc.
WEB-INF/mvc-dispatcher-servlet.xml
Java
<context:component-scan base-package="com.springsamples*"/>
<mvc:annotation-driven/>
<!-- this will render home page from index.html-->
<mvc:default-servlet-handler/>
<bean id = "viewProvider"
class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
In the above XML, the element component-scan with context namespace will scan all the component classes for annotations(
@Component, @Configuration, @Service, @Repository, @Autowired) in the base packages and also initialize the beans. The element annotation-driven within the MVC namespace will scan and initialize
@Controller annotated components.
The element default-servlet-handler, within MVC namespace, extends the default HTTP dispatcher servlet to also serve requests for static resources located in the web-root.
We have also initialized a bean with id 'viewProvider' for rendering .jsp pages. The class
InternalResourceViewResolver would accept the prefix and suffix parameters to construct the path to view page. For example, if the controller class returned a view named as 'greet' then the view-resolver class would identify the path relative to web-root as "/greet.jsp" by appending the given suffix and prefix strings.
Finally, the .jsp file which will be the view. We are sending an attribute from controller class to the view which will be displayed upon hitting the matching URL.
greet.jsp
Java
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-// W3C// DTD HTML 4.01
Transitional// EN" "http:// www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Start Spring MVC</title>
</head>
<body>
<h1>Start here</h1>
${greeting}
</body>
</html>
The controller class code as follows.
Java
@GetMapping(value = "/")
public ModelAndView firstView()
{
ModelAndView mav = new ModelAndView("greet");
// must match the jsp page name which is being requested.
mav.addObject("greeting", "GeeksForGeeks Welcomes you to Spring!");
return mav;
}
Please check the view below which displays the string "greeting" value provided in the controller.
Similar Reads
Spring MVC CRUD with Example
In this article, we will explore how to build a Spring MVC CRUD application from scratch. CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the four basic operations to create any type of project. Spring MVC is a popular framework for building web applications. Spring MVC follows
7 min read
JSON Parameters with Spring MVC
JSON (JavaScript Object Notation) is a lightweight data exchange format. We can interchange data from one application to another from client to server. We have many data interchange formats available in the market. Like properties files, XML files, YAML files, JSON files, etc. But when compared to o
14 min read
ViewResolver in Spring MVC
Spring MVC is a powerful Web MVC Framework for building web applications. It provides a structured way to develop web applications by separating concerns into Model, View, and Controller. One of the key features of Spring MVC is the ViewResolver, which enables you to render models in the browser wit
7 min read
Spring MVC - Custom Validation
Validating user input is essential for any web application to ensure the processing of valid data. The Spring MVC framework supports the use of validation API. The validation API puts constraints on the user input using annotations and can validate both client-side and server-side. It provides stand
8 min read
Spring MVC Matrix Variables
In this article, we will learn about Spring MVC Matrix Variables. Matrix Variable is used to parse and bind name-value pairs inside a path segment to method parameters. A semicolon separates many pairs. Matrix variables must first be enabled. XML Matrix VariableBelow are the necessary dependencies a
3 min read
Serve Static Resources With Spring
It's essential to know about static resources, which are the resources that do not change frequently on a web page. To serve these static resources, Spring Boot comes with an inbuilt class called ResourceHttpRequestHandler in conjunction with the ResourceHandlerRegistry class. You can keep these sta
4 min read
Top 10 Spring MVC Annotations with Examples
In the world of Spring MVC, annotations are like a reliable assistant for your web applications. They usually work behind the scenes of your application and make tasks easier. Also, they help the developers to communicate clearly with their applications and ensure what the developers actually want t
10 min read
Spring Boot Without A Web Server
Spring Boot is a widely used framework used for building Java applications. It comes with lots of features that make a developer's life easy. Out of those features, spring boot applications come with an embedded server in it. The default server being used in spring boot applications is Apache Tomcat
3 min read
Spring @Value Annotation with Example
The @Value annotation in Spring is one of the most important annotations. It is used to assign default values to variables and method arguments. It allows us to inject values from spring environment variables, system variables, and properties files. It also supports Spring Expression Language (SpEL)
6 min read
Spring MVC - WebMvcConfigure
Spring WebMvcConfigurer enables developers to customize the default MVC setups in Spring applications. By implementing this interface, users can customize several features of the MVC framework, such as interceptors, resource handling, and view controllers. In this article, we will learn how to Custo
4 min read