Spring MVC Tutorial

Welcome to lesson 10 of the advanced Java Tutorial, which is a part of the Java Certification Training Course. In this lesson, we'll talk about Spring MVC (Model View Controller).

Objectives

By the end of this lesson on Java Spring MVC, you’ll be able to:

  • Explain the spring MVC architecture and components

  • Discuss the Spring MVC Framework

  • List the steps to write Spring MVC program in Eclipse

Let us start with Spring MVC architecture and components in the next section.

Spring MVC Architecture and Components

The problems in Enterprise Application development with Servlet and JSP Technology are:

  • Servlet and code are not reusable

  • Web designing tools can’t be used in the case of the servlet.

  • Parallel development is not possible

To solve the above problems, SUN microsystem introduced two design patterns for developing enterprise applications:

  1. Model 1 (page-centric model) and

  2. Model 2 (MVC)

In the next section, let us explore Model 1 - Page Centric Model.

Model 1 - Page Centric Model

The following image shows the architecture of Page Centric Model.

Here we have a request coming into the jsp page. The request is forwarded to the JavaBean so that the object can be created.

JavaBean connects to the Enterprise Server/Data Source and then the response is generated to the plaza.

Page Centric Model - Workflow

  1. The request is sent by the browser and received by JSP

  2. Java bean object is created and business methods are called. If required, It communicates with the databases to get the required data.

  3. JSP then displays the processed data to the end user

Page Centric Model - Limitations

The limitations of Page Centric Model include:

  • There is no clear separation of responsibilities

  • JSP acts as both controller and view

  • The business logic is separated using Java Bean

Model 2 - Spring MVC Model

The following image shows the architecture of the Spring MVC Model:

Here you can see that the request comes to the servlet which accesses the controller, the servlet can actually connect to the model Java Bean, which maps to the data source using ORM like hibernate.

That content can be directly pushed into the JSP as well, in case there is no data.

And it can then go to the model bean and retrieve data from the database via the jsp as well.

Finally the response is sent to the browser.

Spring MVC Model - Workflow

  1. The controller or Servlet receives requests from the browser and captures the input

  2. Controller invokes the business method of the model or java bean

  3. Model connects with the database and gets business data

  4. Model sends the response to the controller (keeps the process data in heap memory request, session, and Servlet context)

  5. Controllers switch the control to appropriate view of the application

Spring MVC Model - Limitations

The limitations of the MVC model include:

  • Clear separation of responsibilities

  • Code reusability

  • Single point entry for the application

  • Support for multiple view technologies

Advantages of Spring MVC

Spring MVC is used to develop the web application that uses the MVC design pattern. Spring MVC is meant to make web application development faster, cost-effective, and flexible.

Spring MVC - Components

The components of spring MVC are as follows:

  • DispatcherServlet (org.springframework.web.servlet)

  • HandlerMapping (org.springframework.web.servlet)

  • Controller

  • ModeAndView (org.springframework.web.servlet)

  • ViewResolver

DispatcherServlet

DispatcherServlet is given by org.springframework.web.DispatcherServlet. It follows the FrontController design pattern. Whatever URL comes from the Client, Servlet intercepts the Client Request before passing the Request object to the Controller.

In the web configuration file, write <servlet-mapping> in such a way that Dispatcher Servlet is invoked for ClientRequest.

<servet>
<servlet-name> front-controller</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> front-controller </servlet-name>
<url-pattern>*.extensionname</url-pattern>
</servlet-mapping>

HandlerMapping

HandlerMapping is an interface implemented by objects to define the mapping between request and handler objects. When a request is made to Spring’s dispatcher servlet, it hands over the request to handler mapping.

Handler mapping inspects the request, identifies the appropriate handler execution chain, and delivers it to DispatcherServlet.

Example:

Handler mapping provided by Spring’s MVC module can be implemented in many ways.

Let us consider an example -

BeanNameUrlHandlerMapping: It is the default handler mapping class that maps the URL request to the names of the beans.

<bean…>
<bean class=“org.springframework.web.servlet.handler.
BeanNameUrlHandlerMapping”/>
<bean name=“/welcome.htm” class=“WelcomeController”/>
<bean name=“/streetName.htm” class=“StreetNameController”/>
<bean name=“/process*.htm” class=“ProcessController”/>

If URL pattern:

  • /welcome.htm is requested; DispatcherServlet will forward the request to the “WelcomeController”

  • /streetname.htm is requested; DispatcherServlet will forward the request to the “StreetNameController”

  • /processCreditCard.htm or /process(anything).htm is requested; DispatcherServlet will forward the request to the “ProcessController”

Controllers

Controllers are components that are called by the Dispatcher Servlet for any kind of Business logic. All controllers implement the Controller interface.

The types of controllers are:

  • Abstract Controller

  • MultiAction Controller

  • AbstractWizardFormController

There are components called ViewResolver. Their job is to provide a mapping between Logical View Name and the actual Physical Location of the View Resource.

ModelAndView

The ModelAndView is represented by class.org.springframework.web.servlet.ModelAndView and is returned by the Controller object back to the DispatcherServlet.

This class is just a container class for holding the model and the view information. The model object represents some piece of information that can be used by the View to display the information.

These give abstraction in the Spring framework. Any kind of View Technology (org.springframework.web.servlet.View) can be plugged into the framework.

Excel, Jasper Reports, Pdf, Xslt, freeMarker, Html, Tiles are supported frameworks.

Example:

ModelAndView mv=new ModelAndView(“successView”, “greetingMsg”, “greetingMessage);

View Resolver

ViewResolver is an interface implemented by objects to resolve views using name.Spring’s MVC module. It encapsulates the model object and the view object in a single entity, which is represented by the object of class ModelAndView.

To resolve the view object, DispatcherServlet ViewResolver is used.

Types of ViewResolver

InternalResourceViewResolver

It resolves the logical name of the view to an internal resource by prefixing the logical view name with the resource path and suffixing it with the extension.

BeanNameViewResolver

It resolves the logical name of the view to the bean name, which will render the output to the user. The bean should be defined in the Spring app context file.

XMLFileViewResolver

This View Resolver is the same as BeanNameViewResolver. The only difference is that instead of looking for the beans in Spring’s application context file, it looks for beans defined in a separate XML file.

What Is Spring MVC Framework?

The Spring web MVC framework provides model-view-controller architecture that can be used to develop flexible and loosely coupled web applications.

Next, we see its workflow steps.

Workflow

The following image shows the Spring MVC Framework:

First, the request comes to the service dispatcher.

It goes to the HandlerMapping.

The HandlerMapping sends back to the respective DispatcherServlet that acts as the controller.

We then call the handlerRequest method on the controller, which calls the business methods on the Service.

The Service then calls the DAO method, which talks to the database and gets the response.

The response is sent to the service and then back to the controller.

It is then sent back to the Servlet Dispatcher, which forwards it to the ViewResolver, so the right view can be returned to the ServletDispatcher. The ServletDispatcher then picks up the model and attaches it to the view and generates the response.

The process given above can be clearly stated in the following 16 steps:

  1. The client requests a resource in the Web Application.

  2. The Spring Front Controller (DispatcherServlet) requests the HandlerMapping to identify the particular controller for the given URL.

  3. HandlerMapping identifies the controller and sends it to the DispatcherServlet.

  4. DispatcherServlet calls handleRequest method and passes these two objects to that controller.

  5. Controller calls the business method.

  6. Service class calls the DAO method for business data.

  7. DAO interacts with the database to get the data.

  8. Database shares the result.

  9. DAO returns this result data to service.

  10. DAO data is processed according to business requirement and returns to Controller.

  11. The Controller returns ModelAndView object back to front Controller.

  12. Dispatcher resolves actual View by consulting the View Resolver object.

  13. ViewResolver renders View to the Dispatcher.

  14. DispatcherServlet consults the View to the DispatcherServlet.

  15. View executes and returns HTML to the DispatcherServlet.

  16. DispatcherServlet sends outputs the browser.

Spring Web MVC DispatcherServlet Workflow

The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram:

The handler mapping going to the DispatcherServlet.

Second is the controller data exchange with the DispatcherServlet.

Then it communicates with the view resolver and finally, the View and the response is sent out.

Description

After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.

The Controller takes the request and calls the appropriate service method based on used GET or POST method. The service method will set model data based on defined business logic and return view name to the DispatcherServlet.

The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request.

Once the view is finalized, the DispatcherServlet passes the model data to the view; this is finally rendered on the browser.

Configurations required for Spring MVC

The configurations required for Spring MVC are discussed below:

Map Requests

Map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file.

Use the following code to declare and map Helloweb DispatcherServlet. The web.xml file will be kept in WebContent/WEB-INF directory.

Create [servlet-name]-servlet.xml file

The framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application’s WebContent/WEB-INF-directory. The file0 name is HelloWeb.xml.

The [servlet-name]-servlet.xml file will be used to create the defined beans, overriding the definitions of beans with the same name in the global scope.

The <context:component-scan…> tag will be used to activate Spring MVC annotation scanning capability, which allows you to make use of annotations like @Controller and @RequestMapping.

The internalResourceViewResolver will have rules defined to resolve the view names.

Define A Controller

The @Control 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.

@RequestMapping(method = RequestMethod.GET) is used to declare the printHello() method as the controller's defaults service method to handle HTTP GET requests,

Create view

Spring MVC supports many types of views for different presentation technologies. These include JSP, HTML, Pdf, Excel Worksheet, XML, Velocity template, XSLT, JSON, view in/ WEB-INF/

Spring MVC Program

Let's write a simple web-based application using Spring MVC framework and create a Spring MVC model to display ‘Hello World.’

Spring Web MVC DispatcherServlet WorkFlow for Hello World Example

So the request will come in here, say, hello.jsp

We will use @RequestMapping. Then the DispatcherServlet will communicate with the HelloController. Then the InternalResourceViewResolver, and finally the hello.jsp which will generate the response.

The Hello World example uses Spring MVC framework and follows the Model-View-Controller(MVC) architecture:

The controller is responsible for processing user request and building an appropriate model. It then passes the model to the view for rendering. In this example, HelloController.java class is the controller.

The view is responsible for rendering the model data. In general, it generates HTML output that the client’s browser can interpret.

In this example, hello.jsp is the View.

Steps To Write A web-based Application Using Spring MVC

The steps to write a web-based application using Spring MVC are discussed below:

  1. We create a Dynamic Web Project with the name HelloWeb.

  2. Then add the jar file to WebContent/WEB-INF/lib

  3. Create a java class HelloController under src folder

  4. Create spring configuration files web.xml and HelloWebServlet.xml under the WebContent/WEB-INF folder.

  5. Create a sub-folder with a name jsp under the WebContent/WEB-INF folder. Create a view file hello.jsp under this sub-folder.

  6. The final step is to create the content for all the source and configuration files and export the application.

Step - 1

We create a dynamic web project that we have also learned previously.

Step - 2

We add the following jar files to our project:

Servlet-api-x.y.z.jar

Commons-logging-x.y.z.jar

Spring-aop-x.y.z.jar

Spring-beans-x.y.z.jar

Spring-context-x.y.z.jar

Spring-core-x.y.z.jar

Spring-expression-x.y.z.jar

Spring-webmvc-x.y.z.jar

Spring-web-x.y.z.jar

Step - 3

then we write the @Controller and RequestMapping(“/hello”)

We write the Controller with the request method as get and we say model.addAttribute(“message”, “Hello Spring MVC framework!”);

Step - 4

Then we create the spring config file that maps the DispatcherServlet object and the helloWeb. Then we map the spring framework internalResourceViewResolver as well and we put the WEB-INF/jsp property map to that particular folder path.

Step - 5

Then we create the subfolder with a view hello.jsp which simply returns hello world and $(message) expression

Step - 6

To run the application, you have to write the following URL as HTTP request:

http://localhost:8080/HelloWeb/hello

Form Handling Example

We'll write a simple web-based application that makes use of HTML form using Spring Web MVC framework to submit the data to the controller and display a processed resulted.

Workflow

So the moment we say project name/employee, it will go to the DispatcherServlet. DispatcherServlet will talk to the EmployeeController, retrieve the employee object, move to the InternalResourceViewResolver which picks up the result.jsp and employee.jsp views and sent it out as an HTTP response.

MVC Architecture for Form Handling Example

The form handling example uses Spring web MVC framework. It follows the Model-View-Controller (MVC) architecture:

The model encapsulates the application data and consists of POJO.

It creates Employee class containing id, name in each

The controller is responsible for processing user requests, building an appropriate model, and passes it to the view for rendering

Creates an EmployeeController.java class to call Employee class methods.

The view is responsible for rendering the model data and in general it generates HTML output that the client’s browser can interpret.

java.jsp files, result.jsp and employee.jsp are used to display Employee’s information.

Steps To Write A web-based Application Using Spring MVC

The steps to write a web-based application using Spring MVC are discussed below:

  1. Create a dynamic web project and add the required jar files

  2. Map the requests that you want the DispatcherServlet to handle by using URL mapping in the web.xml file.

  3. Create the java class ‘Employee’

  4. Create EmployeeController in the src folder

  5. Create Spring configuration files Web.xml and servlet.xml under the WebContent/WEB-INF folder

  6. Create a sub-folder with a name jsp under the WebContent/WEB-INF folder. Create view file employee.jsp

  7. Create second view file result.jsp

  8. The final step is to create the content of all the source and configuration files and export the application.

Step - 1

We create a dynamic web project and add the required jar files.

The list of jar files is shown below:

  • Commons-logging-x.y.z.jar

  • org.springframework.asm-x.y.z.jar

  • Org.springframework.beans-x.y.z.jar

  • Org.springframework.context-x.y.z.jar

  • Org.springframework.core-x.y.z.jar

  • Org.springframework.expression-x.y.z.jar

  • Org.springframework.web.servlet-x.y.z.jar

  • Org.springframework.web-x.y.z.jar

  • spring-web.jar

Step - 2

We then define the Spring Web configuration file web.xml where we set up the DispatcherServlet. We give the servlet name as HelloWeb.

Step - 3

We then set up the Employee class with age, name, and id.

Step - 4

We then create the controller with a RequestMapping of a url/employee and map to a Request.GET method.

We then return ModelAndView with the employee and command and the new Employees object. We then do another mapping for the RequestMethod.POST. This is from the form data to be posted. We provide the addEmployee method and add attribute mappings for name, age, and id.

Step - 5

Next, we create a spring configuration file Web.xml and servlet.xml which maps the jsp page.

Step - 6

Then we create a sub-folder in a view which maps the view information as an employee.jsp file where we create a simple table to print out the data.

Step - 7

We create a second view called result.jsp which has a separate table that this gives us the name, age, and id of the employee. We create content for all the source and configuration files and run the application.

Summary

The key takeaways from this lesson have been:

Spring MVC is used to develop the web application that uses the MVC design pattern. Spring MVC is used to make web application development faster, cost-effective and flexible.

DispatcherServlet, HandlerMapping, Controller, ModelAndView, and ViewResolver are the components of spring MVC.

Find our Java Certification Training Online Classroom training classes in top cities:


Name Date Place
Java Certification Training 12 Oct -24 Nov 2019, Weekend batch Your City View Details
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Name*
Email*
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Email*
Phone Number*
Company*
Job Title*