SlideShare una empresa de Scribd logo
1 de 53
Descargar para leer sin conexión
Slide 1 of 53© People Strategists www.peoplestrategists.com
Spring Framework -II
Slide 2 of 53© People Strategists www.peoplestrategists.com
Objectives
In this session, you will learn to:
Explore Spring MVC framework
Identify benefits of Spring MVC framework
Slide 3 of 53© People Strategists www.peoplestrategists.com
The core idea of the MVC pattern is to separate the business logic from
UIs to allow them to change independently without affecting each other.
MVC design pattern is made up of the following components:
Exploring Spring MVC Framework
Represents the data that an
application persists.
Represents the UI of the application.
Responsible for receiving the user
request and passes it to the model.
Slide 4 of 53© People Strategists www.peoplestrategists.com
Spring MVC Framework:
Is an MVC design pattern extension that allows you to represent the UI
flow of a Web applicationintoindividual controllersand views.
Is a highly robust, flexible, and well-designed framework that is used for
rapidlydevelopingWeb applicationsusing the MVC design pattern.
Exploring Spring MVC Framework
Slide 5 of 53© People Strategists www.peoplestrategists.com
The features of Spring MVC framework are:
Exploring Spring MVC Framework (Contd.)
Pluggable view
technology
Injection of
services into
controllers
Integration
support
Spring MVC supports various view technologies,
such as JSP, and JSF.
 Spring MVC supports incorporates the
benefits of the Spring framework, such as DI
and AOP.
 Hence, reduces redundancyof code between
the UI layer and the business logic layer by
implicitlyinjecting the business layer objects
into the controller class.
 Spring MVC framework supports integration
with other frameworks, such as Struts and
Hibernate.
 Hence, developerscan utilize the advantages
of both the frameworks.
Slide 6 of 53© People Strategists www.peoplestrategists.com
The Spring Web MVC framework takes advantageof the AOP and DI
features of the Spring framework to help you create loosely coupled
Web applications.
It is built around a front controller servlet, called dispatcher servlet.
The dispatcher servlet is responsible for delegating the user request to
various components of the application while executing a user request.
Exploring Spring MVC Framework (Contd.)
The Spring MVC framework makes use of the following
components while processing a user request:
Handler mapping Controllers View resolvers View
Slide 7 of 53© People Strategists www.peoplestrategists.com
Exploring Spring MVC Framework (Contd.)
Handler mapping:
It enables the dispatcher servlet to forward the incoming requests to the
appropriatecontrollers.
Controllers:
Provide the application logicto process the incoming user request and
generate appropriateresponse that consists of the data that needs to be
displayedon the view.
The response also consists of the logical name of the view to be displayed.
View resolvers:
Are used for resolving the logical view names returned by the controllerto
the actual views.
Therefore, a view resolver selects the actual view that is displayedto the user.
View:
Is used to displaythe desired response to the user on the browser screen.
Slide 8 of 53© People Strategists www.peoplestrategists.com
Identifying Benefits of Spring MVC Framework
Benefits of
information
analysis
Simple and powerful
tag library
Supports multipleview
technologies and Web
frameworks
Light-weight development
environment
Ease of testing
Reusable
applicationcode
Slide 9 of 53© People Strategists www.peoplestrategists.com
Identifying Benefits of Spring MVC Framework (Contd.)
Ease of testing:
Spring MVC enables you to test individual filesand classes of an application
easily, along with the testing of the entire application.
This unit testing of the classes and files helpsin simplifying the testing
process as you can locate and fix most of the errors at an earlier stage of
applicationdevelopment.
In addition,the use of simple Javabeans makes it easy to inject test data
through setter methods.
Reusable application code:
Spring Web MVC supports reuse of applicationcode because the you can
bind the applicationclasses directly to the HTML form fields.
Simple and powerful tag library:
Spring MVC makes use of a simple and powerful tag library that helps you
render the output contentin different formats, such as HTML, and JSP.
This helpsyou write the flexible markup code as per your requirements.
Slide 10 of 53© People Strategists www.peoplestrategists.com
Identifying Benefits of Spring MVC Framework (Contd.)
Supports multiple view technologies and Web frameworks:
Spring helps you choose from multipleview technologies, such as HTML,
JSP, and JSF, whichever suits your applicationbetter.
It also helps you switch from one view technology to another by simply
modifying the code in the configurationfile.
Light-weight development environment:
Spring MVC provides a lightweight container,within which you can setup
and execute your application,using plainJavabeans.
This lightweightcontainerreduces the time and cost required for
developingand deploying the application.
Slide 11 of 53© People Strategists www.peoplestrategists.com
Identifying Lifecycle of a Web Request
Lifecycle of a Web request:
The Lifecycle of a Web Request
Request
Dispatcher
Servlet
Handler
Mapping
Controller
Model and View
View Resolver
View
1
2
3
4
5
6
Slide 12 of 53© People Strategists www.peoplestrategists.com
Handling a Web Request
Create and configure a dispatcher servlet.1
Steps to handle Web requests:
Create the controllerclass that performs the business logic for the
requested page.2
Configure the controllerwithin the dispatcher servlet’s context
configurationfile.3
Declare a view resolver to tie the controller with the view.4
Create a view to render the requested page to the user.5
Slide 13 of 53© People Strategists www.peoplestrategists.com
Creating and Configuring a Dispatcher Servlet
Dispatcher servlet:
Is a servlet that interceptsall user requests before passing them to a controller
class.
Is represented by the
org.springframework.web.servlet.DispatcherServletclass.
Intercepts all user requests before passing them to a controller class..
For a dispatcher servlet to intercept all user requests, you need to declare
and configure it in the web.xml configuration file.
You can declare and map the dispatcher servlet in the web.xml file with the
help of the <servlet> and <servlet-mapping> elements.
Slide 14 of 53© People Strategists www.peoplestrategists.com
Creating and Configuring a Dispatcher Servlet (Contd.)
<servlet>
<servlet-name>TicketDispatcher</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>TicketDispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
Slide 15 of 53© People Strategists www.peoplestrategists.com
Creating and Configuring a Dispatcher Servlet (Contd.)
Whenever dispatcher servlet is initialized, it loads the Spring’s
application context from an XML file.
This XML file is also called the dispatcher servlet configuration file.
The name of XML file is formed by suffixing -servlet.xml with the servlet
name.
For example, the name of the dispatcher servlet configuration file for the
TicketDispatcher dispatcher will be
TicketDispatcher-servlet.xml.
You can configure all the controller classes in the dispatcher servlet
configuration file.
Slide 16 of 53© People Strategists www.peoplestrategists.com
Creating and Configuring a Controller
Controller:
Is a Javaclass that handles the Web requests made by a user.
Is responsible for processing all the requests coming from the Web browser.
Controls the view and the model of the applicationby facilitatingdata exchange
between them.
Receives the request from the dispatcherservlet, forwards it to the service
classes for processing.
Collectsthe results in a page that is returned to the users in their Web browsers.
The following figure shows the flow of a Web request.
Slide 17 of 53© People Strategists www.peoplestrategists.com
Creating and Configuring a Controller (Contd.)
You can create a controller by annotating a class as @Controller, as shown in
the following figure.
import bookTickets.Passenger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import service.BookService;
@Controller
@RequestMapping(value="/BookTickets.htm")
public class BookController {
private BookService bookService;
@RequestMapping(method=RequestMethod.GET)
public String showView(ModelMap model){
Passenger p = new Passenger();
model.addAttribute("Passenger", p);
return "BookTickets";
}
@RequestMapping(method=RequestMethod.POST)
public String processForm(@ModelAttribute(value="Passenger")
Passenger p, ModelMap model ){
model.addAttribute(“msg",bookService.sayHello(p.getNumTravellers())
);
return "BookConfirmed";
}
}
Slide 18 of 53© People Strategists www.peoplestrategists.com
Creating and Configuring a Controller (Contd.)
@RequestMapping():
Is used to specify the URL Mappingfor the controller.This mapping can be done
at the class-level as well as at the method-level.
Can take the following attributesas its parameter:
 value: It specifies the URL for which the class is acting as the controller.
 method: It specifies the method that will be invoked for the HTTP requests made by
the user.
The value of the method attribute can be either RequestMethod.GET or
RequestMethod.POST.
Once you have created the controller class, you need to configure it in the
dispatcher servlet’s configuration file, TicketDispatcher-servlet.xml.
Slide 19 of 53© People Strategists www.peoplestrategists.com
Creating and Configuring a Controller (Contd.)
The following code snippet can be used to configure the controller class,
BookController:
You can modify the applicationcontext.xml file to enable auto-
detection of the controller class, as shown in the following code snippet:
<bean name="BookController"
class="org.springframework.web.servlet.mvc.ParameterizableViewContr
oller" p:viewName="BookTickets" />
<bean class="controller.BookController“
p:bookService-ref="bookService"/>
<context:component-scan base-package="controller" />
<bean id="bookController" class="controller.BookController">
<property name="bookService" ref="bookService"/>
</bean>
Slide 20 of 53© People Strategists www.peoplestrategists.com
Mapping Requests to Controllers
Handler mappings in Spring are represented by the
org.springframework.web.servlet.HandlerMapping interface.
Spring MVC framework provides the following implementations of handler
mappings:
BeanNameUrlHandlerMappingclass
SimpleUrlHandlerMappingclass
ControllerClassNameHandlerMapping class
Slide 21 of 53© People Strategists www.peoplestrategists.com
Mapping Requests to Controllers (Contd.)
BeanNameUrlHandlerMapping class:
Is one of the simplest and easy-to-use handler mappings.
Maps the incoming user requests to the names of the beans defined in the
Spring’s applicationcontext file.
Is availablein the org.springframework.web.servlet.handler package.
You can use the following code snippet to declare the beans for associatingthe
application’scontrollers with their URL patterns:
<beans>
<bean id=”beanhandlermapping”
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMa
pping"/>
<bean name="/bookTicket.htm" class="controller.BookController"/>
</beans>
Slide 22 of 53© People Strategists www.peoplestrategists.com
Mapping Requests to Controllers (Contd.)
SimpleURLHandlerMapping class:
Is one of the simplest and straightforward handlermapping implementation.
Maps the user request to an appropriatecontrollerobject directly.
Uses property collectionelement <prop> to map the controllersto the URL
pattern.
To perform this type of mapping, you can use the following code snippet in the
Spring’s dispatcher-servlet.xml file:
<beans>
<bean id="simplehandlermapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerM
apping"/>
<property name="mappings">
<props>
<prop key="/bookTicket.htm">BookController</prop>
<props>
<property>
</bean>
<bean id=“bookController" class="controller.BookController"/>
</beans>
Slide 23 of 53© People Strategists www.peoplestrategists.com
Mapping Requests to Controllers (Contd.)
ControllerClassNameHandlerMapping class:
Maps to the URL patterns that are quite similar to the class names of the
controllers.
The Spring framework automaticallymapscontrollersto the URL patternsbased
on the controller’sclass name.
To perform this type of mapping, you can use the following code snippet in the
Spring’s dispatcher-servlet.xml file:
The controllerclass defined in the preceding code snippet will map to the URL
book.htm.
<bean id="ControllerClassHandlerMapping"
class="org.springframework.web.servlet.mvc.support.ControllerCla
ssNameHandlerMapping"/>
<bean class="controller.BookController"/>
</beans>
Slide 24 of 53© People Strategists www.peoplestrategists.com
Rendering Response to the Client
To render the response on the user’s browser screen, a view, such as JSP, is
used.
To render the response to the client, the following steps need to be
performed:
Declare a view
resolver
Create a view
Slide 25 of 53© People Strategists www.peoplestrategists.com
Rendering Response to the Client (Contd.)
Spring uses view resolvers to resolve the logical view names to the actual
views defined by a JSP page.
This view renders the information contained in the ModelMap object.
The following figure shows how a logical view name is resolved to the actual
view.
Dispatcher Servlet
Controller
View Resolver
ModelMap
View
ViewNameView
Slide 26 of 53© People Strategists www.peoplestrategists.com
Rendering Response to the Client (Contd.)
Spring provides you with the following ViewResolver interfaces:
InternalResourceViewResolver
BeanNameViewResolver
ResourceBundleViewResolver
XmlViewResolver
Slide 27 of 53© People Strategists www.peoplestrategists.com
Rendering Response to the Client (Contd.)
To resolve the views rendered using JSP, the
InternalResourceViewResolver interface is used.
For example, consider the air ticket reservation system.
You can declare the InternalResourceViewResolver interface, as shown
in the following code snippet:
It prefixes the view name returned by the controller class with the value of
the prefix property.
Then suffixes it with the value of the suffix property to return the actual view
name located at /WEB-INF/jsp/BookTickets.jsp.
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceView
Resolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
Slide 28 of 53© People Strategists www.peoplestrategists.com
Rendering Response to the Client (Contd.)
Creating a view:
Spring provides a custom tag library that you can use to create your view.
To make use of Spring’s tag library, you need to include the following directive in
the view:
The Spring tag library containsthe following tags that you can use to bind the
bean properties of the model object with the form components:
 <spring:bind>: It enables you to bind a bean property with the form components.
 <spring:nestedPath>: It helps you specify a path that is prefixed with the path
specified in the path attribute of the <spring:bind> tag.
<%@taglib uri="http://www.springframework.org/tags"
prefix="spring" %>
Slide 29 of 53© People Strategists www.peoplestrategists.com
Rendering Response to the Client (Contd.)
The following code snippet binds a textbox:
To specify how a property and its value can be accessed, you need to use
status object.
This object contains informationabout the bean property specified in the path
attribute.
It contains the following properties:
 status.expression: It is used to return the expression for identifying the bean
property. You can Use this property to set the name property of your form
components.
 status.value: It is used to return the value of the bean property. You can use this
property to set the value property of your form components.
<spring:bind path="Student.name">
<input type="text" />
</spring:bind>
Slide 30 of 53© People Strategists www.peoplestrategists.com
Rendering Response to the Client (Contd.)
The following code snippet binds a textbox and defines the status object:
The following code snippet specifies the path attribute:
<spring:bind path="Student.name">
<input type="text" name="${status.expression}"
value="${status.value}"/>
</spring:bind>
<spring:nestedPath path="Student">
<spring:bind path="name">
<input type="text" name="${status.expression}"
value="${status.value}"/>
</spring:bind>
<spring:bind path="age">
<input type="text" name="${status.expression}"
value="${status.value}"/>
</spring:bind>
</spring:nestedPath>
Slide 31 of 53© People Strategists www.peoplestrategists.com
Activity:ImplementingSpringMVC in a Web Application
Let us see how to create User
Interface for the Banking
portal.
Slide 32 of 53© People Strategists www.peoplestrategists.com
Activity: Implementing Spring MVC in a Web Application (Contd.)
You have to develop the UI for the ICHD Bank. Using this application, the
customers of the bank can access their account details and transfer funds to
other accounts of the same bank. The UI for this application consists of the
following Web pages:
Home page: Containsinformationabout the bank and a link for the login page.
Login page: Allows the users to log in using their user name and password, and
view their account details.
User account page: Displaysinformation about a particularaccount after a user
logs in by using his/her user name and password.
Create the Web pages for this application by using Spring MVC.
Slide 33 of 53© People Strategists www.peoplestrategists.com
Exploring AOP
Consider the exampleof an online education portal that allows students
to avail the services online.
StudentService
MiscService
CourseService
L
o
g
g
i
n
g
T
r
a
n
s
a
c
t
i
o
n
s
S
e
C
u
r
i
t
y
Slide 34 of 53© People Strategists www.peoplestrategists.com
Exploring AOP
Primary job is to register the student.
However, accepting online payments, updating mark details, and
sending notification emails to students are the secondary jobs.
These secondary jobs are referred as cross-cutting secondary concerns.
Spring provides Aspect-Oriented Programming (AOP) to solve the
problem of cross-cutting concerns by allowing you to express them in
stand-alone modules called aspects.
ASPECTS
Aspects enable you to isolate secondary logic from
the primary business logic of the application.
Secondary
concerns
Slide 35 of 53© People Strategists www.peoplestrategists.com
Exploring AOP (Contd.)
The secondary concern of an application is considered as an aspect, such as
login, security, authorization, and transaction management.
Features of AOP:
It increases modularityby isolatingsecondary logic from the primary logic.
It gives you the advantageof encapsulatingthe cross-cutting concerns.
It allowseasy removal of the previously defined functionalitieswithout
modifying the primary logic of the application.
You can implement the aspects by defining methods in a Java class.
Slide 36 of 53© People Strategists www.peoplestrategists.com
Exploring AOP (Contd.)
You can implement an aspect by identifying and creating the following
components:
Advice
Joinpoint
Pointcut Target
Proxy
Weaving
Slide 37 of 53© People Strategists www.peoplestrategists.com
Exploring AOP (Contd.)
Advice
Joinpoint
Pointcut
It is the action an aspect performs.
It is a point or a locationin the application,
where an advice can be plugged in.
It defines to which joinpointa particular
advice should be applied.
Slide 38 of 53© People Strategists www.peoplestrategists.com
Exploring AOP (Contd.)
Target
Proxy
Weaving
Is an object to which the aspect is applied.
Wraps the target object and interceptsall the calls
made to the object in such a way that the calling
object seems to be interactingwith the target
object rather than the proxy.
Is the process of applyingaspects to the
target object at the specified joinpointto
create a new proxied object.
Slide 39 of 53© People Strategists www.peoplestrategists.com
Implementing AOP
The primary job of the air ticket booking Web application is to enable users
to book air tickets.
However, checking seats availability is not part of the primary business logic
of the application and becomes secondary jobs.
The secondary jobs of the air ticket reservation application are considered as
aspects.
Air ticket reservation application
BookTicket.
jsp
Book air
tickets
Primary job
Check Seat
Availability
Secondary job
Slide 40 of 53© People Strategists www.peoplestrategists.com
Implementing AOP (Contd.)
To implement these aspects, you need to perform the following operations:
Create advice
Define pointcut
Create proxy
Creating Advice:
An advice is an action taken by the aspect at a particularjoinpoint.
An applicationcan have one or more advices.
Spring provides the following types of advices:
 Before
 After-running
 After-throwing
Slide 41 of 53© People Strategists www.peoplestrategists.com
Implementing AOP (Contd.)
Before
After-returning
After-throwing
This advice is executed before a joinpoint.
This advice is executed after a joinpointcompletes normally.
This advice is executed when a method throws an exception.
public void before(Method method, Object[] args,Object target )
throws Throwable
public void afterReturning(Object returnValue, Method method,
Object[] args,Object target) throws Throwable
public void afterThrowing(Throwable throwable)
Slide 42 of 53© People Strategists www.peoplestrategists.com
Implementing AOP (Contd.)
You can create advices in the following ways:
Using Java
classes
Using
configuration
elements
Slide 43 of 53© People Strategists www.peoplestrategists.com
Implementing AOP (Contd.)
package AOP;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
public class SecondaryJobAdvice implements MethodBeforeAdvice,AfterReturningAdvice {
public SecondaryJob secondary;
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
secondary.authenticate(args[1].toString());
secondary.checkSeatsAvailability(args[0].toString()); }
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object
target) throws Throwable {
secondary.updateSeats(args[0].toString());
secondary.rewardGift(args[0].toString()); }
public void setSecondary(SecondaryJob secondary) {
this.secondary = secondary;}}
The following code snippet shows the implementation of before and
after-returning advices in the SecondaryJobAdvice class:
Using
Java
classes
Slide 44 of 53© People Strategists www.peoplestrategists.com
Implementing AOP (Contd.)
xmlns:aop="http://www.springframework.org/schema/aop"
The Spring configuration elements can be used to turn any Java class into an
aspect by using the following aop namespace:
Spring provides the following configuration elements:
<aop:config>
<aop:aspect>
<aop:before>
<aop:after-running>
<aop:around>
Using
configuration
elements
Slide 45 of 53© People Strategists www.peoplestrategists.com
Implementing AOP (Contd.)
<bean id="bookingPointCut"
class="org.springframework.aop.support.JdkRegexpMethodPoi
ntcut">
<property name="pattern" value=".*book"/>
</bean>
Defining Pointcut:
Spring provides the class
org.springframework.aop.support.JdkRegexpMethodPointcut
that allowsyou to define pointcutsby using regular expressions.
The following code snippet defines a pointcut:
A pattern, .*book, is specified in the <property> tag of the bean.
It means that any method ending in book and belonging to any class in the
applicationwill be matched with the value attributeof the patternproperty.
Slide 46 of 53© People Strategists www.peoplestrategists.com
Implementing AOP (Contd.)
<bean id="secondaryJobAdvisor"
class="org.springframework.aop.support.DefaultPointcutAdvisor"
>
<property name="advice" ref="secondaryJobAdvice"/>
<property name="pointcut" ref="bookingPointCut"/>
</bean>
Defining advisor:
The following code snippet defines an advisor:
Creating a proxy:
The following code snippet defines a proxy:
<bean id="inst" class="AOP.BookTicket"/>
<bean id="bookProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="inst"/>
<property name="interceptorNames"
value="secondaryJobAdvisor"/>
<property name="proxyInterfaces"
value="AOP.BookTicketInterface"/>
</bean>
Parameters to the
constructor of the
ProxyFactoryBean
class
Slide 47 of 53© People Strategists www.peoplestrategists.com
Implementing AOP (Contd.)
@RequestMapping(method=RequestMethod.POST)
public String processView(@ModelAttribute("book")
BookTicketApp bt, ModelMap model) {
ApplicationContext ctx=new
ClassPathXmlApplicationContext("AOP/Config.xml");
BookTicketInterface
perf=(BookTicketInterface)ctx.getBean("bookProxy");
perf.book(bt.getTravelers(), bt.getPassword());
………………………
………………………
}
}
The following code calls the proxy needs from the HandleRequestController
class:
Slide 48 of 53© People Strategists www.peoplestrategists.com
Activity: Implementing AOP
You have to create a funds transfer page for the ICHD Bank. The users can
use this page to transfer funds from their account to other accounts of
the same bank. The funds transfer page consists of the following fields:
From account number
To account number
To bank
Transactionpassword
Transfer amount
In addition to the preceding fields, the funds transfer page has two
buttons, Payment and Reset.
The transfer of funds involves the following operations:
The transactionpassword is validated toauthenticatethe user.
The applicationensures that the amount to be transferred does not exceed
the availableaccountbalance.
Slide 49 of 53© People Strategists www.peoplestrategists.com
Activity: Implementing AOP (Contd.)
Users’ account balance is updated.
Prerequisite:
You need to use the ICHDBank project that you have created in Activity 2.2 to
perform this activity.
Ask your faculty to provide the com.springsource.org.aopalliance-1.0.0.jar
file required for completing this activity. Copy this file to your local computer.
Slide 50 of 53© People Strategists www.peoplestrategists.com
Summary
In this session, you learned that:
The Spring framework also has its own MVC implementation,the Spring MVC
Web framework.
This framework has the following features that make it better than the other
MVC frameworks:
 Pluggable view technology
 Injection of services into controllers
 Integration support
The MVC design pattern is made up of the following components:
 Model
 View
 Controller
Slide 51 of 53© People Strategists www.peoplestrategists.com
Summary (Contd.)
The Spring MVC framework makes use of the following componentswhile
processing a user request:
 Handler mappings
 Controllers
 View resolvers
 View
You can derive the following benefits while creating applicationsthat
implement the Spring MVC framework:
 Ease of testing
 Reusable application code
 Simple and powerful tag library
 Supports multiple view technologies and Web frameworks
 Light-weight development environment
The web.xml file of a Web applicationcontainsinformationabout how to
handlea particularWeb request.
Slide 52 of 53© People Strategists www.peoplestrategists.com
Summary (Contd.)
The dispatcher servlet delegatesthe request to another Spring MVC
component, known as controller.
You can create your own controllersby writing a class and annotatingit as
@Controller.
The ModelMap class is an implementationof the Map class.
Handler mappings in Spring are represented by the
org.springframework.web.servlet.HandlerMapping interface.
Spring MVC framework provides the following implementationsof handler
mappingsthat you can use in your Web application:
 BeanNameUrlHandlerMapping class
 SimpleUrlHandlerMapping class
 ControllerClassNameHandlerMapping class
Spring uses an interface, calledas view, which is responsible for handingover
the user request to a specified view technology, such as JSP.
Slide 53 of 53© People Strategists www.peoplestrategists.com
Summary (Contd.)
To render the response to the client, the following steps need to be performed:
 Declare a view resolver.
 Create a JSP page.
Spring provides you with the following ViewResolverinterfaces:
 InternalResourceViewResolver
 BeanNameViewResolver
 ResourceBundleViewResolver
 XmlViewResolver
The Spring tag library containsthe following tags that you can use to bind the bean
properties of the model object with the form components:
 <spring:bind>
 <spring:nestedPath>

Más contenido relacionado

La actualidad más candente

Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applications
elliando dias
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5
phanleson
 

La actualidad más candente (18)

JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
TY.BSc.IT Java QB U5
TY.BSc.IT Java QB U5TY.BSc.IT Java QB U5
TY.BSc.IT Java QB U5
 
TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6
 
TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6
 
Struts course material
Struts course materialStruts course material
Struts course material
 
Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applications
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
 
Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast track
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5
 
Spring framework DAO
Spring framework  DAOSpring framework  DAO
Spring framework DAO
 
Struts notes
Struts notesStruts notes
Struts notes
 
Hibernate notes
Hibernate notesHibernate notes
Hibernate notes
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
 
Jdbc
JdbcJdbc
Jdbc
 
How do i connect to that
How do i connect to thatHow do i connect to that
How do i connect to that
 

Destacado

Destacado (20)

Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
 
Java Day-2
Java Day-2Java Day-2
Java Day-2
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
 
Java Day-4
Java Day-4Java Day-4
Java Day-4
 
Final Table of Content
Final Table of ContentFinal Table of Content
Final Table of Content
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
RDBMS with MySQL
RDBMS with MySQLRDBMS with MySQL
RDBMS with MySQL
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Basic Hibernate Final
Basic Hibernate FinalBasic Hibernate Final
Basic Hibernate Final
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
JDBC
JDBCJDBC
JDBC
 
MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
Hibernate
HibernateHibernate
Hibernate
 

Similar a Spring Framework-II

A study of mvc – a software design pattern for web application development
A study of mvc – a software design pattern for web application developmentA study of mvc – a software design pattern for web application development
A study of mvc – a software design pattern for web application development
IAEME Publication
 

Similar a Spring Framework-II (20)

Mvc
MvcMvc
Mvc
 
MVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVC
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
 
Struts(mrsurwar) ppt
Struts(mrsurwar) pptStruts(mrsurwar) ppt
Struts(mrsurwar) ppt
 
MVC
MVCMVC
MVC
 
Ppt of Basic MVC Structure
Ppt of Basic MVC StructurePpt of Basic MVC Structure
Ppt of Basic MVC Structure
 
MVC Architecture: A Detailed Insight to the Modern Web Applications Developme...
MVC Architecture: A Detailed Insight to the Modern Web Applications Developme...MVC Architecture: A Detailed Insight to the Modern Web Applications Developme...
MVC Architecture: A Detailed Insight to the Modern Web Applications Developme...
 
An overview of microsoft mvc dot net
An overview of microsoft mvc dot netAn overview of microsoft mvc dot net
An overview of microsoft mvc dot net
 
Intro ASP MVC
Intro ASP MVCIntro ASP MVC
Intro ASP MVC
 
MVC
MVCMVC
MVC
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
IRJET- Lightweight MVC Framework in PHP
IRJET- Lightweight MVC Framework in PHPIRJET- Lightweight MVC Framework in PHP
IRJET- Lightweight MVC Framework in PHP
 
A study of mvc – a software design pattern for web application development
A study of mvc – a software design pattern for web application developmentA study of mvc – a software design pattern for web application development
A study of mvc – a software design pattern for web application development
 
Technoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development servicesTechnoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development services
 
Principles of MVC for PHP Developers
Principles of MVC for PHP DevelopersPrinciples of MVC for PHP Developers
Principles of MVC for PHP Developers
 
Angular JS Basics
Angular JS BasicsAngular JS Basics
Angular JS Basics
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
A report on mvc using the information
A report on mvc using the informationA report on mvc using the information
A report on mvc using the information
 
Month 2 report
Month 2 reportMonth 2 report
Month 2 report
 
IRJET- MVC Framework: A Modern Web Application Development Approach and Working
IRJET- MVC Framework: A Modern Web Application Development Approach and WorkingIRJET- MVC Framework: A Modern Web Application Development Approach and Working
IRJET- MVC Framework: A Modern Web Application Development Approach and Working
 

Más de People Strategists (7)

Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
CSS
CSSCSS
CSS
 
HTML/HTML5
HTML/HTML5HTML/HTML5
HTML/HTML5
 
Java Day-3
Java Day-3Java Day-3
Java Day-3
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Spring Framework-II

  • 1. Slide 1 of 53© People Strategists www.peoplestrategists.com Spring Framework -II
  • 2. Slide 2 of 53© People Strategists www.peoplestrategists.com Objectives In this session, you will learn to: Explore Spring MVC framework Identify benefits of Spring MVC framework
  • 3. Slide 3 of 53© People Strategists www.peoplestrategists.com The core idea of the MVC pattern is to separate the business logic from UIs to allow them to change independently without affecting each other. MVC design pattern is made up of the following components: Exploring Spring MVC Framework Represents the data that an application persists. Represents the UI of the application. Responsible for receiving the user request and passes it to the model.
  • 4. Slide 4 of 53© People Strategists www.peoplestrategists.com Spring MVC Framework: Is an MVC design pattern extension that allows you to represent the UI flow of a Web applicationintoindividual controllersand views. Is a highly robust, flexible, and well-designed framework that is used for rapidlydevelopingWeb applicationsusing the MVC design pattern. Exploring Spring MVC Framework
  • 5. Slide 5 of 53© People Strategists www.peoplestrategists.com The features of Spring MVC framework are: Exploring Spring MVC Framework (Contd.) Pluggable view technology Injection of services into controllers Integration support Spring MVC supports various view technologies, such as JSP, and JSF.  Spring MVC supports incorporates the benefits of the Spring framework, such as DI and AOP.  Hence, reduces redundancyof code between the UI layer and the business logic layer by implicitlyinjecting the business layer objects into the controller class.  Spring MVC framework supports integration with other frameworks, such as Struts and Hibernate.  Hence, developerscan utilize the advantages of both the frameworks.
  • 6. Slide 6 of 53© People Strategists www.peoplestrategists.com The Spring Web MVC framework takes advantageof the AOP and DI features of the Spring framework to help you create loosely coupled Web applications. It is built around a front controller servlet, called dispatcher servlet. The dispatcher servlet is responsible for delegating the user request to various components of the application while executing a user request. Exploring Spring MVC Framework (Contd.) The Spring MVC framework makes use of the following components while processing a user request: Handler mapping Controllers View resolvers View
  • 7. Slide 7 of 53© People Strategists www.peoplestrategists.com Exploring Spring MVC Framework (Contd.) Handler mapping: It enables the dispatcher servlet to forward the incoming requests to the appropriatecontrollers. Controllers: Provide the application logicto process the incoming user request and generate appropriateresponse that consists of the data that needs to be displayedon the view. The response also consists of the logical name of the view to be displayed. View resolvers: Are used for resolving the logical view names returned by the controllerto the actual views. Therefore, a view resolver selects the actual view that is displayedto the user. View: Is used to displaythe desired response to the user on the browser screen.
  • 8. Slide 8 of 53© People Strategists www.peoplestrategists.com Identifying Benefits of Spring MVC Framework Benefits of information analysis Simple and powerful tag library Supports multipleview technologies and Web frameworks Light-weight development environment Ease of testing Reusable applicationcode
  • 9. Slide 9 of 53© People Strategists www.peoplestrategists.com Identifying Benefits of Spring MVC Framework (Contd.) Ease of testing: Spring MVC enables you to test individual filesand classes of an application easily, along with the testing of the entire application. This unit testing of the classes and files helpsin simplifying the testing process as you can locate and fix most of the errors at an earlier stage of applicationdevelopment. In addition,the use of simple Javabeans makes it easy to inject test data through setter methods. Reusable application code: Spring Web MVC supports reuse of applicationcode because the you can bind the applicationclasses directly to the HTML form fields. Simple and powerful tag library: Spring MVC makes use of a simple and powerful tag library that helps you render the output contentin different formats, such as HTML, and JSP. This helpsyou write the flexible markup code as per your requirements.
  • 10. Slide 10 of 53© People Strategists www.peoplestrategists.com Identifying Benefits of Spring MVC Framework (Contd.) Supports multiple view technologies and Web frameworks: Spring helps you choose from multipleview technologies, such as HTML, JSP, and JSF, whichever suits your applicationbetter. It also helps you switch from one view technology to another by simply modifying the code in the configurationfile. Light-weight development environment: Spring MVC provides a lightweight container,within which you can setup and execute your application,using plainJavabeans. This lightweightcontainerreduces the time and cost required for developingand deploying the application.
  • 11. Slide 11 of 53© People Strategists www.peoplestrategists.com Identifying Lifecycle of a Web Request Lifecycle of a Web request: The Lifecycle of a Web Request Request Dispatcher Servlet Handler Mapping Controller Model and View View Resolver View 1 2 3 4 5 6
  • 12. Slide 12 of 53© People Strategists www.peoplestrategists.com Handling a Web Request Create and configure a dispatcher servlet.1 Steps to handle Web requests: Create the controllerclass that performs the business logic for the requested page.2 Configure the controllerwithin the dispatcher servlet’s context configurationfile.3 Declare a view resolver to tie the controller with the view.4 Create a view to render the requested page to the user.5
  • 13. Slide 13 of 53© People Strategists www.peoplestrategists.com Creating and Configuring a Dispatcher Servlet Dispatcher servlet: Is a servlet that interceptsall user requests before passing them to a controller class. Is represented by the org.springframework.web.servlet.DispatcherServletclass. Intercepts all user requests before passing them to a controller class.. For a dispatcher servlet to intercept all user requests, you need to declare and configure it in the web.xml configuration file. You can declare and map the dispatcher servlet in the web.xml file with the help of the <servlet> and <servlet-mapping> elements.
  • 14. Slide 14 of 53© People Strategists www.peoplestrategists.com Creating and Configuring a Dispatcher Servlet (Contd.) <servlet> <servlet-name>TicketDispatcher</servlet-name> <servlet- class>org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>TicketDispatcher</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping>
  • 15. Slide 15 of 53© People Strategists www.peoplestrategists.com Creating and Configuring a Dispatcher Servlet (Contd.) Whenever dispatcher servlet is initialized, it loads the Spring’s application context from an XML file. This XML file is also called the dispatcher servlet configuration file. The name of XML file is formed by suffixing -servlet.xml with the servlet name. For example, the name of the dispatcher servlet configuration file for the TicketDispatcher dispatcher will be TicketDispatcher-servlet.xml. You can configure all the controller classes in the dispatcher servlet configuration file.
  • 16. Slide 16 of 53© People Strategists www.peoplestrategists.com Creating and Configuring a Controller Controller: Is a Javaclass that handles the Web requests made by a user. Is responsible for processing all the requests coming from the Web browser. Controls the view and the model of the applicationby facilitatingdata exchange between them. Receives the request from the dispatcherservlet, forwards it to the service classes for processing. Collectsthe results in a page that is returned to the users in their Web browsers. The following figure shows the flow of a Web request.
  • 17. Slide 17 of 53© People Strategists www.peoplestrategists.com Creating and Configuring a Controller (Contd.) You can create a controller by annotating a class as @Controller, as shown in the following figure. import bookTickets.Passenger; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import service.BookService; @Controller @RequestMapping(value="/BookTickets.htm") public class BookController { private BookService bookService; @RequestMapping(method=RequestMethod.GET) public String showView(ModelMap model){ Passenger p = new Passenger(); model.addAttribute("Passenger", p); return "BookTickets"; } @RequestMapping(method=RequestMethod.POST) public String processForm(@ModelAttribute(value="Passenger") Passenger p, ModelMap model ){ model.addAttribute(“msg",bookService.sayHello(p.getNumTravellers()) ); return "BookConfirmed"; } }
  • 18. Slide 18 of 53© People Strategists www.peoplestrategists.com Creating and Configuring a Controller (Contd.) @RequestMapping(): Is used to specify the URL Mappingfor the controller.This mapping can be done at the class-level as well as at the method-level. Can take the following attributesas its parameter:  value: It specifies the URL for which the class is acting as the controller.  method: It specifies the method that will be invoked for the HTTP requests made by the user. The value of the method attribute can be either RequestMethod.GET or RequestMethod.POST. Once you have created the controller class, you need to configure it in the dispatcher servlet’s configuration file, TicketDispatcher-servlet.xml.
  • 19. Slide 19 of 53© People Strategists www.peoplestrategists.com Creating and Configuring a Controller (Contd.) The following code snippet can be used to configure the controller class, BookController: You can modify the applicationcontext.xml file to enable auto- detection of the controller class, as shown in the following code snippet: <bean name="BookController" class="org.springframework.web.servlet.mvc.ParameterizableViewContr oller" p:viewName="BookTickets" /> <bean class="controller.BookController“ p:bookService-ref="bookService"/> <context:component-scan base-package="controller" /> <bean id="bookController" class="controller.BookController"> <property name="bookService" ref="bookService"/> </bean>
  • 20. Slide 20 of 53© People Strategists www.peoplestrategists.com Mapping Requests to Controllers Handler mappings in Spring are represented by the org.springframework.web.servlet.HandlerMapping interface. Spring MVC framework provides the following implementations of handler mappings: BeanNameUrlHandlerMappingclass SimpleUrlHandlerMappingclass ControllerClassNameHandlerMapping class
  • 21. Slide 21 of 53© People Strategists www.peoplestrategists.com Mapping Requests to Controllers (Contd.) BeanNameUrlHandlerMapping class: Is one of the simplest and easy-to-use handler mappings. Maps the incoming user requests to the names of the beans defined in the Spring’s applicationcontext file. Is availablein the org.springframework.web.servlet.handler package. You can use the following code snippet to declare the beans for associatingthe application’scontrollers with their URL patterns: <beans> <bean id=”beanhandlermapping” class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMa pping"/> <bean name="/bookTicket.htm" class="controller.BookController"/> </beans>
  • 22. Slide 22 of 53© People Strategists www.peoplestrategists.com Mapping Requests to Controllers (Contd.) SimpleURLHandlerMapping class: Is one of the simplest and straightforward handlermapping implementation. Maps the user request to an appropriatecontrollerobject directly. Uses property collectionelement <prop> to map the controllersto the URL pattern. To perform this type of mapping, you can use the following code snippet in the Spring’s dispatcher-servlet.xml file: <beans> <bean id="simplehandlermapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerM apping"/> <property name="mappings"> <props> <prop key="/bookTicket.htm">BookController</prop> <props> <property> </bean> <bean id=“bookController" class="controller.BookController"/> </beans>
  • 23. Slide 23 of 53© People Strategists www.peoplestrategists.com Mapping Requests to Controllers (Contd.) ControllerClassNameHandlerMapping class: Maps to the URL patterns that are quite similar to the class names of the controllers. The Spring framework automaticallymapscontrollersto the URL patternsbased on the controller’sclass name. To perform this type of mapping, you can use the following code snippet in the Spring’s dispatcher-servlet.xml file: The controllerclass defined in the preceding code snippet will map to the URL book.htm. <bean id="ControllerClassHandlerMapping" class="org.springframework.web.servlet.mvc.support.ControllerCla ssNameHandlerMapping"/> <bean class="controller.BookController"/> </beans>
  • 24. Slide 24 of 53© People Strategists www.peoplestrategists.com Rendering Response to the Client To render the response on the user’s browser screen, a view, such as JSP, is used. To render the response to the client, the following steps need to be performed: Declare a view resolver Create a view
  • 25. Slide 25 of 53© People Strategists www.peoplestrategists.com Rendering Response to the Client (Contd.) Spring uses view resolvers to resolve the logical view names to the actual views defined by a JSP page. This view renders the information contained in the ModelMap object. The following figure shows how a logical view name is resolved to the actual view. Dispatcher Servlet Controller View Resolver ModelMap View ViewNameView
  • 26. Slide 26 of 53© People Strategists www.peoplestrategists.com Rendering Response to the Client (Contd.) Spring provides you with the following ViewResolver interfaces: InternalResourceViewResolver BeanNameViewResolver ResourceBundleViewResolver XmlViewResolver
  • 27. Slide 27 of 53© People Strategists www.peoplestrategists.com Rendering Response to the Client (Contd.) To resolve the views rendered using JSP, the InternalResourceViewResolver interface is used. For example, consider the air ticket reservation system. You can declare the InternalResourceViewResolver interface, as shown in the following code snippet: It prefixes the view name returned by the controller class with the value of the prefix property. Then suffixes it with the value of the suffix property to return the actual view name located at /WEB-INF/jsp/BookTickets.jsp. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceView Resolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
  • 28. Slide 28 of 53© People Strategists www.peoplestrategists.com Rendering Response to the Client (Contd.) Creating a view: Spring provides a custom tag library that you can use to create your view. To make use of Spring’s tag library, you need to include the following directive in the view: The Spring tag library containsthe following tags that you can use to bind the bean properties of the model object with the form components:  <spring:bind>: It enables you to bind a bean property with the form components.  <spring:nestedPath>: It helps you specify a path that is prefixed with the path specified in the path attribute of the <spring:bind> tag. <%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
  • 29. Slide 29 of 53© People Strategists www.peoplestrategists.com Rendering Response to the Client (Contd.) The following code snippet binds a textbox: To specify how a property and its value can be accessed, you need to use status object. This object contains informationabout the bean property specified in the path attribute. It contains the following properties:  status.expression: It is used to return the expression for identifying the bean property. You can Use this property to set the name property of your form components.  status.value: It is used to return the value of the bean property. You can use this property to set the value property of your form components. <spring:bind path="Student.name"> <input type="text" /> </spring:bind>
  • 30. Slide 30 of 53© People Strategists www.peoplestrategists.com Rendering Response to the Client (Contd.) The following code snippet binds a textbox and defines the status object: The following code snippet specifies the path attribute: <spring:bind path="Student.name"> <input type="text" name="${status.expression}" value="${status.value}"/> </spring:bind> <spring:nestedPath path="Student"> <spring:bind path="name"> <input type="text" name="${status.expression}" value="${status.value}"/> </spring:bind> <spring:bind path="age"> <input type="text" name="${status.expression}" value="${status.value}"/> </spring:bind> </spring:nestedPath>
  • 31. Slide 31 of 53© People Strategists www.peoplestrategists.com Activity:ImplementingSpringMVC in a Web Application Let us see how to create User Interface for the Banking portal.
  • 32. Slide 32 of 53© People Strategists www.peoplestrategists.com Activity: Implementing Spring MVC in a Web Application (Contd.) You have to develop the UI for the ICHD Bank. Using this application, the customers of the bank can access their account details and transfer funds to other accounts of the same bank. The UI for this application consists of the following Web pages: Home page: Containsinformationabout the bank and a link for the login page. Login page: Allows the users to log in using their user name and password, and view their account details. User account page: Displaysinformation about a particularaccount after a user logs in by using his/her user name and password. Create the Web pages for this application by using Spring MVC.
  • 33. Slide 33 of 53© People Strategists www.peoplestrategists.com Exploring AOP Consider the exampleof an online education portal that allows students to avail the services online. StudentService MiscService CourseService L o g g i n g T r a n s a c t i o n s S e C u r i t y
  • 34. Slide 34 of 53© People Strategists www.peoplestrategists.com Exploring AOP Primary job is to register the student. However, accepting online payments, updating mark details, and sending notification emails to students are the secondary jobs. These secondary jobs are referred as cross-cutting secondary concerns. Spring provides Aspect-Oriented Programming (AOP) to solve the problem of cross-cutting concerns by allowing you to express them in stand-alone modules called aspects. ASPECTS Aspects enable you to isolate secondary logic from the primary business logic of the application. Secondary concerns
  • 35. Slide 35 of 53© People Strategists www.peoplestrategists.com Exploring AOP (Contd.) The secondary concern of an application is considered as an aspect, such as login, security, authorization, and transaction management. Features of AOP: It increases modularityby isolatingsecondary logic from the primary logic. It gives you the advantageof encapsulatingthe cross-cutting concerns. It allowseasy removal of the previously defined functionalitieswithout modifying the primary logic of the application. You can implement the aspects by defining methods in a Java class.
  • 36. Slide 36 of 53© People Strategists www.peoplestrategists.com Exploring AOP (Contd.) You can implement an aspect by identifying and creating the following components: Advice Joinpoint Pointcut Target Proxy Weaving
  • 37. Slide 37 of 53© People Strategists www.peoplestrategists.com Exploring AOP (Contd.) Advice Joinpoint Pointcut It is the action an aspect performs. It is a point or a locationin the application, where an advice can be plugged in. It defines to which joinpointa particular advice should be applied.
  • 38. Slide 38 of 53© People Strategists www.peoplestrategists.com Exploring AOP (Contd.) Target Proxy Weaving Is an object to which the aspect is applied. Wraps the target object and interceptsall the calls made to the object in such a way that the calling object seems to be interactingwith the target object rather than the proxy. Is the process of applyingaspects to the target object at the specified joinpointto create a new proxied object.
  • 39. Slide 39 of 53© People Strategists www.peoplestrategists.com Implementing AOP The primary job of the air ticket booking Web application is to enable users to book air tickets. However, checking seats availability is not part of the primary business logic of the application and becomes secondary jobs. The secondary jobs of the air ticket reservation application are considered as aspects. Air ticket reservation application BookTicket. jsp Book air tickets Primary job Check Seat Availability Secondary job
  • 40. Slide 40 of 53© People Strategists www.peoplestrategists.com Implementing AOP (Contd.) To implement these aspects, you need to perform the following operations: Create advice Define pointcut Create proxy Creating Advice: An advice is an action taken by the aspect at a particularjoinpoint. An applicationcan have one or more advices. Spring provides the following types of advices:  Before  After-running  After-throwing
  • 41. Slide 41 of 53© People Strategists www.peoplestrategists.com Implementing AOP (Contd.) Before After-returning After-throwing This advice is executed before a joinpoint. This advice is executed after a joinpointcompletes normally. This advice is executed when a method throws an exception. public void before(Method method, Object[] args,Object target ) throws Throwable public void afterReturning(Object returnValue, Method method, Object[] args,Object target) throws Throwable public void afterThrowing(Throwable throwable)
  • 42. Slide 42 of 53© People Strategists www.peoplestrategists.com Implementing AOP (Contd.) You can create advices in the following ways: Using Java classes Using configuration elements
  • 43. Slide 43 of 53© People Strategists www.peoplestrategists.com Implementing AOP (Contd.) package AOP; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.MethodBeforeAdvice; public class SecondaryJobAdvice implements MethodBeforeAdvice,AfterReturningAdvice { public SecondaryJob secondary; @Override public void before(Method method, Object[] args, Object target) throws Throwable { secondary.authenticate(args[1].toString()); secondary.checkSeatsAvailability(args[0].toString()); } @Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { secondary.updateSeats(args[0].toString()); secondary.rewardGift(args[0].toString()); } public void setSecondary(SecondaryJob secondary) { this.secondary = secondary;}} The following code snippet shows the implementation of before and after-returning advices in the SecondaryJobAdvice class: Using Java classes
  • 44. Slide 44 of 53© People Strategists www.peoplestrategists.com Implementing AOP (Contd.) xmlns:aop="http://www.springframework.org/schema/aop" The Spring configuration elements can be used to turn any Java class into an aspect by using the following aop namespace: Spring provides the following configuration elements: <aop:config> <aop:aspect> <aop:before> <aop:after-running> <aop:around> Using configuration elements
  • 45. Slide 45 of 53© People Strategists www.peoplestrategists.com Implementing AOP (Contd.) <bean id="bookingPointCut" class="org.springframework.aop.support.JdkRegexpMethodPoi ntcut"> <property name="pattern" value=".*book"/> </bean> Defining Pointcut: Spring provides the class org.springframework.aop.support.JdkRegexpMethodPointcut that allowsyou to define pointcutsby using regular expressions. The following code snippet defines a pointcut: A pattern, .*book, is specified in the <property> tag of the bean. It means that any method ending in book and belonging to any class in the applicationwill be matched with the value attributeof the patternproperty.
  • 46. Slide 46 of 53© People Strategists www.peoplestrategists.com Implementing AOP (Contd.) <bean id="secondaryJobAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor" > <property name="advice" ref="secondaryJobAdvice"/> <property name="pointcut" ref="bookingPointCut"/> </bean> Defining advisor: The following code snippet defines an advisor: Creating a proxy: The following code snippet defines a proxy: <bean id="inst" class="AOP.BookTicket"/> <bean id="bookProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="inst"/> <property name="interceptorNames" value="secondaryJobAdvisor"/> <property name="proxyInterfaces" value="AOP.BookTicketInterface"/> </bean> Parameters to the constructor of the ProxyFactoryBean class
  • 47. Slide 47 of 53© People Strategists www.peoplestrategists.com Implementing AOP (Contd.) @RequestMapping(method=RequestMethod.POST) public String processView(@ModelAttribute("book") BookTicketApp bt, ModelMap model) { ApplicationContext ctx=new ClassPathXmlApplicationContext("AOP/Config.xml"); BookTicketInterface perf=(BookTicketInterface)ctx.getBean("bookProxy"); perf.book(bt.getTravelers(), bt.getPassword()); ……………………… ……………………… } } The following code calls the proxy needs from the HandleRequestController class:
  • 48. Slide 48 of 53© People Strategists www.peoplestrategists.com Activity: Implementing AOP You have to create a funds transfer page for the ICHD Bank. The users can use this page to transfer funds from their account to other accounts of the same bank. The funds transfer page consists of the following fields: From account number To account number To bank Transactionpassword Transfer amount In addition to the preceding fields, the funds transfer page has two buttons, Payment and Reset. The transfer of funds involves the following operations: The transactionpassword is validated toauthenticatethe user. The applicationensures that the amount to be transferred does not exceed the availableaccountbalance.
  • 49. Slide 49 of 53© People Strategists www.peoplestrategists.com Activity: Implementing AOP (Contd.) Users’ account balance is updated. Prerequisite: You need to use the ICHDBank project that you have created in Activity 2.2 to perform this activity. Ask your faculty to provide the com.springsource.org.aopalliance-1.0.0.jar file required for completing this activity. Copy this file to your local computer.
  • 50. Slide 50 of 53© People Strategists www.peoplestrategists.com Summary In this session, you learned that: The Spring framework also has its own MVC implementation,the Spring MVC Web framework. This framework has the following features that make it better than the other MVC frameworks:  Pluggable view technology  Injection of services into controllers  Integration support The MVC design pattern is made up of the following components:  Model  View  Controller
  • 51. Slide 51 of 53© People Strategists www.peoplestrategists.com Summary (Contd.) The Spring MVC framework makes use of the following componentswhile processing a user request:  Handler mappings  Controllers  View resolvers  View You can derive the following benefits while creating applicationsthat implement the Spring MVC framework:  Ease of testing  Reusable application code  Simple and powerful tag library  Supports multiple view technologies and Web frameworks  Light-weight development environment The web.xml file of a Web applicationcontainsinformationabout how to handlea particularWeb request.
  • 52. Slide 52 of 53© People Strategists www.peoplestrategists.com Summary (Contd.) The dispatcher servlet delegatesthe request to another Spring MVC component, known as controller. You can create your own controllersby writing a class and annotatingit as @Controller. The ModelMap class is an implementationof the Map class. Handler mappings in Spring are represented by the org.springframework.web.servlet.HandlerMapping interface. Spring MVC framework provides the following implementationsof handler mappingsthat you can use in your Web application:  BeanNameUrlHandlerMapping class  SimpleUrlHandlerMapping class  ControllerClassNameHandlerMapping class Spring uses an interface, calledas view, which is responsible for handingover the user request to a specified view technology, such as JSP.
  • 53. Slide 53 of 53© People Strategists www.peoplestrategists.com Summary (Contd.) To render the response to the client, the following steps need to be performed:  Declare a view resolver.  Create a JSP page. Spring provides you with the following ViewResolverinterfaces:  InternalResourceViewResolver  BeanNameViewResolver  ResourceBundleViewResolver  XmlViewResolver The Spring tag library containsthe following tags that you can use to bind the bean properties of the model object with the form components:  <spring:bind>  <spring:nestedPath>