Unit Spring MVC
Unit Spring MVC
Unit Spring MVC
7.0 Introduction 1
7.1 Objectives 2
7.2 Setting up Development Environment for Spring MVC 3
7.3 First Hello World Project using Spring MVC 5
7.4 Inversion of Control (IoC) and Dependency Injection 9
7.5 Creating Controllers and Views 10
7.6 Request Params and Request mapping 13
7.7 Form Tags and Data binding 14
7.8 Form Validation 18
7.9 Summary 20
7.10 Solutions/ Answer to Check Your Progress 20
7.11 References/Further Reading 22
7.0 INTODUCTION
The Spring MVC framework is an open source Java platform. This framework was
developed by Rod Johnson and it was first released in June 2003 under the Apache
2.0 license. In web based applications, the size of code plays a vital role.This
framework is lightweight when it comes to size. This leads this framework to reach
its heights. The basic version of this framework is of around 2MB. It follows the
MVC (Model-View-Controller) design pattern. Spring Framework gears all the basic
features of a core spring framework like Inversion of Control, and Dependency
Injection.
MVC is a software structural design - the building of the system - that separates the
business logic (domain/application/business) (whatever the way business prefers) from
the rest of the user interface. The MVC does it by separating the whole application
into three parts: the model, the view, and the controller.
The Spring MVC Dispatcher servlet acts as glue and this act makes it the most
important component. It finds the correct methods and views for received incoming
URL. This can be considered as a middleware as it receives the URL via HTTP
request and it communicates with two ends – the sender of HTTP request and the
Spring application. The Dispatcher servlet allows the use of all the features of Spring
and it is completely integrated in the IoC container.
A the Spring Framework is modular in nature, it can be used in parts instead of using
the whole of it. Java & Web applications can be built by using Spring Framework.
7.1 OBJECTIVES
Spring Framework is used widely in the market and there are many Solution that have
been developed by keeping Spring Framework as core architecture. It is widely used
in the market as well and SAP Hybris is one such example.
Spring Framework is used to build almost anything, it's make coding in Java much
easy as it takes care of most of boilerplate (Boilerplate term refers to standardized
text, methods, or procedures that can be used again without making any major
changes to the original. It is mainly used for efficiency and to increase standardization
in the structure and language of written or digital documents) code and let developer
work on business logic.
Spring can be used to build any kind of applications (web application, enterprise
application, REST APIs and distributed systems) with spring cloud and Angular
framework which makes it more useful/popular.
Spring offers a one-stop shop for all the business needs to develop applications. Due
to its nature of modularity, it allows to pick and choose the modules which are more
suitable to the business and technical demand without resorting to the whole stack.
The following diagram provides details about all the modules available in Spring
Framework.
As all the below modules are the part of Spring Framework libraries hence we need to
download all these libraries and need setup to take all the below modules’ advantage.
2
Frameworks for J2EE
3
Spring MVC Concepts
• The Programmatic and declarative transaction management for classes that
implement special interfaces and for all your POJOs are done by the
Transaction Module.
Web: The Web layer holds of the following modules (Web, Web-MVC, Web-
Socket, and Web-Portlet) and the details of these are as follows:
• Basic featurs for multipart file-upload functionality and the initialization of
the IoC container using servlet listeners and a web-oriented application
context provided by the Web Module.
• Spring's Model-View-Controller (MVC) implementation for web applications
is covered under Web-MVC.
• The Web-Socket module takes responsibility of communication (support for
WebSocket-based, two-way communication between the client and the
server in web applications).
• The Web-Portlet module covers the MVC implementation to be used in a
portlet setup and emulates the functionality of Web-Servlet module.
Miscellaneous:AOP, Aspects, Instrumentation, Web and Test modules are also some
other important modules and the details of these are as follows −
• To decouple code, there is a need to define method-interceptors and pointcuts
and this is achieved by AOP Module as it provides an aspect-oriented
programming implementation.
• AspectJ integration is achieved by the Aspects Module and AspectJ is mature
and powerful AOP Framework.
• This module is basically based on application servers as class loader and
class instrumentation is used and supported by The Instrumentation Module.
• Support of Streaming Text Oriented Messaging Protocol (STOMP) as the
WebSocket sub-protocol to use in applications is provided by
the Messaging Module.
• JUnit or TestNG frameworks are used for Spring Components Testing and all
this is done by Test Module
It is always good to use integrated development environment (IDE) for any kind of
java development as it increases the efficiency of the developer. An IDE is used for
programming in Java or any other language provided by any IDE. IDE basically
provides the functionality like debugging of the code, compilation of the code,
interpreter for java like languages with code editor. Developer perform all the above
mentioned activities with the help of graphical interface (GUI).
We would like to suggest you to use latest version of Eclipse or Netbean for your
programming exercises.
Suppose you install Eclipse or other IDE on your syste. For example once IDE
downloaded the installation, unpack the binary distribution into a convenient
location. For example, in C:\eclipse. Eclipse can be started by double-click on
eclipse.exe
4
Frameworks for J2EE
Once IDE setup is done then download the latest version of Spring framework
binaries from https://repo.spring.io/release/org/springframework/spring.
We will see in the example given below how to write a simple Hello World
application in Spring MVC Framework. First thing to notice is to have Eclipse or
some other IDE in place and follow the steps to develop a Dynamic Web Application.
Here Eclip IDE is used for explanations.
Step 1:
Create a Dynamic Web Project with a name HelloIGNOU and create a package
com.ignou the src folder in the created project.
Step 2:
Drag and drop below mentioned Spring and other libraries into the folder
WebContent/WEB-INF/lib.
5
Spring MVC Concepts
Step 3:
Step 4:
Create Spring configuration files web.xml and HelloWeb -servlet.xml under the
WebContent/WEB-INF folder.
Step 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.
Step 6:
The final step is to create the content of all the source and configuration files. Once it
is done then you have to export the application as explained below.
Web.xml
HelloWeb -servlet.xml
6
Frameworks for J2EE
HelloController.java
Hello.jsp
Need to include the below list of Spring and other libraries in our web application.
We can do this by drag and drop them in in WebContent/WEB-INF/lib folder.
7
Spring MVC Concepts
Once the source and configuration files are created then you have to export the
application. Do right click on the application and use Export > WAR File option for
saving HelloWeb.war file in Tomcat’s webapps folder or deploy this war file to any
web/app server via admin role.
8
Frameworks for J2EE
There is another options to run the app directly on the server from Eclipse.
You can check the working by using URL http://localhost:8080/HelloWeb/hello in
your browser. For this you have to first start the Tomcat Server and using a standard
browser check if you have access to other web pages from webapps folder.
Implement DIP by
Creating abstraction
Step3
Implement DI
Step4
IoC is all about overturning the control. In other words you can understand this by
this example. Let us assume that you drive your car daily to your work place. This
means you are controling the car. The IoC principle suggests to overturn the control,
meaning that instead of you drive your car yourself, you hire a cab, where driver will
be driving the car. Thus, this is called inversion of the control from you to the cab
driver. Now you don’t need to drive a car yourself but you can let the driver do the
driving so that you can focus on your office work.
Dependency Injection:
The Dependency Injection is a design pattern that removes the dependency of the
programs. To removes the dependency of the programs, Dependency Injection design
pattern do this job. In that kind of scenario, information is provided by the external
sources such as XML file. Dependency Injection plays a vital role to make the code
loosely coupled and easier for testing. In such a case we write the code as:
class Ignou
{
Student student;
Ignou(Student student)
{
this.student =student;
}
public void setStudent(Student student)
{
this.student =student;
}
}
We can perform Dependency Injection via following two ways in Spring framework
By Constructor – In the above code, the below snapshot of the code uses the
constructor
Ignou(Student student)
{
this.student =student;
}
By Setter method – In the above code, the below snapshot of the code uses the Setter
method
10
Frameworks for J2EE
Q2: Is Spring Framework open source?
• Controller Converts the payload of the request to the internal structure of the data
(mapping basically).
• After getting response from above two steps then it sends the data to Model for
further processing,
• Once it gets the processed data from the Model then that data is referred to the
View for rendering/display.
11
Spring MVC Concepts
There are basically two kind of constructors as typical MVC controllers as well as
RESTful controllers and the above diagram caters to both with some small
differences.
In the traditional approach, MVC applications are not service-oriented hence these
applications rely on View technology as data is finally redirected to the views
received from a Controller.
RESTful applications are designed as service-oriented and return raw/response data in
the form of JSON/XML typically.
As data is returned in the form of JSON/XML hence these applications do not have
Views, then the Controller is expected to send data directly via the HTTP response as
per the designed structure.
packagecom.ignou;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
publicclassHelloIngnouController
{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMapmodel)
{
model.addAttribute("message", "Hello Spring MVC Framework!");
return"hello";
}
}
12
Frameworks for J2EE
dispatching the request to the right cpontroller is achieved by configuring the
DispatcherServlet. This class handles the complete request handling process. It is a
regular servlet as others and can be configured along with any custom handler
mappings.
Spring MVC framework empowers parting of modules namely Model, View, and
Controller and seamlessly handles the application integration. This permits the
developer to develop complex applications also using plain java classes. The model
object is passed between controller and view using Maps objects. Moreover, it also
provides types mismatch validations and two-way data-binding support in the user
interface. Data-binding and form-submission in the user interface becomes possible
with spring form tags, model objects, and annotations.
In this article. We are discussing the steps involved in developing a Spring web MVC
application, it explains the initial project setup for an MVC application in Spring. We
have multiple options to use view technology but in this example we are using
JSP(Java Server Pages) is used as a view technology.
Please find the below example which explains this whole concept of Controllers and
Views.
DispatcherServlet is the root Servlet, or we can say that it is the front controller class
to handle all requests and then to start processing. This needs to configure first in
web.xml file. DispatcherServlet's primary duty is to pass the request to appropriate
controller class and send the response back.
13
Spring MVC Concepts
Second step is to create spring bean configuration file as ignou-serv-servlet.xml.
packagecom.ignou.controller;
importjava.text.DateFormat;
importjava.util.Date;
importjava.util.Locale;
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.Model;
importorg.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importcom.journaldev.spring.model.User;
@ControllerpublicclassIgnouController
{
/** * Simply selects the home view to render by returning its name. */
@RequestMapping(value = "/", method = RequestMethod.GET) public String ignou(Locale
locale, Model model)
{
System.out.println("LandingIGNOU Page Requested = " + locale); Date date = newDate();
DateFormatdateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date); model.addAttribute("serverTime",
formattedDate);
return"ignou";
}
14
Frameworks for J2EE
@RequestMapping(value = "/ignoustudent", method = RequestMethod.POST) public String
user(@Validated User user, Model model)
{
System.out.println("IGNOUStudent Page Requested"); model.addAttribute("studentName",
ignoustudent.getStudentName());
return"ignoustudent";
}
}
Fourth step is to define Model. This class can be represented by many names like
Bean Class, POJO Class or Model Class.
packagecom.ignou.model;
publicclassIgnoustudent
{
private String studentName;
public String getStudentName()
{
returnstudentName;
}
publicvoidsetStudentName(String studentName)
{
this.studentName = studentName;
}
}
Ignou.jsp
Student.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"https://www.w3.org/TR/html4/loose.dtd">
15
Spring MVC Concepts
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>IGNOU Student Home Page</title>
</head>
<body>
<h3>Hello ${studentName}</h3>
</body>
</html>
This above example basically explains that what configurations are needed to do in
web.xml and how do we define root servlet (DispatcherServlet) and defining of
controllers, models, and views.
16
Frameworks for J2EE
We can explain this with the help of student details which we want to add into
database.
Student_ID
Student_FirstName
Student_LastName
Student_DOB
@Controller
@RequestMapping("/ignoustudent/*")
public class IgnouStudentController
{
@GetMapping("/fill")
public String fill()
{
return "studentForm";
}
@PostMapping("/fill/process")
public String processForm(ModelMap model, @RequestParam("Student_ID")
intstud_id, @RequestParam("Student_FirstName") String stud_firstName,
@RequestParam("Student_LastNAme") String stud_lastName,
@RequestParam("Student_DOB") Date stud_dob)
{
model.addAttribute("Student_ID ", stud_id);
model.addAttribute("Student_FirstName", stud_firstName);
model.addAttribute("Student_LastName", stud_lastName);
model.addAttribute("Student_DOB", stud_dob);
return "index";
}
}
17
Spring MVC Concepts
@Controller
@RequestMapping("/ignoustudent/*")
public class IgnouStudentController
{
@GetMapping("/fill")
public String fill()
{
return "studentForm";
}
@PostMapping("/fill/process")
public String processForm(ModelMap model, @RequestParamint_id,
@RequestParam("FirstName") String firstName, @RequestParam("LastName")
String lastName)
{
model.addAttribute("Student_id", id);
model.addAttribute("Student_firstName", firstName);
model.addAttribute("Student_lastName", lastName);
model.addAttribute("Student_DOB", dob);
return "index";
}
}
Request Mapping:
Spring Controller supports the three levels of request mapping and it depends on the
different @RequestMapping annotations declared in its handler methods and
controller class.
Please find below the different mapping types:
By path
@RequestMapping(“path”)
By HTTP method
@RequestMapping(“path”, method=RequestMethod.GET).
Other Http methods such as POST,
PUT, DELETE, OPTIONS, and TRACE are also supported.
By query parameter
@RequestMapping(“path”, method=RequestMethod.GET,
params=”param1”)
By the presence of request header
@RequestMapping(“path”, header=”content-type=text/*”)
For the Web Pages, Spring MVC has provided the form tags which are configurable
and reusable building blocks. These Tags are very helpful for easy development, easy
to read and maintain. These Tags can be used as data binding tags where these tags
can set data to java objects (Bean or POJO).
The form tag library comes under the spring-webmvc.jar. To get the support from the
form tag library,you requires to reference some configuration So, you have to add the
following directive at the beginning of the JSP page:
Spring data binding mechanism provides the functionality to bound the user inputs
dynamically to the beans. It can explained as it allows the setting property values into
a target object and this functionality is provided by DataBinder class though
BeanWrapper also provides the same functionality but DataBinder additionally
supports field formatting, binding result analysis and validation.
Where DataBinder works on high level and BeanWrapper works on low level. Both
Binders are used in PropertyEditors to parse and format the property values. We
should use the DataBinder as it works on high level and internally it uses the
BeanWrapper only.
Data binding from web request parameters to JavaBean/POJO objects are done by
WebDataBinder.We use it for customizing request param bindings.
We can understand better these topics with the help of the below example:
<html>
<body>
<h2> Spring MVC Form Tag with Data Binding Example for IGNOU Students </h2>
<a href = "home_page">Home page | </a>
<a href = "about_us"> About Us | </a>
<a href = "student_form"> Student Detail Form</a>
</body>
</html>
package com.ignou.studentdetails;
public class Student
{
private String fname;
private String lname;
public Student()
{
}
public String getFname()
{
return fname;
}
public void setFname(String fname)
{
19
Spring MVC Concepts
this.fname = fname;
}
public String getLname()
{
return lname;
}
public void setLname(String lname)
{
this.lname = lname;
}
}
package com.ignou.studentdetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class StudentDetailController
{
@RequestMapping("/student_form")
public String showStudentForm( Model m)
{
Student student = new Student();
m.addAttribute("student", student);
return "studentform" ;
}
@RequestMapping("/studentregis")
public String showStudentData(@ModelAttribute("student") Student student)
{
System.out.println("student:" + student.getFname() +" "+ student.getLname());
return "student-data" ;
}
}
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/view/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
StudentDetailForm.jsp
StudentDetailData.jsp
21
Spring MVC Concepts
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1">
<title>Student Detail Data</title>
</head>
<body>
The student name is ${student.fname} ${student.lname}
</body>
</html>
In Spring MVC form Validation, a variety of annotations are used. These annotations
are available in javax.validation.constraints package. Below is a list of commonly
used Validation annotations:
Annotations Description
@Size It specifies that the size of the annotated element must be between
thespecified boundaries.
@Pattern It specifies that the annotated CharSequence must match the
regularexpression.
@Past It specifies that the annotated element must be a date in the past.
@Null It specifies that the annotated element must be null.
@NotNull It specifies that the annotated element should not be null.
@Min It specifies that the annotated element must be a number whose value
mustbe equal or greater than the specified minimum number.
@Max It specifies that the annotated element must be a number whose value
mustbe equal or smaller than the specified maximum.
@Future It specifies that the annotated element must be a date in the future.
@Digits It specifies that the annotated element must be a digit or number
within thespecified range. The supported types are short, int, long,
byte, etc.
@DecimalMin It specifies that the annotated element must be a number whose
value must be equal or greater than the specified minimum. It is very
similar to @Minannotation, but the only difference is it supports
CharSequence type.
@DecimalMax It specifies that the annotated element must be a number whose
value should be equal or smaller than the specified maximum. It
is very similarto @Max annotation, but the only difference is it
supports CharSequence type.
22
Frameworks for J2EE
@AssertTrue It determines that the annotated element must be true.
@AssertFalse It determines that the annotated element must be false
We can use the model (Student.java) from previous example and put the validations
inside form class as below
package com.ignou.studentdetails;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Student
{
@NotNull
@Size(min =1, message ="You can't leave this empty.")
23
Spring MVC Concepts
7.9 SUMMARY
Spring's Web MVC Framework is very popular and used framework due to its
request-driven, designed around a central Servlet that dispatches requests to
controllers and offers other functionality that facilitates the development of web
applications. It also facilitates fast and parallel development. It Reuses business code -
instead of creating new objects. It allows us to use the existing business objects. It
provides easy to test functionality as we create JavaBeans classes that enable us to
inject test data using the setter methods. This framework is used in many products
development like Hybris and banking domain products.
3. The IoC container is responsible to instantiate, configure and assemble the objects.
The IoC contains gets informations from the XML file and works accordingly and
its primary tasks performed by IoC container are:
24
Frameworks for J2EE
There are two types of IoC containers. They are:
BeanFactory
ApplicationContext
1. The Init Binder is an annotation that is used to customize the request being sent to
the controller. It is used to to control and format those requests that come to the
controller.
3. One of the major difference between these stereotypes is that these are used for
different classification. You may have different layers like presentation, service,
business, data access etc. in a multitier application. When you try to annotated a
class for auto-detection by Spring, then you should have to use the respective
stereotype as below:
• Tag Handlers Java classes. This class implement the functionality of custom
tags.
• Tag Extra Information Classes. These classes are used to supply the JSP
container with logic for validating tag attributes and creating scripting
variables.
• A Tag Library Descriptor (TLD). It is an XML document, used to describe
the properties of the individual tags and the tag library as a whole.
26