spring framework-ii
TRANSCRIPT
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 application into individual controllers and views.
Is a highly robust, flexible, and well-designed framework that is used for
rapidly developing Web applications using 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 redundancy of code between the UI layer and the business logic layer by implicitly injecting the business layer objects into the controller class.
Spring MVC framework supports integration with other frameworks, such as Struts and Hibernate.
Hence, developers can utilize the advantages of both the frameworks.
Slide 6 of 53© People Strategists www.peoplestrategists.com
The Spring Web MVC framework takes advantage of 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
appropriate controllers.
Controllers:
Provide the application logic to process the incoming user request and generate appropriate response that consists of the data that needs to be
displayed on 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 controller to the actual views.
Therefore, a view resolver selects the actual view that is displayed to the user.
View:
Is used to display the 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 multiple view technologies and Web
frameworks
Light-weight development environment
Ease of testing
Reusable application code
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 files and classes of an application
easily, along with the testing of the entire application.
This unit testing of the classes and files helps in simplifying the testing
process as you can locate and fix most of the errors at an earlier stage of
application development.
In addition, the use of simple Java beans makes it easy to inject test data through setter methods.
Reusable application code:
Spring Web MVC supports reuse of application code because the you can
bind the application classes 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 content in different formats, such as HTML, and JSP.
This helps you 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 multiple view technologies, such as HTML,
JSP, and JSF, whichever suits your application better.
It also helps you switch from one view technology to another by simply
modifying the code in the configuration file.
Light-weight development environment:
Spring MVC provides a lightweight container, within which you can setup and execute your application, using plain Java beans.
This lightweight container reduces the time and cost required for developing and 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
RequestDispatcher
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 controller class that performs the business logic for the requested page.2
Configure the controller within the dispatcher servlet’s context configuration file.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 intercepts all 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 Java class 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 application by facilitating data exchange between them.
Receives the request from the dispatcher servlet, forwards it to the service
classes for processing.
Collects the 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 Mapping for the controller. This mapping can be done
at the class-level as well as at the method-level.
Can take the following attributes as 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.GETor 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 application context file.
Is available in the org.springframework.web.servlet.handler package.
You can use the following code snippet to declare the beans for associating the
application’s controllers 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 handler mapping implementation.
Maps the user request to an appropriate controller object directly.
Uses property collection element <prop> to map the controllers to 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 automatically maps controllers to the URL patterns based on the controller’s class name.
To perform this type of mapping, you can use the following code snippet in the Spring’s dispatcher-servlet.xml file:
The controller class 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 ServletController
View Resolver
ModelMap
Vie
w
Vie
w N
am
eView
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 contains the 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 information about 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: Implementing Spring MVC 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: Contains information about 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: Displays information about a particular account 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 example of an online education portal that allows students to avail the services online.
StudentService
MiscService
CourseServiceLogging
Transactions
S eCurity
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 modularity by isolating secondary logic from the primary logic.
It gives you the advantage of encapsulating the cross-cutting concerns.
It allows easy removal of the previously defined functionalities without 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 location in the application, where an advice can be plugged in.
It defines to which joinpoint a 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 intercepts all the calls made to the object in such a way that the calling object seems to be interacting with the target object rather than the proxy.
Is the process of applying aspects to the target object at the specified joinpoint to 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 particular joinpoint.
An application can 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 joinpoint completes 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 allows you to define pointcuts by 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 application will be matched with the value attribute of the pattern property.
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 HandleRequestControllerclass:
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
Transaction password
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 transaction password is validated to authenticate the user.
The application ensures that the amount to be transferred does not exceed the available account balance.
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.jarfile 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 components while processing a user request:
Handler mappings
Controllers
View resolvers
View
You can derive the following benefits while creating applications that 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 application contains information about how to handle a particular Web request.
Slide 52 of 53© People Strategists www.peoplestrategists.com
Summary (Contd.)
The dispatcher servlet delegates the request to another Spring MVC component, known as controller.
You can create your own controllers by writing a class and annotating it as @Controller.
The ModelMap class is an implementation of the Map class.
Handler mappings in Spring are represented by the org.springframework.web.servlet.HandlerMapping interface.
Spring MVC framework provides the following implementations of handler mappings that you can use in your Web application:
BeanNameUrlHandlerMapping class
SimpleUrlHandlerMapping class
ControllerClassNameHandlerMapping class
Spring uses an interface, called as view, which is responsible for handing over 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 ViewResolver interfaces:
InternalResourceViewResolver
BeanNameViewResolver
ResourceBundleViewResolver
XmlViewResolver
The Spring tag library contains the following tags that you can use to bind the bean properties of the model object with the form components:
<spring:bind>
<spring:nestedPath>