Spring Tutorial
Spring Tutorial
Spring
Course Material
SUDHEER
NARESH i technologies
6/30/2012
SPRING SUDHEER
Introduction:
Architecture Diagrams:
1. Before Spring:-
Struts EJB
2. After Spring:-
Struts
Spring Framework:
NARESH i technologies
SPRING SUDHEER
Spring Modules
NARESH i technologies
SPRING SUDHEER
In Spring 1.x, the framework has divided into seven well-defined modules. But in Spring
2.x the framework is divided into 6 modules only.
1. Spring Core Module
2. Spring J2EE Module
3. Spring JDBC Module
4. Spring ORM Module
5. Spring AOP Module.
6. Spring MVC Module.
Spring
JDBC
Spring Core
(Inversion of Controller)
Spring Core Module:
This module provides the basic functionality required for a Spring application
Spring core module generates a high-level object of the Spring framework called
BeanFactory or ApplicationContext.
Spring core module applies IOC (Inversion of Control) or Dependency Injection for
generating Spring IOC container called as BeanFactory.
All frameworks will follows as an high level object is created first and it will have take
care about the low level object required for the application.
For Example
Struts Framework - ActionServlet
Hibernate Framework - SessionFactory
Spring Framework - BeanFactory
Spring J2EE module is an extension to core module where core module creates container
and J2EE module make it as a framework.
NARESH i technologies
SPRING SUDHEER
This module is providing an abstraction layer on top of existing JDBC technology and it
avoids the repeated JDBC code from an application.
Another advantage of this module is, we no need to handle exception while working
with database. Because in Spring all exceptions are unchecked exceptions.
Spring AOP
NARESH i technologies
SPRING SUDHEER
While developing Java Applications one object will collaborate or communicate with
another object for providing services to the clients.
If one object is communicating with another object i.e. If one object is calling the
business method of another object then we can say that there is a coupling between the
two objects.
In Object to Object collaboration, one object becomes dependent object and the other
object becomes caller object.
For example, If Traveler and Car are the two classes and Traveler class is depending on
car. In this case Traveler Object is called dependent Object and that car Object is called
Caller object.
Coupling refers to dependencies that exist between two things. Consider two classes for
an example. If one class is highly dependent on the implementation details of another
class this is considered as tight coupling. Sometimes even both classes might be
dependent on each others implementation details making it more coupled. If a class is
tightly coupled with another class, changing implementation details of main (depending)
class will affect all other dependent classes.
In the above example, Traveler Object is depending on Car Object. So Traveler class
creating an object of Car class inside it.
If directly the object is created in the dependent class then there exists tight coupling
and the above example there is a tight coupling between Traveler and Car Object.
In order to overcome tight coupling between objects, Spring Framework uses
Dependency Injection Mechanism.
NARESH i technologies
SPRING SUDHEER
With the help of POJO or POJI model and through Dependency Injection then it is
possible to achieve loose coupling.
In the above example, Traveler and Car are tightly coupled. If you want to achieve loose
coupling between the objects Traveler and Car, we need to rewrite the application like
the following.
Example:
Vehicle.java
package com.nit.Spring.ioc;
}
Car.java
package com.nit.Spring.ioc;
/**
* @author sudheer
*
*/
public class Car implements Vehicle{
@Override
public void move() {
// Business Logic
}
}
Bike.java
package com.nit.Spring.ioc;
/**
* @author sudheer
*
*/
public class Bike implements Vehicle {
@Override
NARESH i technologies
SPRING SUDHEER
// Business Logic
}
Traveler.java
package com.nit.Spring.ioc;
/**
* @author sudheer
*
*/
public class Traveler {
Vehicle vehicle;
In the above example, through Dependency Injection mechanism, Spring container will
inject either Car object or Bike Object into Traveler by calling setter method. So if Car
object is replaced with Bike object then no changes are required in Traveler class. It
means there is a loose coupling between Traveler Object and Vehicle Object.
NARESH i technologies
SPRING SUDHEER
Types of IoC:
Inversion of Control means, separating the implementation of an object from how the
object is constructed.
In case of Spring Framework the framework will take care of about the object creation
and injecting the dependent object required. As a programmer we are responsible for
only implementation of the business logic.
There are two types of IoCs
a. Dependency Lookup
b. Dependency Injection
Dependency Lookup
In this type of IoC, when one object is collaborating with another object, the first object
has to get all the dependencies required explicitly by itself.
In Dependency Lookup, an external person does not provide collaborating objects
automatically to first object.
In dependency lookup of IoC, the first object is responsible for obtaining its collaborating
objects from the container or registery etc.
For Example:
a. In Servlet with Connection pooling, Servlet object depends on datasource object. In
this case nobody automatically gives DataSource object to Servlet object. Servlet
itself goes to JNDI registry and takes DataSource object from the registery by
performing lookup operation.
NARESH i technologies
SPRING SUDHEER
Servlet Pool
3
DS DATA Con
n Con
SOURCE
Co Co n
4
nn nn
1
2
Key/DS
JNDI Register
b. In Servlet to EJB communication, Servlet depends on EJB Object, For calling the
business logic implemented in an EJB. In this communication nobody will provide EJB
object to Servlet object automatically. Servlet itself goes to EJB container and gets
the required EJB object from it. It means there is a Dependency Lookup.
Dependency Injection:
In this type of IoC, when one object is collaborating with another object, some other
external person will provide the collaborating object to the dependent object
automatically.
In this type of IoC the first object is not responsible to explicitly take the collaborating
objects required. It means the first object does not perform any lookup operation.
In case of Spring Framework, the external person who performs dependency injection is
called Spring IoC container.
NARESH i technologies
SPRING SUDHEER
EJB 3.0 Technology and Spring Framework both are supporting Dependency Injection
type of IoC.
Spring core container is the basis for the complete Spring Framework. It provides an
implementation for IoC supporting dependency injection.
This provides a convenient environment to program the basic to enterprise application
avoiding the need of writing the factory classes and methods in most of the situations.
This even helps one to avoid the need of programming in singletons.
The Spring core container takes the configurations to understand the bean objects that it
has to instantiate and manage the lifecycle.
The one important feature of the Spring core container is that it does not force the user
to have any one format of configurations, as most of the framework which are designed
NARESH i technologies
SPRING SUDHEER
to have XML based or Property file base configuration, or programmatically using the
Spring beans API. But in most of the cases we use XML based configurations since they
are simple and easy to modify.
The org.springframework.beans.factory.BeanFactory is the actual representation of the
Spring IoC container that is responsible for containing and otherwise managing the
aforementioned beans.
The BeanFactory interface is the central IoC container interface in Spring. Its
responsibilities include instantiating or sourcing application objects, configuring such
objects, and assembling the dependencies between these objects.
There are a number of implementations of the BeanFactory interface that come
supplied straight out-of-the-box with Spring. The most commonly used BeanFactory
implementation is the XmlBeanFactory class. This implementation allows you to express
the objects that compose your application, and the doubtless rich interdependencies
between such objects, in terms of XML. The XmlBeanFactory takes this XML
configuration metadata and uses it to create a fully configured system or application.
Produces
Configuration Metadata
As can be seen in the above image, the Spring IoC container consumes some form of
configuration metadata; this configuration metadata is nothing more than how you (as
NARESH i technologies
SPRING SUDHEER
Instantiating a container:
The Spring core container can be instantiated by creating an object of any one of the
BeanFactory or ApplicationContext classes supplying the Spring beans configurations.
The various implementation of BeanFactory are mainly differentiated based on the
Spring beans configuration format they understand and the way they locate the
configurations.
The following code snippet shows the sample code that instantiates the Spring container
using the Spring Beans XML configuration file as configuration metadata.
Syntax:
BeanFactory beans = new XmlBeanFactory (new FileSystemResource (beans.xml));
In the preceding code snippet we are using XmlBeanFactory implementation for
instantiating the Spring container with beans.xml file as a configuration file, as the
NARESH i technologies
SPRING SUDHEER
Setter Injection
In this type of Dependency Injection, the Spring (IoC) container uses setter method in the
dependent class for injecting its dependencies (Collaborators).
Spring Container knows whether to perform Setter Injection or Constructor Injection by
reading information from an external file called as Spring Configuration file.
In case of Setter Injection, the class must contain a setter method to get the
dependencies; otherwise Spring container does not inject the dependencies to the
dependent object.
Example
NARESH i technologies
SPRING SUDHEER
In the above example, Class A is called Dependent and Class B is called Collaborator.
In the Dependent class there is a setter method for getting collaborator object. So we call
it as Setter Injection.
In Spring Framework, we call each class as a Spring Bean .This Spring Bean is no where
related with Java Bean.
Spring Bean and Java Bean both are not same because a Java bean needs definitely a
public default constructor. But in a Spring bean sometimes we include default constructor
and sometimes we do not.
In Spring bean classes; there exists the following three types of dependency values.
i. Dependency in the form of Primitive Values
ii. Dependency in the form of Objects
iii. Dependency in the form of Collections
NARESH i technologies
SPRING SUDHEER
The Spring container understands whether dependency is in the form of primitive or not,
whether setter injection or constructor injection is required information by reading
Spring configuration file.
Spring Configuration file is identified with <any name>.xml
If the dependency in the form of primitives then we can directly provide value in the xml
file for that property.
In Spring configuration file, we used <property> element. So Spring container
understands that there is a Setter Injection in the bean class.
Inside <property> element, we have used <value> element. So Spring container
understands that the dependency is in the form of Primitives.
Syntax:
<property name=k>
<value>100</value>
</property>
In Spring Configuration file, we can use <value> as a sub element of <property> tag or
value as an attribute of <property> tag
Syntax:
<property name=k value=100/>
Example
a. Project Structure
NARESH i technologies
SPRING SUDHEER
b. PrimitivesDemo.java
C. PrimitivesClient.java
NARESH i technologies
SPRING SUDHEER
d. Output
Description of PrimitivesClient
Step 1:
A. Spring environment starts by loading Spring Configuration file into Resource Object.
NARESH i technologies
SPRING SUDHEER
Step 2:
A. Spring IoC container object will be created by reading bean definitions from the
Resource object.
B. Spring IoC container is called BeanFactory and this container is responsible for
creating the bean objects and for assigning its dependencies.
C. BeanFactory is an interface and XmlBeanFactory is an implementation class of it.
D. BeanFactory is an interface given in org.springframework.beans.factory and
XmlBeanFactory is a class given in org.springframework.beans.factory.xml package
Syntax:
BeanFactory beanFactory = new XmlBeanFactory(res);
Step 3:
A. Get the bean object from the Spring container by calling getBean() method.
B. While calling getBean() method, we need to pass the bean id as a parameter.
C. getBean() always return object.
D. We need to type cast the object into our Spring Bean type.
Syntax:
PrimitivesDemo pd = (PrimitivesDemo)obj;
Pd.getDetails ()
NARESH i technologies
SPRING SUDHEER
While constructing Spring Beans (Pojo Classes), one Spring bean class depends on
another Spring Bean class, for performing some business operations.
If one bean class is depending on another bean class object then we call it as an object
dependency.
If one bean class is depending on another bean class object then the Spring IoC
container is responsible for creating and injecting the dependencies.
In Spring Configuration file we have two ways to inform the container about this object
dependency.
1. By using inner beans.
2. By using <ref> element.
Inner bean means a bean which is added for a property by without an id in the xml file.
In case of inner bean definition with setter injection, we should add the <bean>
element, inside the <property> tag in xml.
NARESH i technologies
SPRING SUDHEER
Drawbacks of InnerBeans
An Inner bean does not have any id. So it is not possible to get that bean object
individually from the IoC container.
If another bean class is also depending on the same bean then in the xml file , again we
need to add the inner bean definition.
In order to overcome the above two problems of inner beans, we need to use <ref>
element in the Spring configuration file.
NARESH i technologies
SPRING SUDHEER
<ref> element
When dependencies are in the form of objects then to inform the IoC container, in
Spring configuration xml file, we need to configure <ref> element.
<ref> element is associated with either local or parent and bean attributes.
When we add <ref> element then we need to pass id of collaborator bean to its
attribute, because the dependency is in the form of objects.
Local
If local attribute is used with the <ref> element then the Spring IoC container will verify
for the collaborator bean within same container.
In general, we try to configure all Spring beans into a single Spring configuration file. But
it is not mandatory, because we can create multiple Spring configuration files also.
NARESH i technologies
SPRING SUDHEER
In the above xml file, both the dependent bean and its collaborator bean are configured
in the same xml file. It means into the same Spring IoC container. So we can use local
attribute with <ref> element.
By loading this above xml file, we will get the Spring IoC container object called
BeanFactory.
Syntax
Syntax
NARESH i technologies
SPRING SUDHEER
Parent
If parent attribute is used with <ref> element then the Spring IoC container will search
for the collaborator bean always at parent container. But not in the Same container.
parent.xml
child.xml
In the above xml files, dependent bean is available in beanFactory1 (child container) and
collaborator bean is available in beanFactory (parent container). So parent attribute is
suitable with <ref> element.
Bean
NARESH i technologies
SPRING SUDHEER
In this attribute is used with <ref> element then the Spring IoC container first verifies for
the collaborator bean in the same factory. If not available then it will search in the
parent factory.
Bean is the combination of both local and parent.
Bean first works like local and otherwise it works like parent.
parent.xml
Child.xml
Note:
1. While using <ref> element, if the given id is not found then null will be assigned into
the object, but an exception is not thrown.
2. If id is not found but class is not a suitable for the required type then an exception
will be thrown by the IoC container. The exception name is
org.springframework.beans.UnsatisfiedDependencyInjectionException.
NARESH i technologies
SPRING SUDHEER
Example:
1. Project Structure
ObjectDemo1.java
ObjectDemo2.java
NARESH i technologies
SPRING SUDHEER
ObjectClient.java
NARESH i technologies
SPRING SUDHEER
Parent.xml
Child.xml
NARESH i technologies
SPRING SUDHEER
Output:
While creating a Spring bean (Pojo) , the bean class can use any one of the following four
types of collections as a dependency.
1. Set - <set>
2. List - <list>
3. Map - <map>
4. Properties - <props>
Except the above four types of collections, if the Spring bean class uses any other type of
collection as a dependency then the Spring container does not inject that collection
object to the Spring bean. In this case spring programmer is responsible for injecting the
collection object manually.
Set Collection
If a Spring bean has a property of collection type set then in the Spring configuration file
we need to use <set> element to inform the Sprig IoC.
In Spring configuration file we can use <value> and <ref> tags as a sub elements of <set>
tab.
While configuring <set> element in the xml file it does not allow duplicate values.
Because set collection is unique collection.
In Spring Framework if one bean class is collaborating with another bean class then
Spring IoC container first creates collaborator bean object and after that dependent
bean object
Merging
NARESH i technologies
SPRING SUDHEER
Project Structure
DemoSet.java
SetClient.java
NARESH i technologies
SPRING SUDHEER
Set.xml
NARESH i technologies
SPRING SUDHEER
Output
List Collection
If a Spring bean is depending on a collection of type List then in Spring configuration file,
we need to configure <list> element.
We can use <value> and <ref> tags as sub elements of List
The differences between Set and List Collections are
Set List
Set is an unordered collection List is an ordered collection
Set does not allow dublicate values List allows dublicate values
Set does not allow index based accessing List allows index base accessing
Set does not support list iterator List support list iterator
Merging
NARESH i technologies
SPRING SUDHEER
Example
1. Project Structure
2. DemoList.java
NARESH i technologies
SPRING SUDHEER
3. DemoListClient.java
4. List.xml
NARESH i technologies
SPRING SUDHEER
Output:
} }
} }
What is Map.Entry in java?
Map.Entry is a class . Here map is an interface and Entry is a static class of Map
Interface. A Map stores data in the form of key/value pairs and we call each pair as one
NARESH i technologies
SPRING SUDHEER
entry. In the statement Map.Entry the meaning is we can create static classes inside an
interface. We call those classes as nested classes.
public interface Map
{
static class Entry
{
}
}
Map Collection
In a Spring bean if we take collection type as Map then in the Spring configuration file
we should configure the <map> element.
In Spring configuration file we need to use the sub element of map as <entry>.
In a map collection one entry represents key/value pair.
We use sub element of entry as either <value> or <ref> element.
Merging
Example
1. Project Structure
NARESH i technologies
SPRING SUDHEER
2. DemoMap.java
3. DemoClient.java
NARESH i technologies
SPRING SUDHEER
4. Map.xml
NARESH i technologies
SPRING SUDHEER
OUT PUT
Properties Collection
Properties collection also stores data in the form key/value pairs. But both key/value are
considered as Strings.
If we take Properties collection in the Spring bean then in the Spring configuration file,
we need to use <props> element.
The sub element of <props> is <prop> and the <prop> element does not any have
subelements.
Merging
NARESH i technologies
SPRING SUDHEER
A parent-style <props/> element can have child-style <props/> element which inherit
and overrides the values from the parent collection.
For collection merging you need to specify merge=true attribute on the <props/>
element of child bean definition.
Example:
1. Project Structure
2. DemoProps.java
NARESH i technologies
SPRING SUDHEER
PropsClient.java
3. Props.xml
NARESH i technologies
SPRING SUDHEER
Output:
Constructor Injection
The constructor Injection method of dependency injection is the method of injecting the
dependencies of an object through its constructor arguments. In this mechanism the
dependencies are pushed into the object through the constructor argument at the time
of instantiating.
Constructor Injection is a Dependency Injection variant where an object gets all its
dependencies via the constructor. This is PicoContainer's most important feature.
The most important benefits of Constructor Injection are:
It makes a strong dependency contract
It makes testing easy, since dependencies can be passed in as Mock Objects
It's very succinct in terms of lines of code
Classes that rely on Constructor Injection are generally Good Citizens
A dependency may be made immutable by making the dependency reference
final
In the case when the object is instantiated by using some factory method then passing
the dependencies as arguments to the factory method is also considered as constructor
injection since the dependencies are injected at the time of constructing the object.
The following code snippet shows the sample class that allows the injection of its
dependencies as constructor arguments.
The bean definition can describe to use a constructor with zero or more arguments to
instantiate the bean
The <constructor-arg> element describes one argument of the constructor, which means
that to specify a constructor with multiple arguments we need to use <constructor-arg>
element multiple times.
The zero <constructor-arg> tags in bean definition describes the use of the no-argument
constructor. The arguments specified in the bean definition correspond to either a
specific index of the constructor argument list or are supposed to be matched
generically by type. <constructor-arg> element supports four attributes
NARESH i technologies
SPRING SUDHEER
Index This attribute takes the exact index in the constructor argument list.
This is used to avoid ambiguities like in case of two arguments being of the same type
Example
Project Structure
ConstructorDemo.java
NARESH i technologies
SPRING SUDHEER
ConstructorClient.java
Constructor.xml
NARESH i technologies
SPRING SUDHEER
OUT PUT
If A and B are two classes/beans and if A depends on B and B depends on A then we will
get Circular Dependency.
When circular dependency is occurred then we cannot solve this problem with the help
of Constructor Injection.
In this case, instead of constructor injection we need to use setter injection.
For Example
NARESH i technologies
SPRING SUDHEER
Example
NARESH i technologies
SPRING SUDHEER
1. A.java
2. B.java
3. CircularDemo.java
NARESH i technologies
SPRING SUDHEER
Cic.xml
In the client application, when we call factory.getBean(a) internally the following steps
are executed
i. Spring container creates a mock object of class A using default constructor of
class A.
ii. Spring container create a class B object by passing the mock object of class A
into its constructor.
iii. Spring container injects class B object into class A by calling setter method.
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
byType
In this case the Spring Framework attempts to find out a class in the xml file whose
name is matching with the property type to be wired or not.
If found then injects that class object by using setter Injection.
If no class found in xml with the same name then that property remains unwired.
If a class is found in xml for more than once then Spring Framework throws
UnSatisfiedDependencyException.
NARESH i technologies
SPRING SUDHEER
Constructor
This autowire type is equal to byType. But here constructor injection will be executed.
Example: Previous Example modify with constructor
Autodirect
This type of autowiring first work likes a constructor and if not then it works like byType.
NARESH i technologies
SPRING SUDHEER
If we enable the dependency validation then Spring container verifies whether all
dependencies are set or not. If not the container does not create an object and throws
an Exception.
To enable dependency validation we need to add dependency-check attribute for the
<bean>.
The different values of dependency-check attribute are
i. no (by default)
ii. Simple
iii. Object
iv. All
Simple
In this case Spring container verifies for primitives and collections are set or not. If not
set then exception will be thrown.
Objects
In this case the Spring Container verifies whether objects are set or not. If not the
container throws an Exception
All
In this case the container verifies for objects, primitives and collections.
Example
DemoBean.java
NARESH i technologies
SPRING SUDHEER
TestBean.java
ValidateClient.java
NARESH i technologies
SPRING SUDHEER
Validate.xml
Output
NARESH i technologies
SPRING SUDHEER
ii. destroy()
Code Snippet
In the above bean class when a client request is given for getting the bean object then
internally the following steps are executed.
a. Object is created
b. Properties are injected.
c. afterPropertiesSet() called
d. Now object is given to Client application.
Before container is removing the object then container first calls the destroy() and then
removes that object from the memory.
In the above code snippet the drawback is our class is not a POJO class. Because it is
implementing from predefined interfaces given by the framework.
So we can rewrite the above bean class by adding our own methods for initialization and
cleanup;
In this case the bean into xml we have to add init-method and destroy-method attributes
for <bean> element.
In this case container will do the following before giving the object to client.
a. Object is created
b. Properties are injected
c. Inint() called
d. Now object is given to client.
When Container is going to to remove the object first it calls tearsDown() method and
after that Object is removed.
Example
NARESH i technologies
SPRING SUDHEER
Project Structure:
LifeBean.java
ClientForLife.java
NARESH i technologies
SPRING SUDHEER
Init.xml
NARESH i technologies
SPRING SUDHEER
Scope Definition
singleton Scopes a single bean definition to a single object instance per Spring
IoC container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP
request; that is each and every HTTP request will have its own
instance of a bean created
off the back of a single bean definition. Only valid in the context of a
web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of a HTTP Session.
Only valid in the context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the lifecycle of a global HTTP
Session. Typically only valid when used in a portlet context. Only valid
in the context of a web-aware Spring ApplicationContext.
The Singleton Scope
When a bean is a singleton, only one shared instance of the bean will be managed, and
all requests for beans with an id or ids matching that bean definition will result in that
one specific bean instance being returned by the Spring container.
NARESH i technologies
SPRING SUDHEER
Bean Instantiation
Spring Framework instantiates or gets a Spring bean object by using the following three
ways.
i. By Calling Constructor.
ii. By Calling Static Factory method
iii. By Calling an instance factory method.
By Calling Constructor
When we call getBean(id1) method from the client application then the Spring IoC
container uses new operator and calls constructor of the class and gets an object of the
bean class.
After getting the bean object, it will apply injections and after that other initializations
and then returns that bean object to the client application.
NARESH i technologies
SPRING SUDHEER
If we change the bean scope to prototype then the IoC container gets|created new
object for each call to the getBean(id1) method.
By Calling static factory method
By default Spring IoC container makes each bean as singleton. But when the scope of a
bean is changed to prototype then the bean object becomes non-singleton.
If a Spring programmer doesnt want to make a Spring bean as prototype bean then the
programmer has to explicitly make the bean class as singleton.
To make a bean class as Singleton the following rules are need to be followed.
a. Create a Private static object to the class, inside the class.
b. Create a private constructor
c. Create a public static factory method.
Code Snippet
While configuring the above bean class into Spring configuration file, we need to inform
the Spring IoC container that calls static factory method of the bean class to get an
object of the bean class.
To inform the Spring IoC container we should add an attribute called factory-method to
the <bean>element.
NARESH i technologies
SPRING SUDHEER
When getBean(sb) method is called from the client application then the IoC container
will get the bean object by using the following statement internally.
SampleBean sb = new SampleBean();
How to create Synchrozed Singleton class in java?
If we add Synchronized keyword for the static factory method then the class becomes
synchronized singleton class.
By Calling Instance factory method
In this approach Spring IoC container class the factory method defined in one class to get
an object of another bean class.
In Java we have two types of factory methods
1. Static factory method
2. Instance factory method
A factory method may or may not return same class object. But a factory method must
return an object.
NARESH i technologies
SPRING SUDHEER
In the below xml, for the bean tb1 we have removed class attribute and we have
added factory-bean attribute.
In a Client application when we call factory.getBean
. (id1) internally the following statements are executed by the container.
TestBean1 tb1 = new TestBean1();
1. Inject Dependenc
2. Calls aftPropSet
3. Call customInit
NARESH i technologies
SPRING SUDHEER
Spring JDBC
Introduction:
JDBC technology is required either directly or indirectly for getting a connection with the
database.
Without using JDBC technologies we cannot able connect with databases using Java.
If a programmer is directly working with JDBC technology then there are some problems
facing by the Java Programmer.
a. JDBC technology exceptions are checked exceptions. There we must put try and
catch blocks in the code at various places and it increases the complexity of the
applications.
b. In a Java Program, repetitive code is required to perform operations on databases
from the various client applications. The repetitive code is like loading the drivers,
connection opening, creating a statement and finally closing the objects of JDBC. This
kind of repetitive code, we call as Boilerplate Code.
c. In JDBC, if we open the connection with database then we are responsible to close it.
If the connection is not closed then later at some point of time, we may get out of
connections problem.
d. JDBC throws error codes of the database when an exception is occurred sometimes
the error codes are unknown of the Java Programmer and error codes are different
from one database to another database. Therefore developing JDBC applications
using those error codes will make our application as database dependent.
Spring JDBC frame work has provided an abstraction layer on top of the existing JDBC
technology.
Spring JDBC layer concentrates on avoiding connection management coding and error
management and Spring JDBC programmer will concentrate on construction and
execution of the SQL operations.
Spring framework has provided an exception translator and it translates the checked
exceptions obtained while using JDBC into unchecked exceptions of Spring type and
finally the unchecked exceptions are thrown to the Java Programmer.
While working with Spring JDBC, the programmer no need to open and close the
database connection and it will taken care by the Spring framework.
NARESH i technologies
SPRING SUDHEER
Table 1.1
The following table describes which actions is developers responsibility and which
actions are taking care by Spring itself:
The Spring Framework's JDBC abstraction framework consists of four different packages,
namely core, datasource, object, and support.
The org.springframework.jdbc.core package contains the JdbcTemplate class and its
various callback interfaces, plus a variety of related classes.
A sub-package named org.springframework.jdbc.core.simple contains the
SimpleJdbcTemplate class and the related SimpleJdbcInsert and SimpleJdbcCall classes.
Another sub-package named org.springframework.jdbc.core.namedparam contains the
NamedParameterJdbcTemplate class and the related support classes.
The org.springframework.jdbc.datasource package contains a utility class for easy
DataSource access, and various simple DataSource implementations that can be used for
NARESH i technologies
SPRING SUDHEER
testing and running unmodified JDBC code outside of a J2EE container. The utility class
provides static methods to obtain connections from JNDI and to close connections if
necessary. It has support for thread-bound connections, e.g. for use with
DataSourceTransactionManager.
Next, the org.springframework.jdbc.object package contains classes that represent
RDBMS queries, updates, and stored procedures as thread safe, reusable objects. This
approach is modeled by JDO, although of course objects returned by queries are
disconnected from the database. This higher level of JDBC abstraction depends on the
lower-level abstraction in the org.springframework.jdbc.core package.
Finally the org.springframework.jdbc.support package is where you find the
SQLException translation functionality and some utility classes. Exceptions thrown
during JDBC processing are translated to exceptions defined in the
org.springframework.dao package. This means that code using the Spring JDBC
abstraction layer does not need to implement JDBC or RDBMS-specific error handling. All
translated exceptions are unchecked giving you the option of catching the exceptions
that you can recover from while allowing other exceptions to be propagated to the
caller.
DataSource:
A Java application can get a connection with a database using the following two ways.
i. java.sql.DriverManager (class)
ii. javax.sql.DataSource (Interface)
Spring framework always uses DataSource interface to obtain a connection with the
database internally.
DataSource interface is also having different types of implementation.
i. Basic Implementation, it is equal to DriverManager.
ii. Connection pooling implementation.
iii. Transaction implementation.
NARESH i technologies
SPRING SUDHEER
While using DataSource, it is always does not mean that we are working with connection
pool. If internal implementation class is connection pool enabled then only the
DataSource will provide a logical connection from the pool.
In Spring framework we use any one of the following two implementation classes of
DataSource interface
i. org.springframework.jdbc.datasource.DriverManagerDataSource
ii. org.springframework.jdbc.datasource.BasicDataSource
The above two classes are suitable, when our Spring application is under development
mode.
In Production mode, the Spring application uses connection pooling service provided by
the application servers.
In the above two classes, DriverManagerDataSource is given by Spring framework and it
is equal to DriverMangerClass.It means Spring framework internally opens a new
connection.
BasicDataSource is given by apache .common-dbcp project and it is better than
DriverManagerDataSource. Because BasicDataSource has inbuilt connection pooling
implementation.
Configuration
In Spring Configuration file, we need to configure the following four properties to obtain
the connection with the database.
i. driverClassName
ii. url
iii. username
iv. password
.00
. Syntax:
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
2. The following code snippet for BasicDataSource configuration in Spring configuration file.
Installation:
The following jar file is set as class path for working with Spring Jdbc framework.
A. org.springframework.jdbc-3.0.6.RELEASE.jar
JdbcTemplate:
It simplifies the use of JDBC since it handles the creation and release of resources. This
helps to avoid common errors such as forgetting to always close the connection.
NARESH i technologies
SPRING SUDHEER
It executes the core JDBC workflow like statement creation and execution, leaving Data
access using JDBC Spring Framework application code to provide SQL and extract results.
This class executes SQL queries, update statements or stored procedure calls, imitating
iteration over ResultSets and extraction of returned parameter values.
It also catches JDBC exceptions and translates them to the generic, more informative,
exception hierarchy defined in the org.springframework.dao package.
Code using the JdbcTemplate only need to implement callback interfaces, giving them a
clearly defined contract. The PreparedStatementCreator callback interface creates a
prepared statement given a Connection provided by this class, providing SQL and any
necessary parameters. The same is true for the CallableStatementCreator interface
which creates callable statement. The RowCallbackHandler interface extracts values
from each row of a ResultSet.
The JdbcTemplate can be used within a DAO implementation via direct instantiation with
a DataSource reference, or be configured in a Spring IOC container and given to DAOs as
a bean reference.
Instantiation:
In case first case, DataSource object is injected to JdbcTemplate by calling setter injection
Configuration:
NARESH i technologies
SPRING SUDHEER
Code snippet: 1.3 The above code snippet for JdbcTemplate for instantiation by using setter
Injection
NARESH i technologies
SPRING SUDHEER
Code snippet: 1.4 The above code snippet for JdbcTemplate for instantiation by using
constructor Injection
API Methods:
This is method is used to execute both DDL and DML operations on the Database.
This method allows only static sql command. It means the sql command should not
contain ? symbol
This is suitable to perform DDL operations on the Database. Because, for DML
operations, this method doesnt return the count value back to the programmer.
This method is used to execute only DML operations on the database. It means either
insert or update or delete.
NARESH i technologies
SPRING SUDHEER
If we use a single parameter then we need to pass static SQL command and otherwise
we can use the following method.
Syntax:
int update(Strinq sql,object obj[])
In case of dynamic command, first we need to store all objects into an object array and
then we need to pass that object array as a parameter.
Syntax:
object params[] = {Spring,jdbc};
int k = jt.update(insert into spring values(?,?), params);
This method is used to get the result of select command in the form of required object.
We have to pass the required class type, in the form a class Object as a second
parameter
Syntax:
Object obj = jt.queryForObject(select sysdate from dual ,Date.class);
Object obj = jt.queryForObject(select avg(sal) from emp,Integer.class);
NARESH i technologies
SPRING SUDHEER
This method is used for selecting one or more rows/records from the database table.
Internally JdbcTemplate stores all the rows into a array for each row and finally stores all
these object array into a collection of type ArrayList and the list object is given back to
the programmer.
While iterating the collection the programmer has type cast the result in to an object
array.
Syntax:
List l = jt.queryForList (select * from EMP);
Iterator it = l.iterator();
while (it.hasNext ())
{
Map map = (Map) it.next ();
}
Example
1. Project Structure
NARESH i technologies
SPRING SUDHEER
2. EmployeeDao.java
NARESH i technologies
SPRING SUDHEER
EmployeeDaoImpl.java
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
Jdbc.xml
TemplateClient.java
NARESH i technologies
SPRING SUDHEER
Outputs
While configuring a DataSource implementation class into a Spring configuration xml file,
we are placing directly the connection properties into the xml file.
Instead of directly placing the values into the xml file, we can load the values at runtime
for the DataSource properties from ResourceBundle.
If we want to get the DataSource properties at run time from a ResourceBundle then
while configuring the bean into xml file. We should put the bundle keys with expression
language into the xml file.
NARESH i technologies
SPRING SUDHEER
Syntax:
In to the above bean definition, the values are passed at runtime from the
ResourceBundle. The Bundle is like the following.
Example
NARESH i technologies
SPRING SUDHEER
1. Project Structure
Jdbc.properties
Jdbc.xml
NARESH i technologies
SPRING SUDHEER
DataSourceDemo.java
Output:
NARESH i technologies
SPRING SUDHEER
NamedParameterJdbcTemplate
If you like, you can also pass along named parameters (and their corresponding values)
to a
NamedParameterJdbcTemplate instance using the (perhaps more familiar) Map-based
style. (The rest of the methods exposed by the NamedParameterJdbcOperations - and
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
Calling Procedures/Functions:
To call a procedure or a function from a database, we- have two approaches in Spring i.e.
by extending StoredProcedure class and by without extending it.
If we want to call a procedure or a function then the simple approach is by extending our
bean class from StoredProcedure. (Abstract class but not abstract methods).
If we want to call procedures/functions of the database then the following steps are
need to be followed.
1. Extend the bean class from StoredProcedure.
2. Call the base class constructor from our bean class by passing datasource object,
name of the procedure name or function as parameters.
Syntax:
super (datasource,pro1);
3. Declare the keys in the form of sqlParameter objects that are used as keys for map
objects.
4. Call execute () method from the business method of the bean by passing the input
values in the form of map object.
5. Read the output values returned into the map object from the procedure or function.
Example
1. Project Structure
DBSteps:
NARESH i technologies
SPRING SUDHEER
StoredProcedureDemo.java
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
Proc.xml
ProcedureDemo.java
NARESH i technologies
SPRING SUDHEER
When we configure BasicDataSource into Spring configuration xml file then implicitly
Spring application is using connection pool service. Because BasicDataSource class has a
inbuilt connection pool service.
The inbuilt connection is only suitable for small scale applications, but not for production
level applications.
If a Spring application or any other java application wants to get a connection from an
external connection pool then the application need a mediator object called DataSource,
which is configured in the server.
When a DataSource is configured by the server administrator then it will be stored in
JNDIRegistery with some JNDI name.
If any Java application wants to get connection pool service of a server then the
application has to get the DataSource object from the Registry.
If an application wants to get DataSource object then it need JNDI name.
A
2 POOL 1
T
A
Con co
S n nn
n
O
6 con
Con DS
U nn
n
n
7 R
NARESH i technologies
S
KEY
5 DS 3
E JNDIRegistery
SPRING SUDHEER
In case of Spring Framework, the Programmer is not responsible for opening and closing
of the Database connection and it is done by JdbcTemplate.
JdbcTemplate need JNDI name of the DataSource object to configure the
JndiObjectFactoryBean.
JdbcTemplate is a class which depends on JndiObjectFactoryBean for getting a
connection from the connection pool.
In the Spring configuration file we need to configure JndiObjectFactoryBean and
JdbcTemplate like the following.
http://localhost:7001/console
NARESH i technologies
SPRING SUDHEER
Step 3: At Left Side expand Services -> expand JDBC -> Select DataSources -> Cick on
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
Example:
Project Structure:
NARESH i technologies
SPRING SUDHEER
ConnectionPoolingDemo.java
NARESH i technologies
SPRING SUDHEER
Pooling.xml
JndiClient.java
NARESH i technologies
SPRING SUDHEER
In a Spring bean class while selecting records from a table instead of calling
queryForList() method, we can also call queryForSet() method.
The advantage of using queryForSet() method is , it returns the selected records in the
form of a RowSet object and this RowSet object can be transferred across between from
one machine to another machine. Because RowSet object is Serialized object.
In Spring Framework a class given to support RowSet behavior called SqlRowSet this
class is given in org.springframework.jdbc.support.rowset.* package
If we store the selected records in a RowSet object then we can use methods of RowSet
for moving the cursor in different directions for reading our data.
Syntax
RowMapper Interface:
When selecting records from a database table internally Spring Framework stores all the
records into a ResultSet object and the framework converts the rows into map objects
and those map objects are stored in List.
Instead of Storing each row of a ResultSet in a map object, if we want to store in a POJO
class object then we need to use RowMapper interface.
In case of RowMapper internally for each record of the ResultSet ,its mapRow() method
is
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
SPRING ORM
The Spring Framework provides integration with Hibernate, JDO, Oracle TopLink, iBATIS
SQL Maps and JPA: in terms of resource management, DAO implementation support,
and transaction strategies. For example for Hibernate, there is first-class support with
lots of IoC convenience features, addressing many typical Hibernate integration issues.
Some of the benefits of using the Spring Framework to create your ORM DAOs include:
Ease of testing. Spring's IoC approach makes it easy to swap the implementations and
config locations of Hibernate SessionFactory instances, JDBC DataSource instances,
transaction managers, and mappes object implementations (if needed). This makes it
much easier to isolate and test each piece of persistence-related code in isolation.
Common data access exceptions. Spring can wrap exceptions from your O/R mapping
tool of choice, converting them from proprietary (potentially checked) exceptions to a
common runtime DataAccessException hierarchy. This allows you to handle most
persistence exceptions, which are non-recoverable, only in the appropriate layers,
without annoying boilerplate catches/throws, and exception declarations. You can still
trap and handle exceptions anywhere you need to. Remember that JDBC exceptions
(including DB specific dialects) are also converted to the same hierarchy, meaning that
you can perform some operations with JDBC within a consistent programming model.
General resource management. Spring application contexts can handle the location and
configuration of Hibernate SessionFactory instances, JDBC DataSource instances, iBATIS
SQL Maps configuration objects, and other related resources. This makes these values
easy to manage and change. Spring offers efficient, easy and safe handling of persistence
resources. For example: related code using Hibernate generally needs to use the same
Hibernate Session for efficiency and proper transaction handling. Spring makes it easy to
NARESH i technologies
SPRING SUDHEER
transparently create and bind a Session to the current thread, either by using an explicit
'template' wrapper class at the Java code level or by exposing a current Session through
the Hibernate SessionFactory (for DAOs based on plain Hibernate API). Thus Spring
solves many of the issues that repeatedly arise from typical Hibernate usage, for any
transaction environment (local or JTA).
Integrated transaction management. Spring allows you to wrap your O/R mapping code
with either declarative, AOP style method interceptor, or an explicit 'template' wrapper
class at the Java code level.
While integrating Spring Framework with ORM tools we have the following two
approaches.
We can directly use the ORM tool API into Spring bean for performing DataAccessLayer
logic.
We can use the abstraction layer given by Spring Framework on top of existing ORM
tools for performing DataAccessLayer Operations.
ORM is a translator or an engine it acts as a bridge between a Java application and a
database server and internally translates object into text format and vice versa.
Spring ORM module provides DAO pattern implementation.
The advantage of Spring Framework has given a single exception hierarchy irrespective
of the persistence technology used.
While integrating Spring Framework with hibernate we use the abstraction layer which is
given by Spring Framework and it internally uses hibernate ORM framework.
Spring Framework has provided a central class to perform database operations in the
form of objects called HibernateTemplate.
While integrating the Spring Framework with hibernate then the Hibernate setup
required need to be configured with a Spring Framework provided class called
LocalSessionFactoryBean.
While integrating Spring with hibernate we do not require to construct hibernate
configuration file. Instead we need to configure LocalSessionFactory.
LocalSessionFactoryBean constructs SessionFactory of hibernate internally.
HibernateTemplate is a class which internally uses Session API of hibernate.
As a part of Spring Hibernate integration we configure the following two classes given
by Spring Framework.
i. LocalSessionFactoryBean
ii. HibernateTemplate
The above two classes are given in org.springframework.orm.hibernate3 package.
NARESH i technologies
SPRING SUDHEER
Code Snippet:
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
Table:
Syntax:
create table employee (eno number(10) primary key, ename varchar2(30), address
varchar2(100))
Employee.java
NARESH i technologies
SPRING SUDHEER
EmployeeDao.java
EmployeeDaoImpl.java
NARESH i technologies
SPRING SUDHEER
Orm.xml
NARESH i technologies
SPRING SUDHEER
ORMClient.java
NARESH i technologies
SPRING SUDHEER
Output
It is also possible to integrate the Spring and hibernate by directly importing hibernate
API into Spring bean.
While using direct hibernate into Spring bean than the SesssionFactory of hibernate
should be made as singleton by the programmers.
Inorder to make the SessionFactory as singleton in a Spring bean then we must add init
and destroy methods to Spring bean class.
Either we can implement our bean class from InitializingBean and DisposableBean
interfaces or we can include one method for initialization and other method for destroy.
NARESH i technologies
SPRING SUDHEER
If we add our methods for initialization and destroy then we have to inform the Spring
IoC container by adding init-method and destroy-method attributes for the bean
element.
Code Snippet 1:
Spring AOP
NARESH i technologies
SPRING SUDHEER
Introduction
We are aware that nowadays the most widely used methodology for developing
enterprise applications is Object oriented programming (OOP).The OOP methodology
was introduced in the 1960s to reduce the complexity of the software and improve its
quality. This achieved by modularization and reusability. This allow developers to view
the Software as a collection of objects that interact with each other, allowing easy
solving of critical problems and developing reusable units of software
While implementing business logic for the real time applications we need not only the
business logic but also some services to it, to make it as enterprise logic.
While implementing the business logic in the business methods we can combinable
implement both the logic and its required services into the business methods.
In order spring framework the services that are overlapping on the business logic are
called as cross-cutting concerns or cross-cutting functionalities.
Example
If combinable implement the business logic and the required services then there are
some drawbacks
a. The services and the business logic in each method, increases the size of a Java Class.
Therefore complexity increases.
b. If the same services are required in another business method then we cannot reuse
those services and in each method separate implementations are required.
NARESH i technologies
SPRING SUDHEER
c. If any changes in some service in one method then that changes does not impact on
same services of another method.
d. Selecting services dynamically at runtime is not possible.
In order overcome the above problems we need to separate the business logic and the
service. We can call this separation of the business logic and cross-cutting functionality
as aspect oriented programming.
Authentication
Login
Transaction
The AOP the business logic and cross cutting functionality are implemented separately
and executed at runtime as combinable.
Terminology
Aspect:
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
An advisor advising advices to various Joinpoints we call advisor has a pointcut advisor.
We have two types of Advisor.
NARESH i technologies
SPRING SUDHEER
Advice API:
Advice is an object that includes API invocation to systemwide concerns representing the
action to perform at a joinpoint specified by pointcut.
The different types of advices that Spring AOP framework supports are:
i. Before advice: The advice that executes before the joinpoint.
ii. After returning advice: The advice that executes after the joinpoint execution
completes normal termination.
iii. Throws advice: The advice that executes after the joinpoint execution if it
completes with abnormal termination.
iv. Around advice: The advice that can surround the joinpoint providing the advice
before and after executing the joinpoint even is controlling the joinpoint invocation.
Before Advice
The before advice is the advice that executes before the joinpoint.That means this type
of advice allows us to intercept the request and apply the advice before the execution of
joinpoint.
In order to create a BeforAdvice our class should implement MethodBeforeAdvice
interface.
MethodBeforeAdvice is an interface given in org.springframework.aop package.
The org.springframework.aop.MethodBeforeAdvice interface has only one method
with following signature.
For Example
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
the interceptor chain, the client is throw with exception, not a normal termination
1 : some Method()
2 : before()
3 : before()
4 : before()
5 : some Method()
6 : <return value>()
7 : <return value>()
The following sequence diagram describing the operations when before advice
execution terminates abnormally, that is, throwing exception.
NARESH i technologies
SPRING SUDHEER
1 : some Method()
2 : before()
3 : before()
4 : <exception>()
5 : <exception>()
As shown in figure, in the case where before advice throws an exception then an
exception is thrown to the client without continuing further the interceptors
execution and target object method.
NARESH i technologies
SPRING SUDHEER
The following diagram describing the exception handling done by proxy when
advice throws an exception.
NARESH i technologies
SPRING SUDHEER
b. AccountService.java :
This Interface have two abstract methods performing withdraw and deposit methods.
NARESH i technologies
SPRING SUDHEER
c. AccountServiceImpl.java
d. AccountDao.java
NARESH i technologies
SPRING SUDHEER
e. AccountDaoImpl.java
f. MyException.java
NARESH i technologies
SPRING SUDHEER
g. LoggingAdvice.java
h. log4j.properties
NARESH i technologies
SPRING SUDHEER
i. applicationContext.xml
NARESH i technologies
SPRING SUDHEER
j.
k. Client.java
Output:
sudheer.html
The after returning advice is the advice that executes after the joinpoints invocation
completes with normal termination.
This advice has to be a subtype of org.springframework.aop.AfterReturningAdvice
interface.
The org.springframework.aop.AfterReturningAdvice interface has only one abstract
method.
NARESH i technologies
SPRING SUDHEER
Syntax
Where the first parameter contains return value of the business method or null.
If a business method return type is void then the return value contains null
In this afterReturning advice, we can access the return value. But we can not modify this
return value.
NARESH i technologies
SPRING SUDHEER
Throws Advice:
The throws advice is the advice that executes after the joinpoints invocation completes
with an abnormal termination.
This advice has to be a subtype of org.springframework.aop.ThrowsAdvice interface.
The org.springframework.aop.ThrowsAdvice is a marker interface and does not declare
any methods.
This type of advice should implement one or more methods with the following method
signature.
The throws advice can listen for the exceptions thrown by the method invoked on the
target object but not the exceptions thrown by the advices configured for the target
object.
The throws advice can handle the exception but it cannot stop the exeception throwing
to the client.
Syntax
The afterThrowing() method can encapsulate the exception handling logic like in an
instance when an ArthimeticException is thrown we want to prepare a relevant message
and send an email to the administrator.
NARESH i technologies
SPRING SUDHEER
SequenceDiagram
Around Advice:
NARESH i technologies
SPRING SUDHEER
Around advice is not given by Spring AOP and it is an opensource implementation call
AOP Alliance.
Around Advice can be used by any framework which is supporting AOP.
To create around advice, our class should implement an interface called
MethodInterceptor.
In Around Advice, we implement before and after services in a single method called
invoke().In order to separate before and after services and to execute business logic of
the method in the middle, we call proceed().
Syntax
NARESH i technologies
SPRING SUDHEER
Class Diagram
The invoke() method implemented in around advice can call the proceed() method on
the given MethodInvocation object.
The code that has to execute before the joinpoint execution has to be written before
calling proceed() method and the code to execute after the joinpoint execution has to be
written after the procedd() method.
Sequence Diagram:
NARESH i technologies
SPRING SUDHEER
NARESH i technologies
SPRING SUDHEER
MVC Architecture
N-Tier architecture refers to the architecture of an application that has at least three
tiers separated logically or physically.
This architecture model allows us to design application with any number of tiers
arranged above another.
N-tier architecture is important because each tier in this can be located on physically
different servers.
In case of applications that present a large amount of data to the user, it is
recommended to separate data and user interface concerns so that changes to the user
interface will not affect data handling, and that the data can be recognized without
changing the user interface.
The Model-View-Controller pattern solves this problem by decoupling data access and
business logic from data presentation and user interaction, by introducing an
intermediate component controller.
The responsibilities of Model, View and Controller as defined under the MVC pattern
are:
Model: This tier is responsible to represent business process and business data of
application.
View: This tier is responsible to prepare the presentation for the client based on the
outcome of request processing. That is, this renders the model data into clients user
interface type.
Controller: This tier is responsible for controlling the request to response flow in the
middleware.
MODEL-1 ARCHITECTURE
In this model, the client directly accesses the pages in the web container, and these
pages service the entire the request and response back.
While servicing the client requests these pages generally use a model which represents
the business logic for the application.
These pages are usually implemented using JSP pages, sometimes Servlets, and model as
Beans.
NARESH i technologies
SPRING SUDHEER
In this architecture, controlling and presentation are mixed into a single component, and
hence this model architecture is also known as page-centric architecture.
1 Controller and
Request Presentation (JSP)
Client
5
(Browser) 4 2
3
Model (Java Bean) DataStore
(DB)
Model1 Architecture
MODEL-2 ARCHITECTURE
NARESH i technologies
SPRING SUDHEER
We know that patterns are strategies that allow programmer to share knowledge about
the recurring problems and their solutions.
Documenting patterns is one way we can reuse and possibly share information on how
best it is solve to solve a specific problem.
And a well-known definition for a pattern: A pattern is a tree-path rule, which express a
relation between a certain context, problem, and Solution.
Context we have decided to use Model-View-Controller(MVC) pattern to separate the
user interface logic from the business logic of web application. We have reviewed the
Page Controller pattern,but page controller classes have complicated logic, or our
application determines the navigation between pages dynamically based on configurable
rules.
Problem: we want to structure the controller for very complex web application in the
best possible manner so that we can achieve reuse and flexibility while avoiding code
duplication and decentralization problems in page controller.
Forces
The following are the characteristics of the forces from the MVC that applies the Front
Controller pattern:
a. If common logic is replicated in different pages in the system, we need to centralize
this logic to reduce the amount of code duplication. Removing the duplicated code is
critical in improving the overall maintainability of the System.
b. We want to separate system processing logic from View.
c. The Page Controller pattern describes a separate controller per logical page. This
solution breaks down when you need to control or coordinate processing across
multiple pages.
Solution
Use a Front Controller as the initial point of contact for handling all related requests. The
Front Controller solves the decentralization problem present in Page Controller by
channeling all requests through a single controller that is, it centralizes control logic that
is otherwise duplicated, and even manages key request handling activities, like protocol
handling, context information, navigation and routing, and dispatch.
Protocol Handling is a process of handling a protocol-specific request, which involves in
resolving the request given in a specific protocol format and preparing a message in a
specific protocol format.
NARESH i technologies
SPRING SUDHEER
Context Transformation is a process of converting the protocol specific data into a more
general form, like into our system-defined java bean object or into a general collection
object.
Navigation is a process that chooses the object for handling a particular request that can
perform the core processing for this request and the view that can present the response
to the client.
Dispatch involves in dispatching the request from one part of the application to another,
like from request handling object to view processing components.
Spring provides a very clean division between controllers, JavaBean models, and views.
Spring's MVC is very flexible. Unlike Struts, which forces your Action and Form objects
into concrete inheritance (thus taking away your single shot at concrete inheritance in
Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of
the Spring MVC framework is configurable via plugging in your own interface. Of course
we also provide convenience classes as an implementation option.
Spring, like WebWork, provides interceptors as well as controllers, making it easy to
factor out behavior common to the handling of many requests.
Spring MVC is truly view-agnostic. You don't get pushed to use JSP if you don't want to;
you can use Velocity, XLST or other view technologies. If you want to use a custom view
mechanism - for example, your own templating language - you can easily implement the
Spring View interface to integrate it.
NARESH i technologies
SPRING SUDHEER
Spring Controllers are configured via IoC like any other objects. This makes them easy to
test, and beautifully integrated with other objects managed by Spring.
Spring MVC web tiers are typically easier to test than Struts web tiers, due to the
avoidance of forced concrete inheritance and explicit dependence of controllers on the
dispatcher servlet.
The web tier becomes a thin layer on top of a business object layer. This encourages
good practice. Struts and other dedicated web frameworks leave you on your own in
implementing your business objects; Spring provides an integrated framework for all
tiers of your application.
It provides a rich functionality for building robust Web Applications.
The Spring MVC Framework is architected and designed in such a way that every piece
of logic and functionality is highly configurable.
Spring can integrate effortlessly with other popular Web Frameworks like Struts,
WebWork, Java Server Faces and Tapestry.
Spring is not tightly coupled with Servlets or JSP to render the View to the Clients.
Integration with other View technologies like Velocity, Freemarker, Excel or Pdf is also
possible now.
In Spring Web MVC you can use any object as a command or form-backing object; you
do not need to implement a framework-specific interface or base class.
Springs data binding is highly flexible: for example, it treats type mismatches as
validation errors that can be evaluated by the application, not as system errors. Thus you
need not duplicate your business objects properties as simple, untyped strings in your
form objects simply to handle invalid submissions, or to convert the Strings properly.
Instead, it is often preferable to bind directly to your business objects.
The following diagram describes the architecture and lifecycle of Spring MVC Framework.
NARESH i technologies
SPRING SUDHEER
o The client sends a request to web container in the form of http request.
o With the help of Handler Mappings, the DispatcherServlet will dispatch the request to
appropriate Controller.
o The Controller tries to process the request and returns the Model and View object in form
of ModelAndView instance to the Front Controller.
o The Front Controller then tries to resolve the View (which can be JSP, Freemarker, and
Velocity etc) by consulting the View Resolver object.
NARESH i technologies
SPRING SUDHEER
3. ModelAndView
4. ViewResolver
5. Controller
DISPATCHERSERVLET
NARESH i technologies
SPRING SUDHEER
The preceding code snippet declares DispatcherServlet that specifies the Servlet to use
applicationBeans.xml and applicationControllers.xml documents to initialize
WebApplicationContext.
DispatcherServlet has to be configured to receive all the requests to our application, that
is, for various services,DispatcherServlets mapping should be generic.
The following code snippet shows the sample mapping for DispatcherServlet.
As per the mapping shown in the preceding code snippet all the request for this context
whose servletPath ends with .spring extension are dispatched by the web container to
the DispatcherServlet.
HANDLERMAPPINGS
NARESH i technologies