Spring MVC Framework Tutorial with Example

Spring MVC

Spring MVC (Model view controller) is based on the MVC design pattern, it is a software architecture design pattern.  It provides solution to layer an application by separating three concerns business, presentation and control flow.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Pattern“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.
  • The Model can be some DAO layer or some Service Layers which give some information about request or requested information or Model can be a POJO which encapsulates the application data given by the controller.
  • The View is responsible for rendering the model data and in general it generates HTML output that the client’s browser can interpret.
  • The Controller is responsible for processing user requests and building appropriate model and passes it to the view for rendering.

 

Advantages of Spring MVC Framework-

  • Supports RESTful URLs.
  • Annotation based configuration(i.e. you may reduce the metadata file or less of configuration).
  • Supports to plug with other MVC frameworks like Struts, Struts2, WebWorks etc.
  • Flexible in supporting different view types like JSP, velocity, XML, PDF, Tiles etc.

Front Controller

Front Controller is very important component one which route the all the requests into framework control that means when ever requests land on different controllers it queues that request to the controller of framework without this MVC framework will not may be able to take control of the request at landing at the application. So front controller is not only capture the request but also the following responsibility-

  • It initialize the framework to cater to the requests.
  • Load the map of all URLs and the components responsible to handle the request.
  • Prepare the map for the views.


Spring MVC Basic Architecture

The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.

In Spring MVC framework Dispatcher Servlet access Front Controller which handles all coming requests and queses for forward to the different controller.
1. Whenever request lands the dispatcher servlet consult with HandlerMapping
(HandlerMapping– is a component which have the map of URL and Controller which need to be invoked for that particular request which lands with URL)
2. then Dispatcher servlet has information about which is controller need to be invoked
3. then that controller will be invoked
4. and Controller can request the model for some information (about some DAO, Service layer or Data in POJO, or data in database using business logic)
5. once process has been done then dispatcher servlet get the response then dispatcher servlet will get view resolver to build the view and view resolver look out what view has being configured it has been JSP, Velocity, XML etc. based this configuratin view has been prepared and the information from model i.e. POJO it will be put on the view and response will be send back to browser.

Spring  MVC Request Flow

1. Request lands to Front Controller i.e. DispatcherServlet
2. Capture the Request Locale i.e use for internationalization i.e Read .properties files
3. Check for multipart-file(MIME type header or not) upload data from distributed application
4. Consult with HandlerMapping for which Controller to be invoked
5. and Then responsibility is given to the Handler Chain
6. This Handler Chain is responsible to be invoked some of the interceptors that needs to be invoked before of a controller and after the controller that means interceptors are here like very to similar to the filters that help to separate the pre-process logic and post-process logic.
7. After process of pre-process interceptor return to the controller process the post-process logic.
8. Then return to the view resolver prepared the view based on your configuration decide the which configuration (JSP, Velocity, PDF etc.) to be invoked.
9. After choosing view technology prepare the view and return the response back to the client.

Spring MVC Framework- Initialization

MultipartResolver: Interface to handle the file uploads
LocaleResolver: Helps to resolve the locale from the request
ThemeResolver: Resolve a theme for a request(CSS)
HandlerMapping: Maps the Request to Handlers (Controllers)
HandlerAdapter: Plugs the other frameworks handlers
HandlerExceptionResolver: Mapping of the exceptions to handlers and views
ViewResolver: Maps the view names to view instances

All the above mentioned components ie. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext which is an extension of the plain ApplicationContext with some extra features necessary for web applications.

Required Spring MVC Configuration

You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for spring3 DispatcherServlet example:

Step 1:- Configure the web.xml with DispatcherServlet and details of the application context file location.

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

   <servlet>
      <servlet-name>spring3</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>spring3</servlet-name>
      <url-pattern>*.*</url-pattern>
   </servlet-mapping>

</web-app>

Step 2:- Configure the contextConfigLocation for the application context to be loaded.

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

   <servlet>
      <servlet-name>spring3</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>spring3</servlet-name>
      <url-pattern>*.*</url-pattern>
   </servlet-mapping>

   <context-param>
      <param-name>contextConfigLocation</param-name><param-value>/WEB-INF/spring3-servlet.xml</param-value></context-param>
   <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
      </listener-class>
    </listener>
</web-app>

Step 3:- Configure the spring3-servlet.xml

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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">

   <context:component-scan base-package="com.dineshonjava">
   </context:component-scan>
   <context:annotation-config></context:annotation-config>
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/"></property>
      <property name="suffix" value=".jsp"></property>
   </bean>

</beans>

Following are the important points about spring3-servlet.xml file:

  • The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope.
  • The <context:component-scan…> tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc.
  • The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp .

@Controller:

  •  Used at the class level
  • Tells the spring framework that the marked class acts as a controller.
@Controller
public class EmployeeController{

}

@RequestMapping:

  • Can be used at the class level and method level in controllers.
  • Arguments:-
    URL[]
    HTTP Methods[]-GET, POST, DELETE, TRACE, OPTIONS, HEAD, PUTS. Defaults method supported is GET
    -params[]-used to check if a request parameter matches with a value and only if the conditions passes the method or controller processes the request.
    (eg. @RequestMapping params=”myName=guest” )
    -headers[]-used to check if a request header matches with a value and only if the condition passes the method or controller processes the request
    (eg. @RequestMapping headers=”myheader=guestHadder”)

Next section will show you how to create your actual components ie. Controller, Model and View.

Defining a Controller

DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

@Controller
@RequestMapping("/employee/*")
public class EmployeeController{
 
   @RequestMapping("add", method = RequestMethod.POST)
   public String createEmployee(){}//appcontext/employee/add
   @RequestMapping("delete", method = RequestMethod.GET)
   public String deleteEmployee(){}//appcontext/employee/delete
   @RequestMapping("details")//By default the method is GET
   public String getEmployeeDetails(){}//- /appcontext/employee/details

}

You can write above controller in another form where you can add additional attributes in @RequestMapping as follows:

@Controller
public class EmployeeController{
 
   @RequestMapping("add", method = RequestMethod.POST,value=/employee)
   public String createEmployee(){}//appcontext/employee/add
   @RequestMapping("delete", method = RequestMethod.GET,value=/employee)
   public String deleteEmployee(){}//appcontext/employee/delete
   @RequestMapping("details",value=/employee)//By default the method is GET
   public String getEmployeeDetails(){}//- /appcontext/employee/details

}

The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle HTTP GET request. There are following important points to be noted about the controller defined above:

  • You will defined required business logic inside a service method. You can call another methods inside this method as per requirement.
  • Based on the business logic defined, you will create a model within this method. You can setter different model attributes and these attributes will be accessed by the view to present the final result. This example creates a model with its attribute “message”.
  • A defined service method can return a String which contains the name of the view to be used to render the model.

Creating JSP Views

Spring MVC supports many types of views for different presentation technologies. These include – JSPs, HTML, PDF, Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom and RSS feeds, JasperReports etc. But most commonly we use JSP templates written with JSTL. So let us write a simple employee view in /WEB-INF/emp/employee.jsp:

<html>
   <head>
   <title>Hello Spring MVC</title>
   </head>
   <body>
   <h2>
${name}</h2>
</body>
</html>

Here ${name} is the attribute which we have setup inside the Controller. You can have multiple attributes to be displayed inside your view.
Spring Web MVC Framework Examples

Based on the above concepts, let us check few important examples which will help you in building your Spring Web Applications:

S.N. Example & Description
1 Spring MVC Hello World Example
This example will explain how to write a simple Spring Web Hello World application.
2 Spring MVC Form Handling Example
This example will explain how to write a Spring Web application using HTML forms to submit the data to the controller and display back a processed result.
3 Spring Page Redirection Example
Learn how to use page redirection functionality in Spring MVC Framework.
4 Spring Static Pages Example
Learn how to access static pages along with dynamic pages in Spring MVC Framework.
5 Spring Exception Handling Example
Learn how to handle exceptions in Spring MVC Framework.
6 Spring 3.0 MVC with Hibernate 3.0 CRUD Example
Learn how to configure Spring 3 MVC with Hibernate 3 in Spring MVC Framework.
7 Spring 3 MVC Tiles Plugin with Example
Learn how to configure Spring 3 MVC with Tiles configuration with example.
8 Spring 3 MVC Interceptor with example
Learn how to configure Spring 3 MVC with Interceptor configuration with example.
9 Spring 3 MVC Internationalization & Localization with Example
In this part we will discuss about Internationalization (I18N) and Localization (L10N) in Spring 3.0 MVC.
10 How to write RESTful Web Services using Spring 3.0 MVC
How to write RESTful Web Services using Spring 3.0 MVC
11 Spring 3.0 MVC with MongoDB CRUD Example
This is the CRUD application using the NoSQL database with Spring 3.0 MVC.
12 Spring CRUD Example using One to One Mapping of Two Tables
This is the CRUD application using the One to One Mapping in two tables of database with Spring 3.0 MVC.
13 Spring CRUD Example using Many to One Mapping
This is the CRUD application using the Many to One Mapping in three tables of database with Spring 3.0 MVC.
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago