SlideShare a Scribd company logo
Spring MVC
An Introduction
This lesson will cover the following:
- Understanding the SpringWeb Model View Controller
- Multiple View Page
- Multiple Controller
- Model Interface
- Request Param Annotation
- A spring MVC is a Java Framework used to build web applications.
- Spring MVC complies to the Model-View-Controller design pattern.
- It therefore implements all the basic features of a core spring framework,
including Dependency injection, inversion of control, etc.
- The Spring MVC components can be used to develop flexible and loosely
coupled web applications.
- The spring MVC architecture aids in separating the different aspects of the
application, i.e. input logic, UI logic and business logic - at the same time
providing a loose coupling between these elements.
- This is the core idea of the MVC pattern - to separate business logic from UIs
and allow them to change independently without affecting each other.
- A spring MVC is a good way of using MVC in spring framework.
- This is achievable with the help of the DispatcherServlet, which receives
incoming requests and maps it to the right resources, including models,
controllers, and views.
I - Understanding the SpringWeb
Model View Controller
We shall start by defining the three terms: model, controller and view:
1. Model - The model houses the application data. Data can be either a single
object or a collection of objects
2. Controller - The controller defines the application’s business logic. It processes
user requests and builds an appropriate model, which it then passes to the view for
rendering.
3. View - The view is used to represent the provided information in a specific
format.
- In other words, it is used to render the model data to generate HTML output
that can be interpreted by the client’s browser.
- The view technologies supported by Spring MVC include JSP + JSTL, Apache
Velocity, FreeMaker, Thymeleaf
4. Front Controller - The above mentioned DispatcherServlet class functions as the
front controller.
- It manages the flow of the Spring MVC application. It handles all HTTP requests
and responses.
The figure below represents the MVC model
Another diagramatic representation of the request processing workflow is
presented below:
Below is yet another visual representation of the request processing workflow
in Spring Web MVC:
Understanding the flow of Spring
Web MVC
Below is a visual representation of how work flows in Spring Web MVC
Notes:
- The DispatcherServlet is the front controller. It intercepts all incoming requests
- The DispatcherServlet forwards the request to the controller, by help of the entry
of handler mapping from the XML file.
- The controller takes the requests and invokes the appropriate service methods
based on used GET or POST method.
- The service method will set model data based on defined business logic and
returns an object of ModelAndView
- The DispatcherServlet assesses the view resolver and calls the specified view
component
Advantages of Spring MVC
Framework
What are the advantages of Spring MVC Framework?
1. Clear separation of roles - The Spring MVC is able to divide each role, and thus
the model object, DispatcherServlet, Controller, view resolver, and validator can be
accomplished by a specialized object.
2. Light-weight - Spring MVC uses light-weight servlet container to develop and
deploy your application.
3. Powerful and straight forward configuration - Spring MVC offers a powerful
configuration for both application and framework across contexts, for example,
from web controllers to business objects and validators.
4. Adaptability, non-intrusiveness and flexibility - Spring MVC allows you to
define any controller method signature you need. You can use any of the
parameter annotations such as @RequestParam, @RequestHeader, @PathVariable,
etc.
5. Rapid development - Spring MVC greatly improves the speed of development.
6. Reusable business code - Spring MVC allows us to use the existing business
objects, as opposed to creating new objects, or mirroring them to extend a
particular framework base class.
7. Easy to test - Testing is made simpler in Spring MVC by creation of JavaBeans
classes which enable you to inject test data using the setter methods
8. Flexible Mapping - Spring MVC details particular annotations which redirect the
page easily
9. Flexible model transfer - Spring MVC supports model transfers with a
name/value Map , which is easily integrated with any view technology.
10. Customizable binding and validation - Spring MVC allows type mismatches
such as application-level validation errors, which keep the offending value,
localized date and number binding, instead of String-only form objects with
manual parsing and conversion to business objects.
Tools needed for the tutorials
● We will now move to a number of Spring MVC tutorials. Below is a list of
the tools we will use for these tutorials. Ensure all students have
downloaded and installed these on their PCs.
● Tomcat 9.0.20 - Download the latest Apache Tomcat from here.
● Eclipse IDE 2019-03 for Java - You can download the latest Eclipse IDE
from here.
● Spring 5.1.7 - We shall use Maven dependency for this. You can check
out the latest Spring MVC versions from this Maven Repository.
● Java SE 12.0.1 - Download the latest version from here.
Getting the project skeleton
structure ready
● Since this is a web application, we will use maven for dependencies
management.
● We will first create a dynamic web application and then convert it to a
maven project.
Step 1
● Right click on the project explorer window and click on “New - Dynamic
Web Project” as shown in the screenshot below:
3. Spring MVC Intro - PowerPoint Presentation (1).pptx
Step 2
Provide the name as “springmvcexample” in
the page that pops up. You don’t have to
change the rest of the fields.
Step 3
On the next page,
provide the source
folder as “src”
Step 4
● Next is the web page module
● Provide the context root of application as “springmvcexample”
● Check the “generate web.xml deployment descriptor” option.
● Click on Finish - you now have a new Dynamic Web Project in your eclipse
project explorer.
Step 5
● Convert the dynamic web project to maven project
● We will use maven for easy management of our spring MVC
dependencies.
● To convert our web project to maven, first right click on the project and
select “Configure - Convert to Maven Project”
3. Spring MVC Intro - PowerPoint Presentation (1).pptx
Step 6
- Provide the
pom.xml
configurations as
shown below.
Our maven web
application project
skeleton code is now
ready.
- The next step is
to make changes
to the files within
the directory to
create various
applications.
Activity 1
Spring MVC Hello World Example
- The first activity in this lesson will be on creating a simple employee management
application.
- This will have only one feature, i.e. the list of all available employees in a given
institution.
- The directory structure for this application will look as follows:
3. Spring MVC Intro - PowerPoint Presentation (1).pptx
- The next steps will detail the contents of all the files involved in the hello world
application.
- These are detailed below, with a brief description of each of the files:
Step 1
Pom.xml
- This file contains dependencies for spring mvc and taglibs support for writing
jsp files.
- Open the Pom.xml file located in the target folder. Ensure the contents of the
pom.xml file are correct.
Step 2
Web.xml
- This file declares one servlet to receive all kinds of requests.
- The DispatcherServlet will herein act as a front controller
- On the project explorer window, go to Settings -- src -- main -- webapp -- WEB-INF
-- views.
- Open the web.xml file. Configure DispatcherServlet in web.xml correctly.
Step 3
Spring-servlet.xml
- We shall use annotated classes at request handler, service and dao layer.
- Thus the annotation processing for all class files is enabled in the base package
“com.howtodoinjava.demo”
- Under the project explorer window, go to settings -- src -- main -- webapp -- WEB-
INF -- views.
- Fill the spring bean configuration file spring-servlet.xml with the correct content
as provided in the project folder.
Notes
● In this spring-servlet.xml file, we have 3 important configurations
● Annotation-driven - this tells DispatcherServlet to look for Controller
classes using @Controller annotation
● Context:component-scan - this tells DispatcherServlet where to look for
controller classes
● InternalResourceViewResolver bean configuration - this specifies the
location of view pages and suffix used. Controller class methods return
name of the view page and then suffix is added to figure out the view
page to use for rendering the response.
Step 4
EmployerController.java
- Under the project explorer window, go to settings -- src - main - java - com -
howtodoinjava - demo - controller. We have a single controller class here.
- This file contains the annotation @RequestMapping at class level and method
level, which determine the URL at which the method will be called.
- Ensure the contents of the file are as provided:
Step 5
EmployeeVO.java
- Under the project explorer window, go to settings -- src - main - java - com -
howtodoinjava - demo - model.
- Here you find the Spring MVC model class.
- This class acts as the model for the MVC pattern. The contents of this file
should be as follows.
Step 6
EmployeeDAOImpl.java
Step 6 - EmployeeDAO.java
● Go to settings -- src -- main -- java -- com -- howtodoinjava -- demo -- dao.
● This folder contains the data access object files.
● DAO is a design pattern in which a DAO is an object that provides an abstract
interface to some type of database or other persistence mechanisms.
● By mapping application calls to the persistent layer, DAOs provide some
specific data operations without exposing details of the database.
● Ensure the contents of the EmployeeDAO.java file are as provided.
Step 7
EmployeeDAOImpl.java
- Under the same DAO folder, open the EmployeeDAOImpl.java file.
- This is basically used for implementation of the file in the previous step.
The contents of the file should look as follows.
Step 8
EmployerManager.java
● Under the project explorer window, go to settings -- src -- main -- java -- com --
howtodoinjava -- demo -- service.
● This folder represents the service layer of spring mvc.
● The service layer provides logic to operate on the data sent to and from the
DAO and the client.
● Very often, these 2 pieces will be bundled together into the same module, and
occasionally into the same code, but you will still see them as distinct logical
entities.
● The service layer provides separation of concern, provides security, and
provides loose coupling.
● Ensure the contents of the EmployerManager.java file are as provided.
Step 9
EmployeeManagerImpl.java
- Under the same Service folder in Step 8 above, we have the
EmployeeManagerImpl.java file.
- This basically implements what we have in the EmployeeManager.java file.
- Ensure the contents of the EmployerManagerImpl.java are as provided.
Step 10
employeesListDisplay.jsp
- This file is used to display all employees in the system.
- It prints the employee details in a table in an iterative manner.
- This is the view layer of the MVC architecture.
- Under the project explorer window, go to settings -- src -- main -- webapp --
WEB-INF -- views. Open the employeesListDisplay.jsp file.
- Ensure the contents of the employeesListDisplay.jsp are as provided.
Step 11
- The final step is to use Eclipse export as WAR file option to deploy it
directly to any running tomcat server webapps directory.
- Below is a screenshot of the steps to follow when exporting.
3. Spring MVC Intro - PowerPoint Presentation (1).pptx
3. Spring MVC Intro - PowerPoint Presentation (1).pptx
Step 11
Once the spring mvc project is deployed, we can access the home page at this URL:
http://localhost:8080/springmvcexample/employee-module/getAllEmployees
Expected Results
II - Spring Web MVC Framework
Example
Outlined below are the steps of a simple example of a Spring MVC framework.
- Load the spring jar files
- Create the controller class
- Provide the entry of controller in the web.xml file
- Define the bean in a separate XML file
- Display the message in the JSP page
- Start the server and deploy the project
Directory Structure of Spring MVC
The screenshot below shows the directory structure of Spring MVC
Required Jar files or Maven
Dependency
The execution of the following examples will require the following:
- Spring Core jar files
- Spring Web jar files
- JSP + JSTL jar files - you can load other jar files depending on the view
technology you are using
Activity 2
Step 1
- Provide project information and configuration in the pom.xml file
- The contents of this file are provided in a seperate folder
Step 2
Create the controller class
We will use two annotations to create the controller class:
1. @Controller annotation - this marks this class as Controller
2. @RequestMapping - this maps the class with the specified URL name
Step 3
Provide the entry of controller in
the web.xml file
- Here we’re specifying the servlet class DispatcherServlet.
- As earlier mentioned, this acts as the front controller in Spring Web MVC.
- It intercepts all the incoming request for the html file.
- The xml file will be used to create the beans defined, and override the
definitions of any beans defined with the same name in the global scope.
Step 4
Define the bean in the xml file
- The view components are specified in this configuration file.
- This xml file should be located within the WEB-INF folder.
- The context:component-scan element defines the base-package where
DispatcherServlet searches the controller class.
Step 5
Display the message in the JSP page
- Spring MVC supports several types of views for different presentation
technologies.
- Examples are: JSPs, PDF, HTML, XML, Excel worksheets, velocity templates,
XSLT, JSON, JasperReports, Atom and RSS feeds.
- The most common of all these is a JSP template written with JSTL (Java
Standard Tag Library).
- The JSP page displays the message returned by the Controller
Index.jsp
<html>
<body>
<p>Welcome to Spring MVC Tutorial</p>
</body>
</html>
What output do you get?
III - Spring MVC Multiple View page
Example
In this example, we will redirect a view page to another view page
Outlined below are the steps to follow:
1. Load the spring jar files
2. Create the controller class
3. Provide the entry of controller in the web.xml file
4. Define the bean in the separate XML file
5. Create the other view components
6. Start the server and deploy the project
Directory Structure of Spring MVC
IV - Spring MVC Multiple Controller
Example
-Spring MVC allows us to create multiple controller at a time.
-Each controller class should be matched with @Controller annotation.
- We shall go step by step through an example of Spring MVC with multiple
controllers.
- Outlined below are the main steps we shall follow:
1. Load the spring jar files
2. Create the controller class
3. Provide the entry controller in the web.xml file
4. Create the other view components
5. Start the server - Deploy the project
3. Spring MVC Intro - PowerPoint Presentation (1).pptx
V - Spring MVC Model Interface
-As defined earlier on, the model works as a container that contains the data of the
application.
-This data can be in the form of objects, strings, or information from the database,
among many others.
-The Model Interface should be placed in the controller part of the application. -
HttpServletRequest reads the information provided by the user and passes it to the
Model interface.
-The viewpage then accesses the data from the model part.
-Methods of Model Interface
-Outlined below are the various methods of model interface
1. Model addAllAttributes(Collection</>arg) - this adds all the attributes in the
provided Collection into this Map
2. Model addAllAttributes(Map<String,?> arg) - this adds all the attributes in the
provided Map into this Map
3. Model addAllAttribute(Object arg) - this adds the provided attribute to this
Map using a generated name
4. Model addAllAttribute(String arg0, Object arg1) - this binds the attribute with
the provided name
5. Map<String, Object> asMap() - this returns the current set of model attributes
as a Map
6. Model mergeAttributes(Map<String,?> arg) - this adds all attributes in the
provided Map into this Map, with existing objects of the same name taking
precedence.
7. Boolean containsAttribute(String arg) - this indicates if this model contains an
attribute of the given name
VI - Spring MVC RequestParam
Annotation
- The @RequestParam annotation basically reads the form data and
automatically binds it to the parameter present in the provided method.
- It does not consider the requirement of HttpServletRequest object to read the
provided data.
- The @RequestParam annotation also maps the request parameter to query
parameter as well as parts in multipart requests.
- In case the method parameter type is defined as Map, and a specific request
parameter name is given, the request parameter value will be converted to a
Map, otherwise the map parameter will be populated with all request
parameter names and values.

More Related Content

PPTX
Spring Framework
PDF
Asp 1a-aspnetmvc
PDF
Aspnetmvc 1
PDF
Spring mvc 2.0
PDF
Spring mvc
PDF
IRJET- Lightweight MVC Framework in PHP
PPTX
Spring MVC 5 & Hibernate 5 Integration
ODP
springmvc-150923124312-lva1-app6892
Spring Framework
Asp 1a-aspnetmvc
Aspnetmvc 1
Spring mvc 2.0
Spring mvc
IRJET- Lightweight MVC Framework in PHP
Spring MVC 5 & Hibernate 5 Integration
springmvc-150923124312-lva1-app6892

Similar to 3. Spring MVC Intro - PowerPoint Presentation (1).pptx (20)

ODP
Java Spring MVC Framework with AngularJS by Google and HTML5
PDF
Jinal desai .net
PPTX
Spring MVC framework features and concepts
PPTX
ASP.NET Presentation
PDF
Spring MVC Framework
DOCX
Month 2 report
PPTX
MVC & backbone.js
DOCX
A report on mvc using the information
PPTX
Asp.net With mvc handson
PPTX
MVC Framework
PDF
Spring Framework-II
PPTX
Session 1
PPTX
Mvc Brief Overview
PDF
ASP.Net | Sabin Saleem
PPTX
Jsp and Servlets
PPTX
Spring Web Presentation 123143242341234234
PDF
PDF
Spring MVC
PDF
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
PPTX
Technoligent providing custom ASP.NET MVC development services
Java Spring MVC Framework with AngularJS by Google and HTML5
Jinal desai .net
Spring MVC framework features and concepts
ASP.NET Presentation
Spring MVC Framework
Month 2 report
MVC & backbone.js
A report on mvc using the information
Asp.net With mvc handson
MVC Framework
Spring Framework-II
Session 1
Mvc Brief Overview
ASP.Net | Sabin Saleem
Jsp and Servlets
Spring Web Presentation 123143242341234234
Spring MVC
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
Technoligent providing custom ASP.NET MVC development services
Ad

Recently uploaded (20)

PPTX
Fundamentals of Mechanical Engineering.pptx
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PPTX
communication and presentation skills 01
PDF
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
PPT
A5_DistSysCh1.ppt_INTRODUCTION TO DISTRIBUTED SYSTEMS
PDF
86236642-Electric-Loco-Shed.pdf jfkduklg
PPTX
Safety Seminar civil to be ensured for safe working.
PPT
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
PDF
III.4.1.2_The_Space_Environment.p pdffdf
PPTX
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PPTX
Current and future trends in Computer Vision.pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PPTX
Artificial Intelligence
PPTX
introduction to high performance computing
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
737-MAX_SRG.pdf student reference guides
Fundamentals of Mechanical Engineering.pptx
Categorization of Factors Affecting Classification Algorithms Selection
communication and presentation skills 01
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
A5_DistSysCh1.ppt_INTRODUCTION TO DISTRIBUTED SYSTEMS
86236642-Electric-Loco-Shed.pdf jfkduklg
Safety Seminar civil to be ensured for safe working.
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
III.4.1.2_The_Space_Environment.p pdffdf
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
Fundamentals of safety and accident prevention -final (1).pptx
Current and future trends in Computer Vision.pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
Artificial Intelligence
introduction to high performance computing
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
737-MAX_SRG.pdf student reference guides
Ad

3. Spring MVC Intro - PowerPoint Presentation (1).pptx

  • 2. An Introduction This lesson will cover the following: - Understanding the SpringWeb Model View Controller - Multiple View Page - Multiple Controller - Model Interface - Request Param Annotation
  • 3. - A spring MVC is a Java Framework used to build web applications. - Spring MVC complies to the Model-View-Controller design pattern. - It therefore implements all the basic features of a core spring framework, including Dependency injection, inversion of control, etc. - The Spring MVC components can be used to develop flexible and loosely coupled web applications. - The spring MVC architecture aids in separating the different aspects of the application, i.e. input logic, UI logic and business logic - at the same time providing a loose coupling between these elements.
  • 4. - This is the core idea of the MVC pattern - to separate business logic from UIs and allow them to change independently without affecting each other. - A spring MVC is a good way of using MVC in spring framework. - This is achievable with the help of the DispatcherServlet, which receives incoming requests and maps it to the right resources, including models, controllers, and views.
  • 5. I - Understanding the SpringWeb Model View Controller We shall start by defining the three terms: model, controller and view: 1. Model - The model houses the application data. Data can be either a single object or a collection of objects 2. Controller - The controller defines the application’s business logic. It processes user requests and builds an appropriate model, which it then passes to the view for rendering.
  • 6. 3. View - The view is used to represent the provided information in a specific format. - In other words, it is used to render the model data to generate HTML output that can be interpreted by the client’s browser. - The view technologies supported by Spring MVC include JSP + JSTL, Apache Velocity, FreeMaker, Thymeleaf 4. Front Controller - The above mentioned DispatcherServlet class functions as the front controller. - It manages the flow of the Spring MVC application. It handles all HTTP requests and responses.
  • 7. The figure below represents the MVC model
  • 8. Another diagramatic representation of the request processing workflow is presented below:
  • 9. Below is yet another visual representation of the request processing workflow in Spring Web MVC:
  • 10. Understanding the flow of Spring Web MVC Below is a visual representation of how work flows in Spring Web MVC
  • 11. Notes: - The DispatcherServlet is the front controller. It intercepts all incoming requests - The DispatcherServlet forwards the request to the controller, by help of the entry of handler mapping from the XML file. - The controller takes the requests and invokes the appropriate service methods based on used GET or POST method. - The service method will set model data based on defined business logic and returns an object of ModelAndView - The DispatcherServlet assesses the view resolver and calls the specified view component
  • 12. Advantages of Spring MVC Framework What are the advantages of Spring MVC Framework? 1. Clear separation of roles - The Spring MVC is able to divide each role, and thus the model object, DispatcherServlet, Controller, view resolver, and validator can be accomplished by a specialized object. 2. Light-weight - Spring MVC uses light-weight servlet container to develop and deploy your application. 3. Powerful and straight forward configuration - Spring MVC offers a powerful configuration for both application and framework across contexts, for example, from web controllers to business objects and validators.
  • 13. 4. Adaptability, non-intrusiveness and flexibility - Spring MVC allows you to define any controller method signature you need. You can use any of the parameter annotations such as @RequestParam, @RequestHeader, @PathVariable, etc. 5. Rapid development - Spring MVC greatly improves the speed of development. 6. Reusable business code - Spring MVC allows us to use the existing business objects, as opposed to creating new objects, or mirroring them to extend a particular framework base class. 7. Easy to test - Testing is made simpler in Spring MVC by creation of JavaBeans classes which enable you to inject test data using the setter methods 8. Flexible Mapping - Spring MVC details particular annotations which redirect the page easily
  • 14. 9. Flexible model transfer - Spring MVC supports model transfers with a name/value Map , which is easily integrated with any view technology. 10. Customizable binding and validation - Spring MVC allows type mismatches such as application-level validation errors, which keep the offending value, localized date and number binding, instead of String-only form objects with manual parsing and conversion to business objects.
  • 15. Tools needed for the tutorials ● We will now move to a number of Spring MVC tutorials. Below is a list of the tools we will use for these tutorials. Ensure all students have downloaded and installed these on their PCs. ● Tomcat 9.0.20 - Download the latest Apache Tomcat from here. ● Eclipse IDE 2019-03 for Java - You can download the latest Eclipse IDE from here. ● Spring 5.1.7 - We shall use Maven dependency for this. You can check out the latest Spring MVC versions from this Maven Repository. ● Java SE 12.0.1 - Download the latest version from here.
  • 16. Getting the project skeleton structure ready ● Since this is a web application, we will use maven for dependencies management. ● We will first create a dynamic web application and then convert it to a maven project. Step 1 ● Right click on the project explorer window and click on “New - Dynamic Web Project” as shown in the screenshot below:
  • 18. Step 2 Provide the name as “springmvcexample” in the page that pops up. You don’t have to change the rest of the fields.
  • 19. Step 3 On the next page, provide the source folder as “src”
  • 20. Step 4 ● Next is the web page module ● Provide the context root of application as “springmvcexample” ● Check the “generate web.xml deployment descriptor” option. ● Click on Finish - you now have a new Dynamic Web Project in your eclipse project explorer. Step 5 ● Convert the dynamic web project to maven project ● We will use maven for easy management of our spring MVC dependencies. ● To convert our web project to maven, first right click on the project and select “Configure - Convert to Maven Project”
  • 22. Step 6 - Provide the pom.xml configurations as shown below. Our maven web application project skeleton code is now ready. - The next step is to make changes to the files within the directory to create various applications.
  • 23. Activity 1 Spring MVC Hello World Example - The first activity in this lesson will be on creating a simple employee management application. - This will have only one feature, i.e. the list of all available employees in a given institution. - The directory structure for this application will look as follows:
  • 25. - The next steps will detail the contents of all the files involved in the hello world application. - These are detailed below, with a brief description of each of the files:
  • 26. Step 1 Pom.xml - This file contains dependencies for spring mvc and taglibs support for writing jsp files. - Open the Pom.xml file located in the target folder. Ensure the contents of the pom.xml file are correct.
  • 27. Step 2 Web.xml - This file declares one servlet to receive all kinds of requests. - The DispatcherServlet will herein act as a front controller - On the project explorer window, go to Settings -- src -- main -- webapp -- WEB-INF -- views. - Open the web.xml file. Configure DispatcherServlet in web.xml correctly.
  • 28. Step 3 Spring-servlet.xml - We shall use annotated classes at request handler, service and dao layer. - Thus the annotation processing for all class files is enabled in the base package “com.howtodoinjava.demo” - Under the project explorer window, go to settings -- src -- main -- webapp -- WEB- INF -- views. - Fill the spring bean configuration file spring-servlet.xml with the correct content as provided in the project folder.
  • 29. Notes ● In this spring-servlet.xml file, we have 3 important configurations ● Annotation-driven - this tells DispatcherServlet to look for Controller classes using @Controller annotation ● Context:component-scan - this tells DispatcherServlet where to look for controller classes ● InternalResourceViewResolver bean configuration - this specifies the location of view pages and suffix used. Controller class methods return name of the view page and then suffix is added to figure out the view page to use for rendering the response.
  • 30. Step 4 EmployerController.java - Under the project explorer window, go to settings -- src - main - java - com - howtodoinjava - demo - controller. We have a single controller class here. - This file contains the annotation @RequestMapping at class level and method level, which determine the URL at which the method will be called. - Ensure the contents of the file are as provided:
  • 31. Step 5 EmployeeVO.java - Under the project explorer window, go to settings -- src - main - java - com - howtodoinjava - demo - model. - Here you find the Spring MVC model class. - This class acts as the model for the MVC pattern. The contents of this file should be as follows.
  • 32. Step 6 EmployeeDAOImpl.java Step 6 - EmployeeDAO.java ● Go to settings -- src -- main -- java -- com -- howtodoinjava -- demo -- dao. ● This folder contains the data access object files. ● DAO is a design pattern in which a DAO is an object that provides an abstract interface to some type of database or other persistence mechanisms. ● By mapping application calls to the persistent layer, DAOs provide some specific data operations without exposing details of the database. ● Ensure the contents of the EmployeeDAO.java file are as provided.
  • 33. Step 7 EmployeeDAOImpl.java - Under the same DAO folder, open the EmployeeDAOImpl.java file. - This is basically used for implementation of the file in the previous step. The contents of the file should look as follows.
  • 34. Step 8 EmployerManager.java ● Under the project explorer window, go to settings -- src -- main -- java -- com -- howtodoinjava -- demo -- service. ● This folder represents the service layer of spring mvc. ● The service layer provides logic to operate on the data sent to and from the DAO and the client. ● Very often, these 2 pieces will be bundled together into the same module, and occasionally into the same code, but you will still see them as distinct logical entities. ● The service layer provides separation of concern, provides security, and provides loose coupling. ● Ensure the contents of the EmployerManager.java file are as provided.
  • 35. Step 9 EmployeeManagerImpl.java - Under the same Service folder in Step 8 above, we have the EmployeeManagerImpl.java file. - This basically implements what we have in the EmployeeManager.java file. - Ensure the contents of the EmployerManagerImpl.java are as provided.
  • 36. Step 10 employeesListDisplay.jsp - This file is used to display all employees in the system. - It prints the employee details in a table in an iterative manner. - This is the view layer of the MVC architecture. - Under the project explorer window, go to settings -- src -- main -- webapp -- WEB-INF -- views. Open the employeesListDisplay.jsp file. - Ensure the contents of the employeesListDisplay.jsp are as provided.
  • 37. Step 11 - The final step is to use Eclipse export as WAR file option to deploy it directly to any running tomcat server webapps directory. - Below is a screenshot of the steps to follow when exporting.
  • 40. Step 11 Once the spring mvc project is deployed, we can access the home page at this URL: http://localhost:8080/springmvcexample/employee-module/getAllEmployees Expected Results
  • 41. II - Spring Web MVC Framework Example Outlined below are the steps of a simple example of a Spring MVC framework. - Load the spring jar files - Create the controller class - Provide the entry of controller in the web.xml file - Define the bean in a separate XML file - Display the message in the JSP page - Start the server and deploy the project
  • 42. Directory Structure of Spring MVC The screenshot below shows the directory structure of Spring MVC
  • 43. Required Jar files or Maven Dependency The execution of the following examples will require the following: - Spring Core jar files - Spring Web jar files - JSP + JSTL jar files - you can load other jar files depending on the view technology you are using
  • 44. Activity 2 Step 1 - Provide project information and configuration in the pom.xml file - The contents of this file are provided in a seperate folder
  • 45. Step 2 Create the controller class We will use two annotations to create the controller class: 1. @Controller annotation - this marks this class as Controller 2. @RequestMapping - this maps the class with the specified URL name
  • 46. Step 3 Provide the entry of controller in the web.xml file - Here we’re specifying the servlet class DispatcherServlet. - As earlier mentioned, this acts as the front controller in Spring Web MVC. - It intercepts all the incoming request for the html file. - The xml file will be used to create the beans defined, and override the definitions of any beans defined with the same name in the global scope.
  • 47. Step 4 Define the bean in the xml file - The view components are specified in this configuration file. - This xml file should be located within the WEB-INF folder. - The context:component-scan element defines the base-package where DispatcherServlet searches the controller class.
  • 48. Step 5 Display the message in the JSP page - Spring MVC supports several types of views for different presentation technologies. - Examples are: JSPs, PDF, HTML, XML, Excel worksheets, velocity templates, XSLT, JSON, JasperReports, Atom and RSS feeds. - The most common of all these is a JSP template written with JSTL (Java Standard Tag Library). - The JSP page displays the message returned by the Controller
  • 49. Index.jsp <html> <body> <p>Welcome to Spring MVC Tutorial</p> </body> </html>
  • 50. What output do you get?
  • 51. III - Spring MVC Multiple View page Example In this example, we will redirect a view page to another view page Outlined below are the steps to follow: 1. Load the spring jar files 2. Create the controller class 3. Provide the entry of controller in the web.xml file 4. Define the bean in the separate XML file 5. Create the other view components 6. Start the server and deploy the project
  • 53. IV - Spring MVC Multiple Controller Example -Spring MVC allows us to create multiple controller at a time. -Each controller class should be matched with @Controller annotation. - We shall go step by step through an example of Spring MVC with multiple controllers. - Outlined below are the main steps we shall follow: 1. Load the spring jar files 2. Create the controller class 3. Provide the entry controller in the web.xml file
  • 54. 4. Create the other view components 5. Start the server - Deploy the project
  • 56. V - Spring MVC Model Interface -As defined earlier on, the model works as a container that contains the data of the application. -This data can be in the form of objects, strings, or information from the database, among many others. -The Model Interface should be placed in the controller part of the application. - HttpServletRequest reads the information provided by the user and passes it to the Model interface. -The viewpage then accesses the data from the model part. -Methods of Model Interface -Outlined below are the various methods of model interface
  • 57. 1. Model addAllAttributes(Collection</>arg) - this adds all the attributes in the provided Collection into this Map 2. Model addAllAttributes(Map<String,?> arg) - this adds all the attributes in the provided Map into this Map 3. Model addAllAttribute(Object arg) - this adds the provided attribute to this Map using a generated name 4. Model addAllAttribute(String arg0, Object arg1) - this binds the attribute with the provided name 5. Map<String, Object> asMap() - this returns the current set of model attributes as a Map
  • 58. 6. Model mergeAttributes(Map<String,?> arg) - this adds all attributes in the provided Map into this Map, with existing objects of the same name taking precedence. 7. Boolean containsAttribute(String arg) - this indicates if this model contains an attribute of the given name
  • 59. VI - Spring MVC RequestParam Annotation - The @RequestParam annotation basically reads the form data and automatically binds it to the parameter present in the provided method. - It does not consider the requirement of HttpServletRequest object to read the provided data. - The @RequestParam annotation also maps the request parameter to query parameter as well as parts in multipart requests. - In case the method parameter type is defined as Map, and a specific request parameter name is given, the request parameter value will be converted to a Map, otherwise the map parameter will be populated with all request parameter names and values.

Editor's Notes

  • #3: [- Kick off the lesson by an oral introduction of Spring MVC to the students - Explain the importance of the MVC architecture]