Anda di halaman 1dari 116

Radha Technologies

Spring Frameworks

9500085257

Introduction

Spring is an open source framework, which is very flexible while developing any kind
of application.
i.e. stand alone application/web-application/enterprise applications.
Struts is used only for web applications, where as Spring can be used for developing
stand-alone application, applet based application, web application and enterprise
application.
Spring framework is created to address the complexity of enterprise application
development
One of the chief advantages of the Spring framework is its layered architecture
Spring is a light-weight framework.
Spring is having total 6 modules.
We can use the modules independently or combine depending on the type of
application and requirement.
Main core of Spring is IOC module.

The Advantages of spring framework


The advantages of spring are as follows:
Spring has layered architecture. Use what you need and leave you don't need now.
Spring Enables POJO Programming. There is no behind the scene magic here. POJO
programming enables continuous integration and testability.
Dependency Injection and Inversion of Control Simplifies JDBC
Open source and no vendor lock-in.

The Features of Spring framework


The features of spring framework are as follows
Lightweight:
Spring is lightweight when it comes to size and transparency. The basic version of
spring framework is around 1MB. And the processing overhead is also very
negligible.
Inversion of control (IOC):
Loose coupling is achieved in spring using the technique Inversion of Control. The
objects give their dependencies instead of creating or looking for dependent objects.
Aspect oriented (AOP):
Spring supports Aspect oriented programming and enables cohesive development by
separating application business logic from system services.
Container:
Spring contains and manages the life cycle and configuration of application objects.
MVC Framework:

www.javaeasytoall.com

Radha Technologies

Spring Frameworks

9500085257

Spring comes with MVC web application framework, built on core Spring functionality.
This framework is highly configurable via strategy interfaces, and accommodates
multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other
frameworks can be easily used instead of Spring MVC Framework.
Transaction Management:
Spring framework provides a generic abstraction layer for transaction management.
This allowing the developer to add the pluggable transaction managers, and making
it easy to demarcate transactions without dealing with low-level issues. Spring's
transaction support is not tied to J2EE environments and it can be also used in
container less environments.
JDBC Exception Handling:
The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy,
which simplifies the error handling strategy. Integration with Hibernate, JDO, and
iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS

The 6 modules of Spring Framework are


1. IOC: Inversion of Control.
It is also called as Dependency Injection. The core container provides
the essential functionality of the spring framework. A primary component of the
core container is the BeanFactory, an implementation of the Factory pattern. The
BeanFactory applies the Inversion of Control (IOC) pattern to separate an
application's configuration and dependency specification from the actual
application code.
2. AOP: Aspect Oriented Programming.
The Spring AOP module integrates aspect-oriented programming functionality
directly into the Spring framework, through its configuration management
feature. As a result you can easily AOP-enable any object managed by the Spring
framework. The Spring AOP module provides transaction management services
for objects in any Spring-based application. With Spring AOP you can incorporate
declarative transaction management into your applications without relying on EJB
components.
3. DAO & JDBC:
The Spring JDBC DAO abstraction layer offers a meaningful exception
hierarchy for managing the exception handling and error messages thrown by
different database vendors. The exception hierarchy simplifies error handling and
greatly reduces the amount of exception code you need to write, such as opening
and closing connections. Spring DAO's JDBC-oriented exceptions comply to its
generic DAO exception hierarchy.

4. ORM: Object Relational Mapping System


The Spring framework plugs into several ORM frameworks to provide its
Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these
comply with Spring's generic transaction and DAO exception hierarchies.
5. J2EE: related to Java Enterprise Edition.
6. Web & MVC: struts are only this module.

www.javaeasytoall.com

Radha Technologies

Spring Frameworks

9500085257

The Model-View-Controller (MVC) framework is a full-featured MVC


implementation for building Web applications. The MVC framework is highly
configurable via strategy interfaces and accommodates numerous view
technologies including JSP, Velocity, Tiles, iText, and POI.
DAO
&
JDBC

ORM

WEB
&
MVC
Module

J2EE

AOP

IOC

Spring framework came up with every module for every tier. No other framework
contains these many modules.
Tier: It is a clear separation of two or more Systems arranged by one after
another.

Possible Tiers while developing an application.

UI
Tier
Web browser

Presen
tation
Tier
HTML/JSP

Busi
ness
Tier
J2EE

Integ
ratio
n
Tier
JDBC/DAO

Data
Base
Tier
EIS

UI Tier: User Interface Tier. Like a web browser


Presentation Tier: CSS, HTML, JavaScript, Images, Servlet, Jsp, Web MVC
Module of spring,
Struts.
Business Tier: we can use plain java class, java beans, ejb, messaging services. For
this Spring is providing J2EE Module.
Integration Tier: JDBC or any ORM tools like Hibernate, IBatis. For this Spring is
providing JDBC&DAO Module.
DataBase Tier: under this Enterprise Information Services will come.
If you are using any ORM related tools like Hibernate, for this Spring provides one
module ORM.

Inversion of Control

In general object is controlled by our java programme; otherwise we can store the
state of object using Serialization or Externalization.

www.javaeasytoall.com

Radha Technologies

Spring Frameworks

9500085257

If controlling of object is done by configuration files i.e. creating of object, storing


state of object (i.e. somewhat inverse of way), this is called Inversion of Control.
(IOC).
This IOC concept is base for every module of spring.
IOC is core incase of spring.
IOC is also called as Dependence Injection.
Here we are achieving dependency injection depending on object whatever the data
requires, that will be injected through configuration file.
IOC container provides objects bases on the configuration in xml files. We are not
creating object by using new operator for an entity. We will get object from IOC
container. It goes to configuration file, based on that it generates object.
IOC container generates objects and it is giving those objects to our programme.
IOC is maintains Singleton Object

Simple Core Development in Ioc Module

Create core java project


Update the build path with relevant jar files.
i.e. spring.jar and commons-logging.jar.
Write one pojo class and develop one configuration file.
Then develop one client programme.

Developing the pojo class.


src\com\lara\ioc\Person.java
package com.lara.ioc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class Person
{
private String age;
private String name;
private String[] lovers;
private ArrayList mails;
private HashSet jobs;
private HashMap education;
public String getAge()
{
return age;
}
public void setAge(String age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{

www.javaeasytoall.com

Radha Technologies

Spring Frameworks

9500085257

this.name = name;
}
public String[] getLovers()
{
return lovers;
}
public void setLovers(String[] lovers)
{
this.lovers = lovers;
}
public ArrayList getMails()
{
return mails;
}
public void setMails(ArrayList mails)
{
this.mails = mails;
}
public HashSet getJobs()
{
return jobs;
}
public void setJobs(HashSet jobs)
{
this.jobs = jobs;
}
public HashMap getEducation()
{
return education;
}
public void setEducation(HashMap education)
{
this.education = education;
}
}

Develop one Configuration file for this Person.java


src\Person.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="person" class="com.lara.ioc.Person">
<property name="age" value="28" />
<property name="name" value="Ramu" />
<property name="lovers">
<list>
<value>India</value>

www.javaeasytoall.com

BEAN

2.0//EN"

Radha Technologies

Spring Frameworks

9500085257

<value>Cricket</value>
</list>
</property>
<property name="mails">
<list>
<value>ramu123banda@gmail.com</value>
<value>b.kodandaramireddy@gmail.com</value>
</list>
</property>
<property name="jobs">
<set>
<value>Project Manager in GE</value>
<value>Deliver Manager in IBM</value>
</set>
</property>
<property name="education">
<map>
<entry key="graduation" value="B.Sc."/>
<entry key="postgraduation" value="M.Sc."/>
</map>
</property>
</bean>
</beans>
Develop the client programme
src\com\lara\ioc\Manager.java
package com.lara.ioc;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Manager
{
public static void main(String[] args)
{
/*
Get the Person class object by using IOC.
So control will not be inside main method, control will be inside
configuration xml file.
*/
/*
In order to get the person class object first
pass the configuration file path to the constructor of ClassPathResource
class and then pass the bean id value i.e. person to the get Bean() method
of BeanFactory.
*/
BeanFactory
factory=new
ClassPathResource("Person.xml"));
Person p=(Person)factory.getBean("person");

www.javaeasytoall.com

XmlBeanFactory(new

Radha Technologies

Spring Frameworks

9500085257

/*
IOC container will calls all setter methods and state of an object is injected
By using setter methods.
In order to use the state of the object, then go for getter methods.
*/

System.out.println(p.getName() +" : "+p.getAge());


for(String lover : p.getLovers())
{
System.out.println(lover);
}
for(Object email : p.getMails())
{
System.out.println((String)email);
}
for(Object job : p.getJobs())
{
System.out.println((String)job);
}

}
Another Simple Core Development in Ioc Module

Createing the core java project.


Updating the build path with relevant jar files, i.e. spring.jar and commonslogging.jar
Developing the pojo classes, i.e. Person.java and Address.java
Develop one configuration file for both Person class and Address class.
Develop one client class.

Developing the pojo classes


.
0
src\com\lara\ioc\Person.java
// keep one derived data-type attribute(user-defined), then develop one separate class for
//that derive data-type, i.e. here Address class.
package com.lara.ioc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class Person

www.javaeasytoall.com

Radha Technologies

Spring Frameworks
{

9500085257

public Person()
{
System.out.println("Person");
}
private String age;
private String name;
private String[] lovers;
private ArrayList mails;
private HashSet jobs;
private HashMap education;
private Address presentAddress;
public String getAge()
{
return age;
}
public void setAge(String age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String[] getLovers()
{
return lovers;
}
public void setLovers(String[] lovers)
{
this.lovers = lovers;
}
public ArrayList getMails()
{
return mails;
}
public void setMails(ArrayList mails)
{
this.mails = mails;
}
public HashSet getJobs()
{
return jobs;
}
public void setJobs(HashSet jobs)
{
this.jobs = jobs;
}

www.javaeasytoall.com

Radha Technologies

Spring Frameworks

9500085257

public HashMap getEducation()


{
return education;
}
public void setEducation(HashMap education)
{
this.education = education;
}
public Address getPresentAddress()
{
return presentAddress;
}
public void setPresentAddress(Address presentAddress)
{
this.presentAddress = presentAddress;
}
}
src\com\lara\ioc\Address.java
package com.lara.ioc;
public class Address
{
private String streetName;
private String city;
public Address()
{
System.out.println("Address()");
}

public String getStreetName()


{
return streetName;
}
public void setStreetName(String streetName)
{
this.streetName = streetName;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}

Develop one configuration file for both Person and Address classes.

www.javaeasytoall.com

10

Radha Technologies

Spring Frameworks

9500085257

src\Person.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- bean defination for Person class with id values as person
If any derived data-types are there in Person class then go for one
-->
<bean id="person" class="com.lara.ioc.Person" >
<property name="age" value="28" />
<property name="name" value="Ramu" />
<property name="lovers">
<list>
<value>India</value>
<value>Cricket</value>
</list>
</property>
<property name="mails">
<list>
<value>ramu123banda@gmail.com</value>
<value>b.kodandaramireddy@gmail.com</value>
</list>
</property>
<property name="jobs">
<set>
<value>Project Manager in GE</value>
<value>Deliver Manager in IBM</value>
</set>
</property>
<property name="education">
<map>
<entry key="graduation" value="B.Sc."/>
<entry key="postgraduation" value="M.Sc."/>
</map>
</property>
<!-- property tag along with ref attribute -->
<property name="presentAddress" ref="add" />
</bean>
<!-- develop one separate bean with the value of ref attribute of the property tag
of the above bean tag
-->
<!-- bean defination for Address class with id values as add -->
<bean id="add" class="com.lara.ioc.Address">
<property name="streetName" value="Thavarakare" />
<property name="city" value="Bangalore" />
</bean>
</beans>
Develop the client programme
src\com\lara\ioc\Manager.java

www.javaeasytoall.com

11

Radha Technologies

Spring Frameworks

9500085257

package com.lara.ioc;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Manager
{
public static void main(String[] args)
{
BeanFactory factory=new XmlBeanFactory(new
ClassPathResource("Person.xml"));
Person p=(Person)factory.getBean("person");
System.out.println(p.getName() +" : "+p.getAge());
for(String lover : p.getLovers())
{
System.out.println(lover);
}
for(Object email : p.getMails())
{
System.out.println((String)email);
}
for(Object job : p.getJobs())
{
System.out.println((String)job);
}
System.out.println(p.getPresentAddress().getStreetName());
System.out.println(p.getPresentAddress().getCity());
Person p1=(Person)factory.getBean("person");
Person p2=(Person)factory.getBean("person");
}
}
Whenever we are trying to create an object for a Person class more than once, we will get
only one object but not more than one.
In order to get a new object for each object creation then go for scope attribute for the
<bean> tag
For example if you want get a new object for each object creation to the Person class
then go for scope attribute with a value prototype.
Like below
<bean id="person" class="com.lara.ioc.Person" scope="prototype">
</bean>

By default scope value is singleton.

www.javaeasytoall.com

12

Radha Technologies

Spring Frameworks

9500085257

If scope value is singleton then Ioc will retrieves the same object for each object
creation to that class.
If we gives scope value as prototype then will get a new object for each object
creation to that class.
The state of an object is injected in two ways.
1. by using setter methods.
2. by using constructors.
The above two programmes are examples for injecting the data of an object into
the bean by using setter methods.

Injecting data in the bean by using constructors

Example:-1

Create one core-java project


Update the build path with relevant jar files i.e. spring.jar and commons-logging.jar
Develop one pojo class along with one no-arg constructor and one parameterized
constructor. Parameters should be attributes types of that class.
Develop one configuration file for that pojo class.
Develop one client class.

Developing the pojo class


src\com\lara\ioc\Mail.java
package com.lara.ioc;
public class Mail
{
private Integer id;
private String mailId;
private String password;
public Mail()
{
System.out.println("Mail()");
}
public Mail(Integer id,String mailId, String password)
{
System.out.println("Mail(id,mailId,password)");
this.id=id;
this.mailId=mailId;
this.password=password;
}
public Integer getId()
{
System.out.println("getId");
return id;
}
public void setId(Integer id)

www.javaeasytoall.com

13

Radha Technologies

Spring Frameworks
{

9500085257

System.out.println("setId");
this.id = id;

}
public String getMailId()
{
System.out.println("getMailId");
return mailId;
}
public void setMailId(String mailId)
{
System.out.println("setMailId");
this.mailId = mailId;
}
public String getPassword()
{
System.out.println("getPassword");
return password;
}
public void setPassword(String password)
{
System.out.println("setPassword");
this.password = password;
}
}
Develop one configuration file for Mail class.
src\abc.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="mailObj" class="com.lara.ioc.Mail">
<constructor-arg index="0" type="java.lang.Integer" value="1000"/>
<constructor-arg index="1" type="java.lang.String"
value="mail@mail.com"/>
<constructor-arg index="2" type="java.lang.String" value="india"/>
</bean>
</beans>

In order to use the constructors to inject data in the bean go for


<constructor-arg index="0" type="java.lang.Integer" value="1000"/> tag
along with index, type and value attributes inside the <bean > tag.
Here the index attribute value will start with 0 to represent the attributes of the pojo
class.
And the type attribute will represents the data-type of the class attribute.
if we use constructors to inject data in the bean Ioc will not call the no-arg
constructor, it will call the parameterized constructor. Through constructor desired
values are assigning.

www.javaeasytoall.com

14

Radha Technologies

Spring Frameworks

9500085257

Develop the client programme


src\com\lara\ioc\Manager.java
package com.lara.ioc;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class Manager
{
public static void main(String[] args)
{
BeanFactory factory=new XmlBeanFactory(new
FileSystemResource("./src/abc.xml"));
Mail mail=(Mail)factory.getBean("mailObj");
System.out.println(mail.getId());
System.out.println(mail.getMailId());
System.out.println(mail.getPassword());
}
}

Example:-2
Developing the pojo classes
src\com\lara\ioc\Mail.java
same as the above developed in Example:-1
src\com\lara\ioc\Address.java
package com.lara.ioc;
public class Address
{
private Mail mail;
private String streetName;
public Address()
{
}
public Address(Mail mail, String streetName)
{
this.mail=mail;
this.streetName=streetName;
}
public Mail getMail()
{
return mail;
}
public void setMail(Mail mail)
{

www.javaeasytoall.com

15

Radha Technologies

Spring Frameworks

9500085257

this.mail = mail;
}
public String getStreetName()
{
return streetName;
}
public void setStreetName(String streetName)
{
this.streetName = streetName;
}
}
Develop one configuration file for Mail class.
src\abc.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="mailObj" class="com.lara.ioc.Mail">
<constructor-arg index="0" type="java.lang.Integer" value="1000"/>
<constructor-arg
index="1"
type="java.lang.String"
value="mail@mail.com"/>
<constructor-arg index="2" type="java.lang.String" value="india"/>
</bean>
<bean id="add" class="com.lara.ioc.Address">
<constructor-arg index="0" ref="mailObj"/>
<constructor-arg index="1" type="java.lang.String" value="Thavarakare"/>
</bean>
</beans>

Develop the client programme


src\com\lara\ioc\Manager.java

package com.lara.ioc;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class Manager
{

www.javaeasytoall.com

16

Radha Technologies

Spring Frameworks

9500085257

public static void main(String[] args)


{
BeanFactory factory=new XmlBeanFactory(new
FileSystemResource("./src/abc.xml"));
Address address=(Address)factory.getBean("add");
System.out.println(address.getMail().getId());
System.out.println(address.getMail().getMailId());
System.out.println(address.getMail().getPassword());
System.out.println(address.getStreetName());
}
}

Example:-3
Developing the pojo classes
src\com\lara\ioc\Mail.java
same as the above developed in Example:-1
src\com\lara\ioc\Address.java
same as the above developed in Example:-2
src\com\lara\ioc\Person.java
package com.lara.ioc;
public class Person
{
private Address address;
private String name;
public Person()
{
}
public Person(Address address, String name)
{
this.address=address;
this.name=name;
}
public Address getAddress()
{
return address;
}
public void setAddress(Address address)
{
this.address = address;
}
public String getName()
{

www.javaeasytoall.com

17

Radha Technologies

Spring Frameworks

9500085257

return name;
}
public void setName(String name)
{
this.name = name;
}
}
Develop one configuration file for Mail class.
src\abc.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="mailObj" class="com.lara.ioc.Mail">
<constructor-arg index="0" type="java.lang.Integer" value="1000"/>
<constructor-arg
index="1"
type="java.lang.String"
value="mail@mail.com"/>
<constructor-arg index="2" type="java.lang.String" value="india"/>
</bean>
<bean id="add" class="com.lara.ioc.Address">
<constructor-arg index="0" ref="mailObj"/>
<constructor-arg index="1" type="java.lang.String" value="Thavarakare"/>
</bean>
<bean id="personObj" class="com.lara.ioc.Person">
<constructor-arg index="0" ref="add"/>
<constructor-arg index="1" type="java.lang.String" value="Mahesh"/>
</bean>
<!-<bean id="personObj" class="com.lara.ioc.Person" autowire="byType">
<property name="name" value="Mahesh"/>
</bean>
-->
</beans>
Develop the client programme
src\com\lara\ioc\Manager.java
package com.lara.ioc;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class Manager
{
public static void main(String[] args)
{
BeanFactory factory=new XmlBeanFactory(new
FileSystemResource("./src/abc.xml"));
Person person=(Person)factory.getBean("personObj");
System.out.println(person.getAddress().getMail().getId());
System.out.println(person.getAddress().getMail().getMailId());
System.out.println(person.getAddress().getMail().getPassword());

www.javaeasytoall.com

18

Radha Technologies

Spring Frameworks

9500085257

System.out.println(person.getAddress().getStreetName());
System.out.println(person.getName());
}

Giving a call from one bean to another bean, this process is called as wiring.
There are two types of wirings, one is explicit wiring and second one is Auto-wiring.
The above three examples will comes under explicit wiring.
If already bean id is there then we can go for auto wiring, we dont require setting
explicitly.
If you want achieve auto-wiring then go for one attribute called autowire to the
<bean> tag.

Ex:
<bean id="personObj" class="com.lara.ioc.Person" autowire="byType">
<property name="name" value="Mahesh"/>
</bean>

Here Address class object is automatically wired to person class attribute, and the
name attribute is setting to explicit wiring.
Auto wiring is 4 types
1. byType
2. byName
3. constroctor
4. autodetect

An Example for Auto Wiring Concept


Developing the pojo classes
src\com\lara\ioc\ autowire\ Product.java
package com.lara.ioc.autowire;
public class Product
{
private String name;
private String desc;
public Product()
{
}
public Product(String name, String desc)
{
this.name=name;
this.desc=desc;
}
public String getName()
{
return name;
}
public void setName(String name)
{

www.javaeasytoall.com

19

Radha Technologies

Spring Frameworks

9500085257

this.name = name;
}
public String getDesc()
{
return desc;
}
public void setDesc(String desc)
{
this.desc = desc;
}
}
src\com\lara\ioc\ autowire\ Order.java
package com.lara.ioc.autowire;
public class Order
{
private Product pdr;
public Order()
{
}
private Order(Product pdr1)
{
this.pdr=pdr1;
}
public Product getPdr() {
return pdr;
}
public void setPdr(Product pdr) {
this.pdr = pdr;
}
}

Develop one configuration file for Mail class.


src\abc.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="pdr" class="com.lara.ioc.autowire.Product" autowire="byType">
<property name="name" value="TV"/>
<property name="desc" value="This is Sony Product"/>
</bean>
<!-- here autowire type is 'byType' -->
<!-<bean id="order1" class="com.lara.ioc.autowire.Order" autowire="byType"/>

www.javaeasytoall.com

20

Radha Technologies

Spring Frameworks

9500085257

-->
<!-- here autowire type is 'byName' -->
<!-<bean id="order1" class="com.lara.ioc.autowire.Order" autowire="byName"/>
-->
<!-- here autowire type is 'autodetect' -->
<!-<bean id="order1" class="com.lara.ioc.autowire.Order" autowire="autodetect"/>
-->
<!-- here autowire type is 'constructor' -->
<bean id="order1" class="com.lara.ioc.autowire.Order" autowire="constructor"/>
</beans>

If autowire type is byName then Ioc will look for a bean id which is matching the
value with the Order class attribute name.

If autowire type is byType then Ioc will look what is the data-type of the derived
attributes inside Order class. Then it will look for a matching bean id inside
configuration file which is having the class value as the data-type of the derived
attribute.

If autowire type is constructor then Ioc will look for a matching constructor inside
Order class which is taking the derived data-type as an attribute.

If autowire type is autodetect then Ioc will detect automatically for the next wiring
class.

Auto wiring is good for only for small applications. It is not advisable for large
applications.

Develop the client programme


src\com\lara\ioc\ autowire \Manager.java
package com.lara.ioc.autowire;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class Manager


{
public static void main(String[] args)
{
BeanFactory factory=new XmlBeanFactory(new
FileSystemResource("./src/abc.xml"));
Order order=(Order)factory.getBean("order1");
System.out.println(order.getPdr().getName());
System.out.println(order.getPdr().getDesc());
}
}

www.javaeasytoall.com

21

Radha Technologies

Spring Frameworks

9500085257

Bean Life
Through Ioc container initialization cleanup operations will done in two ways.
1. Developing your own methods for initialization and cleanup operations in pojo class .
And then give an instruction to Ioc container by using init-method and destroy
attributes of the <bean> tag. Pass the initialization and cleanup method names of
your pojo class as the values to init-method and destroy attributes respectively.
2. if you dont want to develop your own methods for initialization and cleanup and u
dont to use the init-method and destroy attributes of <bean> tag, then go for
InitializingBean, DisposableBean interfaces in order to initialization and cleanup
operations respectively. After implementing the pojo class to the InitializingBean,
DisposableBean interfaces, override the afterPropertiesSet() and destroy()
respectively for initialization and cleanup operations.
An Example for Bean Life by using init-method and destroy attributes of <bean>
tag
Developing pojo class
src\ com\lara\ioc\beanlife\Book.java
package com.lara.ioc.beanlife;
public class Book
{
private Integer id;
private String title;
private Double price;
public Book()
{
System.out.println("Book()");
}
public Integer getId()
{
System.out.println("getId()");
return id;
}
public void setId(Integer id)
{
System.out.println("setId()");
this.id = id;
}
public String getTitle()
{
System.out.println("getTitle()");
return title;
}
public void setTitle(String title)

www.javaeasytoall.com

22

Radha Technologies

Spring Frameworks
{
}

9500085257

System.out.println("setTitle()");
this.title = title;

public Double getPrice()


{
System.out.println("getPrice()");
return price;
}
public void setPrice(Double price)
{
System.out.println("setPrice()");
this.price = price;
}
//User defined method for initialization process
public void initialize()
{
System.out.println("initialize()");
}
//User defined method for cleanup process
public void cleanup()
{
System.out.println("cleanup()");
}
}

Develop configuration file for Book class


src\abc.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-bean defination for Book pojo class by using init-method and destroy
attributes in order to achive initialization, cleanup operations.
-->
<bean
id="bookId"
class="com.lara.ioc.beanlife.Book"
init-method="initialize"
destroy-method="cleanup">
<property name="id" value="28"/>
<property name="title" value="Spring"/>
<property name="price" value="1000"/>
</bean>
</beans>
Write a client programme
src\ com\lara\ioc\beanlife\Manager.java
package com.lara.ioc.beanlife;

www.javaeasytoall.com

23

Radha Technologies

Spring Frameworks

9500085257

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class Manager
{
public static void main(String[] args)
{
BeanFactory factory=new XmlBeanFactory(new
FileSystemResource("./src/abc.xml"));
Book book=(Book)factory.getBean("bookId");
System.out.println(book.getId());
System.out.println(book.getTitle());
System.out.println(book.getPrice());
}
}
An Example for Bean Life by implementing
InitializingBean, DisposableBean interfaces

the

pojo(Book)

class

Developing pojo class


src\ com\lara\ioc\beanlife\Book.java
package com.lara.ioc.beanlife;
package com.lara.ioc.beanlife;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class Book implements InitializingBean, DisposableBean
{
private Integer id;
private String title;
private Double price;
public Book()
{
System.out.println("Book()");
}
public Integer getId()
{
System.out.println("getId()");
return id;
}
public void setId(Integer id)
{
System.out.println("setId()");
this.id = id;
}
public String getTitle()
{
System.out.println("getTitle()");
return title;
}
public void setTitle(String title)

www.javaeasytoall.com

24

Radha Technologies

to

Spring Frameworks
{

9500085257

System.out.println("setTitle()");
this.title = title;

}
public Double getPrice()
{
System.out.println("getPrice()");
return price;
}
public void setPrice(Double price)
{
System.out.println("setPrice()");
this.price = price;
}
public void afterPropertiesSet() throws Exception
{
System.out.println("afterPropertiesSet()");
}
public void destroy() throws Exception
{
System.out.println("destroy()");
}
}
Develop configuration file for Book class
src\abc.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="bookId" class="com.lara.ioc.beanlife.Book">
<property name="id" value="28"/>
<property name="title" value="Spring"/>
<property name="price" value="1000"/>
</bean>
</beans>

BEAN

2.0//EN"

Write a client programme


src\ com\lara\ioc\beanlife\Manager.java
package com.lara.ioc.beanlife;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class Manager
{

www.javaeasytoall.com

25

Radha Technologies

Spring Frameworks

9500085257

public static void main(String[] args)


{
BeanFactory
factory=new
FileSystemResource("./src/abc.xml"));
Book book=(Book)factory.getBean("bookId");
System.out.println(book.getId());
System.out.println(book.getTitle());
System.out.println(book.getPrice());
System.out.println("Done1234");
}
}

XmlBeanFactory(new

Spring AOP Basics


Topics
Why AOP?
AOP concepts
Spring AOP
What is AOP?
Aspect-Oriented Programming (AOP) complements OOP by providing another
way of thinking about program structure. While OO decomposes applications into a
hierarchy of objects, AOP decomposes programs into aspects or concerns. This
enables modularization of concerns such as transaction management that would
otherwise cut across multiple objects. (Such concerns are often termed crosscutting
concerns.)
Why AOP?
Aspect-oriented programming (AOP) provides for
simplified application of cross-cutting concerns
Examples of cross-cutting concerns
Logging
Transaction management
Security
Auditing
Locking
Event handling

AOP Concepts
AOP Concepts: Joinpoint
Well-defined point during the execution of your
application
You can insert additional logic at Joinpoint's
Examples of Jointpoint's
Method invocation
Class initialization
Object initialization
AOP Concepts: Advice
The code that is executed at a particular
joinpoint
Types of Advice

www.javaeasytoall.com

26

Radha Technologies

Spring Frameworks

AOP

AOP
AOP

AOP

AOP

9500085257

before advice, which executes before joinpoint


after advice, which executes after joinpoint
around advice, which executes around joinpoint
Concepts: Pointcuts
A collection of joinpoints that you use to define
when advice should be executed
By creating pointcuts, you gain fine-grained
control over how you apply advice to the
components
Example
A typical joinpoint is a method invocation.
A typical pointcut is a collection of all method
invocations in a particular class
Pointcuts can be composed in complex
relationships to further constrain when advice is
executed
Concepts: Aspects
An aspect is the combination of advice and
pointcuts
Concepts: Weaving
Process of actually inserting aspects into the
application code at the appropriate point
Types of Weaving
Compile time weaving
Runtime weaving
Concepts: Target
An object whose execution flow is modified by
some AOP process
They are sometimes called advised object
Concepts: Introduction
Process by which you can modify the structure
of an object by introducing additional methods
or fields to it
You use the Introduction to make any object
implement a specific interface without needing
the object's class to implement that interface
explicitly

Types of AOP
Static AOP
The weaving process forms another step in the build
process for an application
Example: In Java program, you can achieve the
weaving process by modifying the actual bytecode
of the application changing and modifying code as
necessary
Dynamic AOP
The weaving process is performed dynamically at
runtime
Easy to change the weaving process without
recompilation

www.javaeasytoall.com

27

Radha Technologies

Spring Frameworks

9500085257

Spring AOP
Based on proxies
When you want to create an advised instance of a
class, you must use the ProxyFactory class to create
a proxy of an instance of that class, first providing
the ProxyFactory with all the aspects that you want
to be woven into the proxy
You typically use ProxyFactoryBean class to provide
declarative proxy creation

Spring AOP capabilities and goals


Spring AOP is implemented in pure Java. There is no need for a special compilation
process. Spring AOP does not need to control the class loader hierarchy, and is thus
suitable for use in a J2EE web container or application server.
Spring currently supports interception of method invocations. Field interception is not
implemented, although support for field interception could be added without breaking
the core Spring AOP APIs.
Field interception arguably violates OO encapsulation. We don't believe it is wise in
application development. If you require field interception, consider using AspectJ.
Spring provides classes to represent pointcuts and different advice types. Spring
uses the term advisor for an object representing an aspect, including both an advice
and a pointcut targeting it to specific joinpoints.

Example:-1
Hello World Application in Spring AOP
Development steps
1. create one java project(aop).
2. update the build path with relevant jar files
i.e. spring.jar and commons-logging.jar
3. create a package structure(i.e. com.javaTouch.hello)
4. Develop one interface.
5. Develop one public class for that interface which you developed in
step4
6. Write one advice class.
7. Develop one configuration file.
8. Write one client programme.
1. Developing interface
package com.javaTouch.hello;
public interface IGreetingService
{
public void sayGreeting();
}

www.javaeasytoall.com

28

Radha Technologies

Spring Frameworks

9500085257

2. Deveoping the public class


package com.javaTouch.hello;
public class GreetingServiceImpl implements IGreetingService
{
public void sayGreeting()
{
System.out.println("Hello World");
}
}
3. Writing an advice class
package com.javaTouch.hello;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class BeforeGreetingAdvice implements MethodBeforeAdvice
{
public void before(Method m, Object[] args, Object target) throws
Throwable
{
System.out.println("Before calling method: "+ m.getName()+
" (by " +
this.getClass().getName()+ ")");
}
}
4. Develop One Configuration file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- Bean configuration -->
<bean id="greetingBean"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.javaTouch.hello.IGreetingService</value>
</property>
<property name="target">
<ref local="greetingService"/>
</property>
<property name="interceptorNames">
<list>
<value>theBeforeGreetingAdvisor</value>
</list>
</property>
</bean>
<!-- Advisor pointcut definition for before advice -->
<bean id="theBeforeGreetingAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="theBeforeGreetingAdvice"/>
</property>
<property name="pattern">
<value>.*</value>
</property>

www.javaeasytoall.com

29

Radha Technologies

Spring Frameworks

9500085257

</bean>
<!-- Advice classes -->
<bean id="theBeforeGreetingAdvice"
class="com.javaTouch.hello.BeforeGreetingAdvice"/>
<!-- Bean Class -->
<bean id="greetingService"
class="com.javaTouch.hello.GreetingServiceImpl">
</bean>
</beans>
5. Write one client class
package com.javaTouch.hello;
import com.javaTouch.hello.IGreetingService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
public class HelloApp
{
public static void main(String[] args) throws Exception
{
// Read the configuration file
BeanFactory
factory
=
new
XmlBeanFactory(new
ClassPathResource("hello.xml"));
//Instantiate an object
IGreetingService
greetingService
=
(IGreetingService)
factory.getBean("greetingBean");
//Execute the public method of the bean (the test)
greetingService.sayGreeting();
}
}

Example:-2
1. Developing interface
package com.javaTouch.hello;
public interface IGreetingService
{
public void sayGreeting();
}
2. Deveoping the public class
package com.javaTouch.hello;
public class GreetingServiceImpl implements IGreetingService
{

www.javaeasytoall.com

30

Radha Technologies

Spring Frameworks

9500085257

public void sayGreeting()


{
System.out.println("Hello World");
String s1 = null;
System.out.println(s1.length());
}
}
3. Writing an advice class
package com.javaTouch.hello;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class BeforeGreetingAdvice implements MethodBeforeAdvice {
public void before(Method m, Object[] args, Object target) throws Throwable {
System.out.println("Before calling method: "+ m.getName()+ " (by " +
this.getClass().getName()
+ ")");
}
}
4. Developing MInterceptor class
package com.javaTouch.hello;
import
import
import
import
import

java.lang.reflect.Method;
org.aopalliance.intercept.MethodInvocation;
org.springframework.aop.IntroductionInterceptor;
org.springframework.aop.AfterReturningAdvice;
org.springframework.aop.ThrowsAdvice;

public class MInterceptor implements IntroductionInterceptor,


AfterReturningAdvice, ThrowsAdvice
{
public Object invoke(MethodInvocation method) throws Throwable
{
long start = System.currentTimeMillis();
try
{
Object result = method.proceed();
return result;
}
finally
{
long end = System.currentTimeMillis();
long timeMs = end - start;
System.out.println("Method: " + method.toString()
+ " took: " + timeMs +" ms.");
}
}
public boolean implementsInterface(Class arg0)
{
System.out.println("implementsInterface");

www.javaeasytoall.com

31

Radha Technologies

Spring Frameworks

9500085257

return false;
}
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
System.out.println("After returning");
}
public void afterThrowing(NullPointerException ex)
{
System.out.println("null pointer");
}
}
5. Develop One Configuration file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- Bean configuration -->
<bean id="greetingBean"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.javaTouch.hello.IGreetingService</value>
</property>
<property name="target">
<ref local="greetingService"/>
</property>
<property name="interceptorNames">
<list>
<value>theBeforeGreetingAdvisor</value>
<value>theTheTimeAdvisor</value>
</list>
</property>
</bean>
<!-- Bean Class -->
<bean id="greetingService"
class="com.javaTouch.hello.GreetingServiceImpl">
</bean>
<!-- Advisor pointcut definition for before advice -->
<bean id="theBeforeGreetingAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="theBeforeGreetingAdvice"/>
</property>
<property name="pattern">
<value>.*</value>
</property>
</bean>
<bean id="theTheTimeAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="theTime"/>
</property>
<property name="pattern">

www.javaeasytoall.com

32

Radha Technologies

Spring Frameworks

9500085257

<value>.*</value>
</property>
</bean>
<!-- Advice classes -->
<bean id="theBeforeGreetingAdvice"
class="com.javaTouch.hello.BeforeGreetingAdvice"/>
<bean id="theTime"
class="com.javaTouch.hello.MInterceptor"/>
</beans>
6. Write one client class
package com.javaTouch.hello;
import
import
import
import
import
import

com.javaTouch.hello.IGreetingService;
org.springframework.beans.factory.BeanFactory;
org.springframework.beans.factory.xml.XmlBeanFactory;
org.springframework.context.ApplicationContext;
org.springframework.context.support.FileSystemXmlApplicationContext;
org.springframework.core.io.ClassPathResource;

public class HelloApp {


public static void main(String[] args) throws Exception {
// Read the configuration file
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("hello.xml"));
//Instantiate an object
IGreetingService greetingService = (IGreetingService) factory.getBean("greetingBean");
//Execute the public method of the bean (the test)
greetingService.sayGreeting();
}
}

WEB-MVC-MODULE
Application

www.javaeasytoall.com

33

Radha Technologies

Spring Frameworks

9500085257
DispatcherServlet

Browser

Front Controller

Specific
Controller

View

Every request should go to one centralized controller i.e. Front Controller. If we are
using the web mvc module of spring then the front controller is
DispatcherServlet (DS).
DS, it identifies the corresponding controller, and then dispatches the request to that
specific controller.
Request wise we can assign a controller. Specific controller controls specific activities
of a specific request and it generates a model. That model is sending back to
the DispatcherServlet.
Specific controllers main work is to generate a model for that particular request.
DispatcherServlet receives the model form the specific controller and it identifies the
view, and then it forwards the request to the view.
View will be running in the container and the O/P of the view will be sending back to
the DispatcherServlet. The DispatcherServlet sends the O/P view to the
Browser.
Model is generated by specific controller. Model is nothing-but transferring the data.
Model is responsible for holding the data which will be available to all other
controlling activities.
Web MVC Module is only for developing web application based on MVC Architecture.
MVC: - Model View Controller Architecture.
Every framework should have one Controller. Controller means java classes. We can
write java classes by extending with existing abstract controllers.
Getting Started with Spring by Web MVC Module
Download framework related jar files from springframework.org web site.
At the time of download we can find two types of links to download the jar files. 1.
spring-framework-2.0.4.jar download this jar for essential features
2. spring-framework-2.0.4-with-dependencies.jar it is for all of its
dependencies.
Download the 2nd type jar file. In this we can find each and every jar file for all J2ee
related web applications. i.e. servlets/jsp/jstl/ejb/struts related jar files.
In cd3 go for spring-framework-2.0.4-with-dependencies.jarunzip
Inside this unzipped folder 3 main jar files and some other jar files are there in
various locations, to develop a spring application.
The three main jar files to develop a spring application are
1. spring-framework-2.0.4\dist\spring.jar

www.javaeasytoall.com

34

Radha Technologies

Spring Frameworks

9500085257

2. spring-framework-2.0.4\lib\j2ee\jstl.jar
3. spring-framework-2.0.4\lib\jakarta-taglibs\standard.jar
spring.jar, jstl.jar these two jar are developed by sun people and standard.jar is
developed by apache community.
Spring.jar it is using internally some of the jar files of lib folder.
Inside docs folder api documentation and reference materials are given.
Inside sample folder some model examples are given

Development Steps to develop simple hello world programme in spring


1. create the directory structure for the dynamic web project.
2. copy all relevant jar files in the lib folder of your web application.
3. create one web.xml file inside WEB-INF folder of your application and register the
FrontController i.e. DispatcherServlet inside web.xml.
4. take the servlet-name from the web.xml file and with that servlet-name create
one configuration file
Like [servlet-name]-servlet.xml
5
inside the configuration file i.e. inside [servlet-name]-servlet.xml file keep the
root tag i.e. <beans>
</beans>
6. then create a jsp page to make a request to the application.
Developing simple Hello World Programme in Spring

Spring-app
src
com
lara
webcontext
WEB-INF
lib

1. test.jsp

www.javaeasytoall.com

35

Radha Technologies

Spring Frameworks

9500085257

creating a JSP page named 'test.jsp' in the webcontext directory. This is the entry
point for our application
Spring-app\WebContent\test.jsp
<a href="hello.do">Get a Message From Spring</a>
2. Modify web.xml in WEB-INF directory
Go to the 'spring-app/webcontext/ WEB-INF' directory. Modify the minimal
'web.xml' file that we created earlier. Now we will modify it to suit our needs. We
define a DispatcherServlet that is going to control where all our request are
routed based on information we will entered. It also has a standard servletmapping entry that maps to the url patterns that we will be using. I have decided
to let any url with an '.do' extension be routed to the 'spring-app' dispatcher.
Spring-app\WebContent\WEB-INF\web.xml
<web-app>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
3. Creating Configuration file
Now, create a file called controller -servlet.xml' in the springapp/webcontext/WEB-INF directory (you can copy an example of this file from the
Spring distributions samples\countries\war\WEB-INF\countries-servlet.xml). This is
the file where definitions used by the DispatcherServlet should be entered. It is
named based on the servlet-name from web.xml with '-servlet' appended. This is
a standard naming convention used in the Spring Framework. Now, add a bean
entry named helloController and make the class HelloController. This defines
the controller that our application will be using. We also need to add a url mapping
so the DispatcherServlet knows which controller should be invoked for different
url/s

spring-app\ WebContent\WEB-INF\controller-servlet.xml
<beans>

www.javaeasytoall.com

36

Radha Technologies

Spring Frameworks

9500085257

<bean
id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="hello.do">helloController</prop>
</props>
</property>
</bean>
<bean id="helloController" class="com.lara.HelloController"/>
</beans>
4. Create your Controller
Create your Controller I named mine HelloController.java and placed it in the
spring-app\src\com\lara directory.
spring-app\src\com\lara\HelloController.java
package com.lara;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class HelloController implements Controller
{
public
ModelAndView
handleRequest(HttpServletRequest
arg0,HttpServletResponse arg1) throws Exception {
return new ModelAndView("response.jsp", "hello", str);
View

key

Model

/*
1. String str="Hello every body, welcome to spring world";
ModelAndView mav=new ModelAndView("response.jsp",
str);
return mav;
2. Date date = new Date();
ModelAndView mav=new ModelAndView("response.jsp",
date);
return mav;
*/

"hello",

"hello",

}
}
This is acting as a basic Controller. The Controller handles the request and
returns a ModelAndView. we are going to get a default one that just forwards to a
url matching the name of the view specified.

www.javaeasytoall.com

37

Radha Technologies

Spring Frameworks

9500085257

5. response.jsp
Spring-app\WebContent\response.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${hello}"/>
Login Form development by using MesssageResource File

1. index.jsp

Instead of hard coding the static messages into your application, read the
static messages from properties file.
Keep one properties file in your applications source folder, then configure
the properties file with one xml file i.e. applicationContext.xml.
Register a listener for that applicationContext.xml file in web.xml.

import the relevant tld files into your jsp page. And use those files inorder to
read the static messages from the properties file.
Spring-app1\WebContent\index.jsp
<%@ taglib uri="http://www.springframework.org/tags"
prefix="core"
%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<a href="login.do">
<core:message code="goToLogin.href"/>
</a>
2. web.xml
Spring-app1\WebContent\WEB-INF\web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>

www.javaeasytoall.com

38

Radha Technologies

Spring Frameworks

9500085257

3. Creating Configuration files


spring-app1\ WebContent\WEB-INF\controller-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="login.do">getLoginController</prop>
<prop key="doLogin.do">
doLoginController
</prop>
</props>
</property>
</bean>
<bean id="getLoginController" class="com.lara.GetLoginController"/>
<bean id="doLoginController" class="com.lara.DoLoginController">
<property name="commandClass" value="com.lara.Login"/>
</bean>
</beans>
spring-app1\ WebContent\WEB-INF\applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
</beans>
4. Create Properties File
then create properties file with the name of messages.properties in your source
folder
spring-app1\ src\messages.properties
goToLogin.href=GO TO Lin
login.welcome=Welcome To Login Page
login.username=UserName
login.password=Password
5. Creating your Controller
spring-app1\src\com\lara\GetLoginController.java
package com.lara;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;

www.javaeasytoall.com

39

Radha Technologies

Spring Frameworks

9500085257

import org.springframework.web.servlet.mvc.Controller;
public class GetLoginController implements Controller
{
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
return new ModelAndView("login.jsp");
}
}
6. Create login.jsp
Spring-app1\WebContent\login.jsp
<%@ taglib uri="http://www.springframework.org/tags" prefix="core" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<core:message code="login.welcome"/><br>
<form action="doLogin.do" method="post">
<core:message code="login.username"/>
<input type="text" name="username"><br>
<core:message code="login.password"/>
<input type="password" name="password">
<br> <input
type="submit" value="GetLogin">
</form>
7. Create Login command class
spring-app1\src\com\lara\Login.java
package com.lara;
public class Login
{
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
8. Create DoLoginController
spring-app1\src\com\lara\DoLoginController.java
package com.lara;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

www.javaeasytoall.com

40

Radha Technologies

Spring Frameworks

9500085257

public class DoLoginController extends SimpleFormController


{
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse
response,
Object
BindException errors)
throws Exception {
Login login = (Login)command;
System.out.println(login.getUsername()
+"========="+login.getPassword());
return new ModelAndView("success.jsp");
}
}

command,

9. success.jsp
Spring-app1\WebContent\success.jsp

YOU SUCCESSFULLY LOGGED IN


Simple-Development with Validation Feature
1. create one properties file inorder to read static messages.
2. register the properties file in applicationContext.xml file
3. register the ContextLoaderListener listener class inside your web.xml file inorder
to read the content of applicationContext.xml file
1. Creating messages.properties file
login.href=Login
login.username=UserName
login.password=Password
username.require=Usernaame is mandatory. enter correct username
password.require=Password is mandatory. enter correct password
2. creating applicationContext.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
</beans>

www.javaeasytoall.com

41

Radha Technologies

Spring Frameworks

9500085257

3. Modify web.xml in WEB-INF directory


<web-app>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>b
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
4. Create Index.jsp
<%@ taglib prefix="core"
uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form"
uri="http://www.springframework.org/tags/form" %>
<a href="login.do">
<core:message code="login.href"/>
</a>
5. Creating configuration file with the value of <servlet-name> tag
i.e Controller-servlet.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandler Mapping">
<property name="mappings">
<props>
<prop key="/login.do">loginController</prop>
</props>
</property>
</bean>
<bean id="loginController" class="com.lara.login.LoginController">
<property name="formView" value="login.jsp" />
<property name="commandClass" value="com.lara.login.LoginForm" />
<property name="commandName" value="loginForm" />
<property name="validator" ref="loginValidator" />
</bean>
<bean id="loginValidator" class="com.lara.login.LoginValidator" />
</beans>

www.javaeasytoall.com

42

Radha Technologies

Spring Frameworks

9500085257

6. create login.jsp
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form method="post">
<core:hasBindErrors name="loginForm">
<font color="red">Please Fix All Errors</font>
</core:hasBindErrors>
<core:message code="login.username" />
<core:bind path="loginForm.username">
<input type="text" name="username" value="${status.value }">
${status.errorMessage }
</core:bind>
<br>
<core:message code="login.password" />
<core:bind path="loginForm.password">
<input type="password" name="password" value="${status.value }">
${status.errorMessage }
</core:bind>
<br>
<input type="submit" value="Login">
</form:form>
7. Create LoginForm.java
package com.lara.login;
public class LoginForm
{
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
8. Creating LoginValidator.java
package com.lara.login;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
public class LoginValidator implements Validator
{
public boolean supports(Class arg0)
{
return arg0.equals(LoginForm.class);
}

www.javaeasytoall.com

43

Radha Technologies

Spring Frameworks

9500085257

public void validate(Object arg0, Errors arg1)


{
LoginForm login = (LoginForm)arg0;
String uid = login.getUsername();
if(uid==null || uid.length()==0)
{
arg1.rejectValue("username", "username.require",
UserName Failed");
}
String pw = login.getPassword();
if(pw==null || pw.length()==0)
{
arg1.rejectValue("password",
"password.require",
Password Failed");
}
}
}

"Please

Enter.

"Please

Enter.

9. Develop a LoginController.java
package com.lara.login;
import
import
import
import
import

javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
org.springframework.validation.BindException;
org.springframework.web.servlet.ModelAndView;
org.springframework.web.servlet.mvc.SimpleFormController;

public class LoginController extends SimpleFormController


{
protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse
response, Object command, BindException errors) throws Exception {
LoginForm login = (LoginForm)command;
String uid = login.getUsername();
String pw = login.getPassword();
if("ramuesh".equals(uid) && "1234".equals(pw))
{
return new ModelAndView("success.jsp");
}
else
{
return new ModelAndView("login.jsp");
}
}
}
10. Develop the success.jsp
Login Success.

www.javaeasytoall.com

44

Radha Technologies

Spring Frameworks

9500085257

File upload Development


* inorder to upload a file, you required two more jar files
i.e. commons-fileupload.jar and commands-io.jar
* inside your configuration file register one multipart resolver for
uploads, implementation for CommansFileUploads

parsing file

1. messages.properties
create one message resource file to read the static messages.
Spring-app4\src\messages.properties
registration.href=NewUser?
registration.firstName=FirstName
registration.lastName=LastName
registration.resume=Resume
registration.firstName.required=FirstName is Mandatory. Please Enter it.
registration.lastName.required=LastName is Mandatory. Please Enter it.
2. applicationContext.xml
Spring-app4\webcontext\WEB-INF\applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
</beans>
3. Modify web.xml in WEB-INF directory
Spring-app4\webcontext\WEB-INF\web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
id="WebApp_ID"
version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>spring-file-dev</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>RegistrationController</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>RegistrationController</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<listener>

www.javaeasytoall.com

45

Radha Technologies

Spring Frameworks

9500085257

<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
4. create one index.jsp page as the entry point for your application
Spring-app4\webcontext\index.jsp
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<a href="registration.do">
<core:message code="registration.href" />
</a>
5. create one configuration file in WEB-INF
Spring-app4\webcontext\WEB-INF\RegistrationController.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
</bean>
<bean
id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/registration.do">
registrationController
</prop>
</props>
</property>
</bean>
<bean id="registrationController" class="com.lara.reg.RegistrationController" >
<property name="formView" value="registration.jsp" />
<property name="commandClass" value="com.lara.reg.RegistrationForm" />
<property name="commandName" value="registrationForm" />
<property name="validator" ref="registrationValidator" />
</bean>
<bean id="registrationValidator" class="com.lara.reg.RegistrationValidator" />
</beans>
6. Develop one registration form
Spring-app4\webcontext\registration.jsp
If your form is containing any form-fields which is to be used to upload a file then that form
tag should have a attribute enctype with value as multipart/form-data
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<body>

www.javaeasytoall.com

46

Radha Technologies

Spring Frameworks

9500085257

<form:form method="post" enctype="multipart/form-data">


<core:bind path="registrationForm.firstName">
<core:message code="registration.firstName"/>
<input type="text" name="firstName" value="${status.value}">
${status.errorMessage}
</core:bind><br>
<core:bind path="registrationForm.lastName">
<core:message code="registration.lastName"/>
<input type="text" name="lastName" value="${status.value}">
${status.errorMessage}
</core:bind><br>
<core:bind path="registrationForm.resume">
<core:message code="registration.resume"/>
<input type="file" name="resume" value="${status.value}">
${status.errorMessage}
</core:bind><br>
<input type="submit" value="Submit">
</form:form>
</body>
7. Develop one CommandBean class with the form input fileds as its attributes
In order to upload a file the attribute data-type should be MultipartFile class type
Spring-app4\src\com\lara\reg\RegistrationForm.java
package com.lara.reg;
import org.springframework.web.multipart.MultipartFile;
public class RegistrationForm
{
private String firstName;
private String lastName;
private MultipartFile resume;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public MultipartFile getResume() {
return resume;
}
public void setResume(MultipartFile resume) {
this.resume = resume;
}
}

www.javaeasytoall.com

47

Radha Technologies

Spring Frameworks

9500085257

8. Inorder to validate the form fields develop one separate validator class which
should implements the Validator interface
* implement the unimplement methods from the Validator interface
* i.e. implement the supports() and validate() methods in your class
Spring-app4\src\com\lara\reg\RegistrationValidator.java
package com.lara.reg;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
public class RegistrationValidator implements Validator
{
public boolean supports(Class arg0)
{
return arg0.equals(RegistrationForm.class);
}
public void validate(Object arg0, Errors arg1)
{
RegistrationForm form=(RegistrationForm)arg0;
String fn=form.getFirstName();
if(fn==null || fn.length()==0)
{
arg1.rejectValue("firstName", "registration.firstName.required", "FirstNme is
required. please Enter.");
}
String ln=form.getLastName();
if(ln==null || ln.length()==0)
{
arg1.rejectValue("lastName", "registration.lastName.required", "LastNme is
required. please Enter.");
}
String resume=form.getResume().getOriginalFilename();
if(resume==null || resume.length()==0)
{
arg1.rejectValue("resume", "registration.resume.required", "Resume Field
Required. Please upload.");
}
}
}
9. Develop a Specific Controller to your application
* override the onSubmit() method in your app specific controller.
If you are submitting any form to the server side then your controller
Should extend to SimpleFormController

Spring-app4\src\com\lara\reg\RegistrationController.java

www.javaeasytoall.com

48

Radha Technologies

Spring Frameworks

9500085257

package com.lara.reg;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class RegistrationController extends SimpleFormController
{
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException
throws Exception
{
RegistrationForm form=(RegistrationForm)command;
System.out.println(form.getFirstName());
System.out.println(form.getLastName());
System.out.println(form.getResume().getBytes().length);
return new ModelAndView("success.jsp");
}
}

errors)

10. success.jsp
Spring-app4\webcontext\success.jsp
Success
Handling Exceptions in case of Spring Based Application
* take the previous example .
* In order to handle exceptions, develop your own Exception class or
use the existed one
exception classes.
* In side configuration file define one bean to handle the exceptions, under property tag of
bean keep all the exception classes which you wants to handle.
11. Developing our own Exception Class
spring-app4\src\com\lara\reg\UploadException.java
public class UploadException extends RuntimeException
{
private String message;
public RegistrationException()
{
}
public RegistrationException(String msg)
{
super(msg);
message=msg;
}
}

www.javaeasytoall.com

49

Radha Technologies

Spring Frameworks

9500085257

12. Inside configuration file under the root tag keep the below code.
<bean
id="ex-maps"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.lara.reg.UploadException ">error.jsp</prop>
<prop key="java.lang.RuntimeException">error1.jsp</prop>
</props>
</property>
</bean>
13. Developing the jsp pages to handle the corresponding exceptions.
13.1 error.jsp(to handle the UploadException)
${exception.message}
13.2 error1.jsp(to handle the RuntimeException)
${exception.message}
14. keep the sample code in your Contoller class inorder to rise the exceptions.
if(true)
{
//throw new RegistrationException("Some Exception accured while uploading Resume");
throw new RegistrationException("Runtime Exception accured while uploading Resume");
}
Wizard Development in Spring Based Application
1. index.jsp
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<center>
<a href="wizardRegistration.do">
<core:message code="wizardRegistration.href" />
</a>
</center>
2. messages.properties
wizardRegistration.href=WizardRegistration
wizardRegistration.firstName=FirstName
wizardRegistration.lastName=LastName
wizardRegistration.resume=Resume
wizardRegistration.firstName.required=FirstName is Mandatory. Please Enter it.
wizardRegistration.lastName.required=LastName is Mandatory. Please Enter it.
wizardRegistration.resume.required=Resume Field is Mandatory.
3. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
</beans>

www.javaeasytoall.com

50

Radha Technologies

Spring Frameworks

9500085257

4. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app >
<display-name>spring-file-dev</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>RegistrationController</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>RegistrationController</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
5. RegistrationController-servlet.xml
In case of wizard develop there is no need the property tag for formView
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
</bean>
<bean
id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/wizardRegistration.do">
wizardRegistrationController
</prop>
</props>
</property>
</bean>
<bean id="wizardRegistrationController"
class="com.lara.wizard.RegistrationController" >
<property name="commandClass"
value="com.lara.wizard.RegistrationForm" />
<property name="commandName" value="wizardRegistrationForm" />
<property name="pages">

www.javaeasytoall.com

51

Radha Technologies

Spring Frameworks

9500085257
<list>

<value>registration0.jsp</value>
<value>registration1.jsp</value>
<value>registration2.jsp</value>

</list>
</property>
<property name="sessionForm" value="true"/>
</bean>
</beans>
6. RegistrationForm.java
package com.lara.wizard;
import org.springframework.web.multipart.MultipartFile;
public class RegistrationForm
{
private String firstName;
private String lastName;
private MultipartFile resume;

public String getFirstName() {


return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public MultipartFile getResume() {
return resume;
}
public void setResume(MultipartFile resume) {
this.resume = resume;
}

7. RegistrationController.java
In case of wizard development
the controller class should extend to
AbstractWizardFormController and it should override the processFinish()and validate()
methods
package com.lara.wizard;
import
import
import
import
import
import

javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
org.springframework.validation.BindException;
org.springframework.validation.Errors;
org.springframework.validation.ValidationUtils;
org.springframework.web.servlet.ModelAndView;

www.javaeasytoall.com

52

Radha Technologies

Spring Frameworks

9500085257

import org.springframework.web.servlet.mvc.AbstractWizardFormController;
public class RegistrationController extends AbstractWizardFormController
{
protected ModelAndView processFinish(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, BindException arg3)
throws Exception {
RegistrationForm form=(RegistrationForm)arg2;
System.out.println(form.getFirstName());
System.out.println(form.getLastName());
System.out.println(form.getResume().getBytes().length);
return new ModelAndView("success.jsp");
}
protected void validatePage(Object command, Errors errors, int page) {
RegistrationForm form=(RegistrationForm)command;
if(page==0)
{
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"firstName", "wizardRegistration.firstName.required");
}
if(page==1)
{
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName",
"wizardRegistration.lastName.required");
}
if(page==2)
{
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "resume",
"wizardRegistration.resume.required");
}
}
}
8. registration0.jsp
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form method="post" >
<core:bind path="wizardRegistrationForm.firstName">
<core:message code="wizardRegistration.firstName"/>
<input type="text" name="firstName" value="${status.value}">
${status.errorMessage}
</core:bind><br>
<input type="submit" value="Submit" name="_target1"">
</form:form>
9. registration1.jsp
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form method="post" >
<core:bind path="wizardRegistrationForm.lastName">
<core:message code="wizardRegistration.lastName"/>

www.javaeasytoall.com

53

Radha Technologies

Spring Frameworks

9500085257

<input type="text" name="lastName" value="${status.value}">


${status.errorMessage}
</core:bind><br>
<input type="submit" value="Submit" name="_target2"">
</form:form>
10. registration2.jsp
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form method="post" enctype="multipart/form-data">
<core:bind path="wizardRegistrationForm.resume">
<core:message code="wizardRegistration.resume"/>
<input type="file" name="resume" value="${status.value}">
${status.errorMessage}
</core:bind><br>
<input type="submit" value="Submit" name="_finish"">
</form:form>
11. success.jsp
Success
A Simple Form Development by make use of ViewResolver
1. messages.properties
empAdd.href=AddEmployee
listEmp.href=ListAllEmployees
firstName.required=FirstName is Mandatory. Please Enter It.
gender.required=Gender is Mandatory
skills.required=Skills are Required
qualification.required=Qualification is Mandatory
emp.firstName=FirstName
emp.gender=Gender
emp.skills=Skills
emp.qualification=Qualification
2. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
</beans>
3. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
id="WebApp_ID"
version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

www.javaeasytoall.com

54

Radha Technologies

Spring Frameworks

9500085257

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>spring-viewresolver</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
4. test-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property
name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean
id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="empAdd.do">empAddController</prop>
</props>
</property>
</bean>
<bean id="empAddController" class="com.lara.emp.EmployeeAddController">
<property name="formView" value="employee"/>
<property name="commandClass" value="com.lara.emp.Employee"/>
<property name="commandName" value="employee"/>
<property name="validator" ref="empValidator"/>
</bean>
<bean id="empValidator" class="com.lara.emp.EmployeeValidator"/>
</beans>

www.javaeasytoall.com

55

Radha Technologies

Spring Frameworks

9500085257

5. index.jsp
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<center>
<a href="empAdd.do">
<core:message code="empAdd.href"/>
</a>
<br><br>
<a href="listEmp.do">
<core:message code="listEmp.href"/>
</a>
</center>
6. Employee,java
package com.lara.emp;
public class Employee
{
private String firstName;
private String gender;
private String[] skills;
private String qualification;

public String getFirstName() {


return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String[] getSkills() {
return skills;
}
public void setSkills(String[] skills) {
this.skills = skills;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}

7. EmployeeValidator.java

www.javaeasytoall.com

56

Radha Technologies

Spring Frameworks

9500085257

package com.lara.emp;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
public class EmployeeValidator implements Validator
{
public boolean supports(Class arg0)
{
return arg0.equals(Employee.class);
}
public void validate(Object arg0, Errors arg1)
{
Employee emp=(Employee)arg0;
String fn=emp.getFirstName();
if(fn==null || fn.length()==0)
{
arg1.rejectValue("firstName", "firstName.required", "FirstName is
Required");
}
String gender=emp.getGender();
if(gender==null || gender.length()==0)
{
arg1.rejectValue("gender", "gender.required", "Gender is Required");
}
String skills[]=emp.getSkills();
if(skills==null || skills.length==0)
{
arg1.rejectValue("skills", "skills.required", "skills are Required");
}
String qualification=emp.getQualification();
if("pls".equals(qualification))
{
arg1.rejectValue("qualification", "qualification.required", "Qualification
are Required");
}
}
}
8. EmployeeAddController.java
package com.lara.emp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

www.javaeasytoall.com

57

Radha Technologies

Spring Frameworks

9500085257

public class EmployeeAddController extends SimpleFormController


{
@Override
protected Map referenceData(HttpServletRequest request) throws Exception
{
Map map=new HashMap();
ArrayList genders=new ArrayList();
genders.add("Male");
genders.add("Female");
map.put("genders", genders);
ArrayList skills=new ArrayList();
skills.add("C");
skills.add("Cpp");
skills.add("Java");
skills.add("Oracle");
map.put("skills", skills);
ArrayList qualificatiions=new ArrayList();
qualificatiions.add("pls");
qualificatiions.add("B.Sc");
qualificatiions.add("B.Tech");
qualificatiions.add("M.Tech");
qualificatiions.add("M.C.A");
map.put("qualificatiions", qualificatiions);
return map;
}
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command,
errors)

BindException

throws Exception {
Employee emp=(Employee)command;
System.out.println(emp.getFirstName());
System.out.println(emp.getGender());
for(String skill : emp.getSkills())
{
System.out.println(skill+",");
}
System.out.println();
System.out.println(emp.getQualification());
return new ModelAndView("success");
}

}
9. employee,jsp
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="/WEB-INF/custom.tld" %>
<body>
<core:hasBindErrors name="employee">

www.javaeasytoall.com

58

Radha Technologies

Spring Frameworks

9500085257

<h3><font color="red">Pls Fix All Erros</font></h3>


</core:hasBindErrors>
<form:form>
<core:message code="emp.firstName"/>
<core:bind path="employee.firstName">
<input type="text" name="firstName" value="${status.value}">
<font color="red">${status.errorMessage}</font>
</core:bind><br>
<core:message code="emp.gender"/><br>
<core:bind path="employee.gender">
<c:forEach var="item" items="${genders}">
<input
type="radio"
name="gender"
value="${item}"
<c:if
test="${status.value==item}">checked</c:if>>${item}
</c:forEach>
<font color="red">${status.errorMessage}</font>
</core:bind><br>
<core:message code="emp.skills"/><br>
<core:bind path="employee.skills">
<c:forEach var="item" items="${skills}">
<input type="checkbox" name="skills" value="${item}" <c:if test="$
{fn:compare(status.value,item)}">checked</c:if>>${item}
</c:forEach>
<font color="red">${status.errorMessage}</font>
</core:bind><br>
<core:message code="emp.qualification"/><br>
<core:bind path="employee.qualification">
<select name="qualification">
<c:forEach var="item" items="${qualificatiions}">
<option
value="${item}"
<c:if
test="$
{status.value==item}">selected</c:if>>
${item}
</c:forEach>
</select>
<font color="red">${status.errorMessage}</font>
</core:bind><br>
<input type="submit" value="Submit">
</form:form>
10. custom.tld
<taglib>
<tlib-version>1</tlib-version>
<jsp-version>2</jsp-version>
<uri>test</uri>
<function>
<name>compare</name>
<function-class>com.lara.el.Check</function-class>
<function-signature>
java.lang.Boolean compare(java.lang.String[], java.lang.String)
</function-signature>
</function>
</taglib>
11. Check.java

www.javaeasytoall.com

59

Radha Technologies

Spring Frameworks

9500085257

package com.lara.el;
import java.util.Arrays;
public class Check
{
public static boolean compare(String[] skills, String skill)
{
if(skills != null)
{
Arrays.sort(skills);
int i=Arrays.binarySearch(skills, skill);
if(i<0)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
}
12. success.jsp
Employee Added Successfully.
The Complete CRUD Application with Database Interaction.
1. messages.properties
addEmp=Want to add one employee
firstName=FirstName
gender=Gender
skills=Skills
qual=Qualification
listEmp=list of employees
2. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
id="WebApp_ID"
version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>
crudapp-1</display-name>
<welcome-file-list>

www.javaeasytoall.com

60

Radha Technologies

Spring Frameworks

9500085257

<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
3. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<bean
id="driversource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/lara"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
</beans>
4. sql.sql
create table genders
(
id int auto_increment unique key,
name varchar(78),
desc1 varchar(78)
);
insert into genders
(
name,
desc1
)
values
(

www.javaeasytoall.com

61

Radha Technologies

Spring Frameworks

9500085257

'male',
'male description'
);
insert into genders
(
name,
desc1
)
values
(
'female',
'female description'
);
create table skills
(
id int auto_increment unique key,
name varchar(78),
desc1 varchar(7)
);
insert into skills
(
name,
desc1
)
values
(
'Cpp',
'Cpp-description'
);
insert into skills
(
name,
desc1
)
values
(
'c',
'C-description'
);
insert into skills
(
name,
desc1
)
values
(
'Java',
'Java-description'
);
insert into skills
(
name,
desc1
)

www.javaeasytoall.com

62

Radha Technologies

Spring Frameworks

9500085257

values
(
'Oracle',
'Oracle-description'
);
create table qualifications
(
id int auto_increment unique key,
name varchar(78),
desc1 varchar(7)
);
insert into qualifications
(
name,
desc1
)
values
(
'plz',
'plz-description'
);
insert into qualifications
(
name,
desc1
)
values
(
'MCA',
'M-C-A-description'
);
insert into qualifications
(
name,
desc1
)
values
(
'M-tech',
'M-tech-description'
);
insert into qualifications
(
name,
desc1
)
values
(
'B-tech',
'B-tech-description'
);
create table persons
(
id int auto_increment unique key,

www.javaeasytoall.com

63

Radha Technologies

Spring Frameworks

9500085257

first_name varchar(67),
gender varchar(6),
skills varchar(7),
qualification varchar(78)
);
5. simple-servlet.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

BEAN

2.0//EN"

<beans>
<bean
id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property
name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean
id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key = "addEmp.do">empaddController</prop>
<prop key = "listEmp.do">emplistController</prop>
<prop key = "editEmp.do">empeditController</prop>
</props>
</property>
</bean>
<bean id="empeditController" class="com.lara.EmpEditController">
<property name="formView" value="addemp"/>
<property name="commandName" value="empForm"/>
<property name="commandClass" value="com.lara.Employee"/>
<property name="validator" ref="empValidator"/>
</bean>
<bean id="emplistController" class="com.lara.ListEmpController"/>
<bean id="empaddController" class="com.lara.EmpAddController">
<property name="formView" value="addemp"/>
<property name="commandName" value="empForm"/>
<property name="commandClass" value="com.lara.Employee"/>
<property name="validator" ref="empValidator"/>
</bean>
<bean id="empValidator" class="com.lara.EmpValidator"/>
</beans>
6. DbUtil.java
package com.lara;
import
import
import
import

java.sql.Connection;
java.sql.SQLException;
javax.servlet.ServletContext;
org.springframework.context.ApplicationContext;

www.javaeasytoall.com

64

Radha Technologies

Spring Frameworks

9500085257

import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class DbUtil
{
public static Connection getConnection(ServletContext context)throws SQLException
{
ApplicationContext appContext = null;
appContext
=
WebApplicationContextUtils.getWebApplicationContext(context);
DriverManagerDataSource
ds
=
(DriverManagerDataSource)appContext.getBean("driversource");
Connection con = ds.getConnection();
return con;
}
}
7. index.jsp
<%@taglib prefix="core" uri="http://www.springframework.org/tags" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<a href="addEmp.do">
<core:message code = "addEmp"></core:message>
</a><br>
<a href="listEmp.do">
<core:message code = "listEmp"></core:message>
</a>
8. addemp.jsp
<%@taglib
<%@taglib
<%@taglib
<%@taglib

prefix="core" uri="http://www.springframework.org/tags"%>
prefix="form" uri="http://www.springframework.org/tags/form"%>
prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
prefix="fn" uri="/WEB-INF/custom.tld" %>

<core:hasBindErrors name="empForm">
<h3> <font color='red'>Plz fix errors</font></h3>
</core:hasBindErrors><br>
<form:form method="post">
<core:message code="firstName"/>
<core:bind path="empForm.firstname">
<input type="text" name="firstname" value="${status.value}">
${status.errorMessage}
</core:bind><br>
<core:message code = "gender"/>
<core:bind path="empForm.gender">
<c:forEach var = "item" items="${genders}">
<input type="radio" name="gender" value="${item}"
<c:if test="${status.value == item}">checked</c:if>>${item}<br>
</c:forEach>
${status.errorMessage}
</core:bind>
<core:message code = "skills"/>

www.javaeasytoall.com

65

Radha Technologies

Spring Frameworks

9500085257

<core:bind path="empForm.skills">
<c:forEach var = "item" items="${skills}">
<input type="checkbox" name="skills" value="${item}"
<c:if
test="${fn:compare(status.value,item)}">checked</c:if>>$
{item}<br>
</c:forEach>
${status.errorMessage}
</core:bind>
<core:message code="qual"/>
<core:bind path="empForm.qualification">
<select name="qualification">
<c:forEach var = "item" items="${quals}">
<option value = "${item }"
<c:if test="${status.value == item}">selected</c:if>>$
{item}
</option>
</c:forEach>
</select>
${status.errorMessage}
</core:bind>
<input type="submit" value="submit">
</form:form>
9. Employee.java
package com.lara;
public class Employee
{
private Integer id;
private String firstname;
private String gender;
private String[] skills;
private String qualification;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String[] getSkills() {
return skills;
}
public void setSkills(String[] skills) {
this.skills = skills;
}
public String getQualification() {

www.javaeasytoall.com

66

Radha Technologies

Spring Frameworks

9500085257

return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}

10. EmpValidator.java
package com.lara;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
public class EmpValidator implements Validator
{
public boolean supports(Class arg0) {
return arg0.equals(Employee.class);
}
public void validate(Object arg0, Errors arg1) {
Employee emp = (Employee)arg0;

String fn = emp.getFirstname();
if(fn == null || fn.length() == 0)
{
arg1.rejectValue("firstname", "first-required","plz enter firstname");
}
String gender = emp.getGender();
if(gender == null || gender.length() == 0)
{
arg1.rejectValue("gender", "gender-required","plz enter gender");
}
String skills[] = emp.getSkills();
if(skills == null || skills.length == 0)
{
arg1.rejectValue("skills","skills-reqiured", "plz enter skills");
}
String qual = emp.getQualification();
if("plz".equals(qual))
{
arg1.rejectValue("qualification", "qual-requies", "plz enter qual");
}

www.javaeasytoall.com

67

Radha Technologies

Spring Frameworks

9500085257

11. EmpAddController.java
package com.lara;
import
import
import
import
import
import
import
import
import
import
import
import

java.sql.Connection;
java.sql.ResultSet;
java.sql.SQLException;
java.sql.Statement;
java.util.ArrayList;
java.util.HashMap;
java.util.Map;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
org.springframework.validation.BindException;
org.springframework.web.servlet.ModelAndView;
org.springframework.web.servlet.mvc.SimpleFormController;

public class EmpAddController extends SimpleFormController


{
protected Map referenceData(HttpServletRequest request) throws Exception {
Map map = new HashMap();
Connection
con
=
DbUtil.getConnection(request.getSession().getServletContext());
//ArrayList genders = new ArrayList();
ArrayList genders = getMasterData(con,"genders");
ArrayList skills = getMasterData(con,"skills");
ArrayList quals = getMasterData(con,"qualifications");
map.put("genders", genders);
map.put("skills", skills);
map.put("quals", quals);
return map;
}
private ArrayList getMasterData(Connection con , String Table)throws SQLException
{
ArrayList list = new ArrayList();
Statement stmt = null;
ResultSet rs = null;
try
{
stmt = con.createStatement();
rs = stmt.executeQuery("select * from " + Table);
while(rs.next())
{
list.add(rs.getString(2));
}
}
finally
{
if(rs != null)
{
rs.close();
rs = null;

www.javaeasytoall.com

68

Radha Technologies

Spring Frameworks

9500085257
}
if(stmt != null)
{
stmt.close();
stmt = null;
}

}
return list;

}
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command,

BindException

errors)

throws Exception {
Employee emp = (Employee)command;
Connection
con
DbUtil.getConnection(request.getSession().getServletContext());
saveEmployee(con,emp);
return new ModelAndView("success");
}
private void saveEmployee(Connection con, Employee emp)throws SQLException
{
Statement stmt = null;
try
{
stmt = con.createStatement();
StringBuilder sb= new StringBuilder();
sb.append("insert into persons");
sb.append("(");
sb.append("firstname,");
sb.append("gender,");
sb.append("skills,");
sb.append("qualification");
sb.append(")");
sb.append("values");
sb.append("(");
sb.append("'"+emp.getFirstname()+"',");
sb.append("'"+emp.getGender()+"',");
sb.append("'");
for(String s :emp.getSkills())
{
sb.append(s + "',");
}
sb.append("'" + emp.getQualification()+"'");
sb.append(");");
System.out.println(sb);
stmt.executeUpdate(sb.toString());
}
finally
{
if(stmt != null)
{
stmt.close();
stmt = null;

www.javaeasytoall.com

69

Radha Technologies

Spring Frameworks
}

9500085257
}

}
}
12. EmpEditController.java
package com.lara;
import
import
import
import
import
import
import

java.sql.Connection;
java.sql.ResultSet;
java.sql.SQLException;
java.sql.Statement;
java.util.ArrayList;
java.util.HashMap;
java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class EmpEditController extends SimpleFormController
{
protected Map referenceData(HttpServletRequest request) throws Exception {
Map map = new HashMap();
Connection
con
=
DbUtil.getConnection(request.getSession().getServletContext());
ArrayList genders = getMasterData(con,"genders");
ArrayList skills = getMasterData(con,"skills");
ArrayList quals = getMasterData(con,"qualifications");
map.put("genders", genders);
map.put("skills", skills);
map.put("quals", quals);
return map;
}
private ArrayList getMasterData(Connection con , String Table)throws SQLException
{
ArrayList list = new ArrayList();
Statement stmt = null;
ResultSet rs = null;
try
{
stmt = con.createStatement();
rs = stmt.executeQuery("select * from " + Table);
while(rs.next())
{
list.add(rs.getString(2));
}
}
finally

www.javaeasytoall.com

70

Radha Technologies

Spring Frameworks
{

9500085257
if(rs != null)
{
rs.close();
rs = null;
}
if(stmt != null)
{
stmt.close();
stmt = null;
}

}
return list;
}
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
String id = request.getParameter("id");
Connection
con
DbUtil.getConnection(request.getSession().getServletContext());
Employee emp = getEmployee(con,id);
return emp;
}
private Employee getEmployee(Connection con,String id) throws SQLException
{
Employee emp = null;
Statement stmt = null;
ResultSet rs = null;
try
{
stmt = con.createStatement();
rs = stmt.executeQuery("select * from persons where id="+id);
if(rs.next())
{
emp = new Employee();
emp.setFirstname(rs.getString("firstname"));
emp.setGender(rs.getString("gender"));
emp.setSkills(rs.getString("skills").split(","));
emp.setQualification(rs.getString("qualification"));
}
}
finally
{
if(rs != null)
{
rs.close();
rs = null;
}
if(stmt != null)
{
stmt.close();
stmt = null;
}

www.javaeasytoall.com

71

Radha Technologies

Spring Frameworks

9500085257

}
return emp;

errors)

}
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command,

BindException

throws Exception {
Employee emp = (Employee)command;
Connection
con
DbUtil.getConnection(request.getSession().getServletContext());
String id = request.getParameter("id");
saveEmployee(con,emp,id);
return new ModelAndView("grandSuccess");
}
private void saveEmployee(Connection con, Employee emp,String
SQLException
{
Statement stmt = null;
try
{
stmt = con.createStatement();
StringBuilder sb= new StringBuilder();
sb.append("update persons ");
sb.append("set firstname='"+emp.getFirstname()+"',");
sb.append("gender='"+emp.getGender()+"',");
sb.append("skills='");
for(String s:emp.getSkills())
{
sb.append(s+",");
}
sb.append("',");
sb.append("qualification='"+emp.getQualification()+"'");
sb.append("where id = "+emp.getId());

id)throws

System.out.println(sb);
stmt.executeUpdate(sb.toString());
}
finally
{

if(stmt != null)
{
stmt.close();
stmt = null;
}

}
13. ListEmpController.java
package com.lara;
import java.sql.Connection;

www.javaeasytoall.com

72

Radha Technologies

Spring Frameworks
import
import
import
import
import
import
import
import
import
import
import
import

9500085257

java.sql.ResultSet;
java.sql.SQLException;
java.sql.Statement;
java.util.ArrayList;
javax.servlet.ServletContext;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
org.springframework.context.ApplicationContext;
org.springframework.jdbc.datasource.DriverManagerDataSource;
org.springframework.web.context.support.WebApplicationContextUtils;
org.springframework.web.servlet.ModelAndView;
org.springframework.web.servlet.mvc.Controller;

public class ListEmpController implements Controller


{
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
ArrayList list = new ArrayList();
list = getEmployees(arg0.getSession().getServletContext());
ModelAndView mav = new ModelAndView("listAll");
mav.addObject("employees" , list);
return mav;

}
private ArrayList getEmployees(ServletContext context)throws SQLException
{
ArrayList list = new ArrayList();
ApplicationContext appcontext = null;
appcontext = WebApplicationContextUtils.getWebApplicationContext(context);
DriverManagerDataSource
data
=
(DriverManagerDataSource)appcontext.getBean("driversource");
Connection con = data.getConnection();
Statement stmt = null;
ResultSet rs = null;
try
{
stmt = con.createStatement();
rs = stmt.executeQuery("select * from persons");
while(rs.next())
{
Employee emp = new Employee();
emp.setId(rs.getInt("id"));
emp.setFirstname(rs.getString("firstname"));
emp.setGender(rs.getString("gender"));
emp.setSkills(rs.getString("skills").split(","));
emp.setQualification(rs.getString("qualification"));
list.add(emp);
}
}
finally
{
if(rs != null)
{

www.javaeasytoall.com

73

Radha Technologies

Spring Frameworks

9500085257
rs.close();
rs = null;
}
if(stmt != null)
{
stmt.close();
stmt = null;
}

}
return list;
}

14. Check.java
package com.lara;
import java.util.Arrays;
public class Check
{
public static Boolean compare(String skills[] , String skill)
{
if(skills != null)
{
Arrays.sort(skills);
int i = Arrays.binarySearch(skills, skill);
if(i < 0)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
}
15. custom.tld
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<function>
<name>compare</name>
<function-class>com.lara.Check</function-class>
<function-signature>
java.lang.Boolean compare(java.lang.String[],java.lang.String)

www.javaeasytoall.com

74

Radha Technologies

Spring Frameworks

9500085257

</function-signature>
</function>
</taglib>
16. listAll.jsp
<%@taglib prefix="core" uri="http://www.springframework.org/tags"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<center>
<table border='1' bgcolor="green">
<tr>
<td>
id
</td>
<td>
FirstName
</td>
<td>
Gender
</td>
<td>
Skills
</td>
<td>
Qualification
</td>
</tr>
<c:forEach var = "employee" items="${employees}">
<tr>
<td>
${employee.id}
</td>
<td>
<a href="editEmp.do?id=${employee.id}">
${employee.firstname}
</a>
</td>
<td>
${employee.gender}
</td>
<td>
<c:forEach var = "skill" items="${employee.skills}">
${skill}
</c:forEach>
</td>

</tr>
</c:forEach>
</table>

<td>
${employee.qualification}<br>
</td>

www.javaeasytoall.com

75

Radha Technologies

Spring Frameworks

9500085257

</center>
17. success.jsp
<marquee>
<font color='#660066' size='5'>
successfully added into database
</font>
</marquee>
18.grandSuccess.jsp
<marquee>
<font color='blue' size='9'>
successfully modified in database
</font>
</marquee>
Simple MultiAction dev
messages.properties
1. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
</beans>
2. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
id="WebApp_ID"
version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>
multi-action-controller</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener

www.javaeasytoall.com

76

Radha Technologies

Spring Frameworks

class>

9500085257

</listener-class>
</listener>
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-

<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
3. simple-servlet.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

BEAN

2.0//EN"

<beans>

<bean
id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="hello.do">multiactioncontroller</prop>
</props>
</property>
</bean>
<bean id="multiactioncontroller" class="com.lara.MultiActController">
<property name="methodNameResolver" ref="paramResolver"/>
</bean>
<bean
id="paramResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="action"/>
</bean>
</beans>
4. MultiActionController.java
package com.lara;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class MultiActController extends MultiActionController
{
public ModelAndView add(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception
{
ModelAndView mav = new ModelAndView("testpage.jsp");

www.javaeasytoall.com

77

Radha Technologies

Spring Frameworks

9500085257

mav.addObject("test","add");
return mav;
}
public ModelAndView delete(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception
{
ModelAndView mav = new ModelAndView("testpage.jsp");
mav.addObject("test","delete");
return mav;
}
public ModelAndView list(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception
{
ModelAndView mav = new ModelAndView("testpage.jsp");
mav.addObject("test","list");
return mav;
}
}
5. hello.jsp
<a href="hello.do?action=add">Add</a><br>
<a href="hello.do?action=list">List</a><br>
<a href="hello.do?action=delete">Delete</a><br>
6. testPage.jsp
${test}
<br>
<a href="hello.jsp">Go back</a>
Adding Validator-Plugin feature to Spring
1. copy all relevant jar files
spring.jar
standard.jar
jstl.jar
commons-beanutils.jar
commons-digester.jar
commons-validator.jar
springmodules-validator-0.1.jar
2. index.jsp
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<a href="login.do">
<core:message code="login.href" />
</a>
3. web.xml
<?xml version="1.0" encoding="UTF-8"?>

www.javaeasytoall.com

78

Radha Technologies

Spring Frameworks

9500085257

<web-app
id="WebApp_ID"
version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>
validator-plugin
</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
4. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

BEAN

2.0//EN"

<beans>
<bean
id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
</beans>
5. messages.properties
login.href=Login
login.username=UserName
login.password=Password
success.login=<h1><font color="Green">Login Success</font></h1>
errors.required={0} is required Field
6. login-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>

www.javaeasytoall.com

79

Radha Technologies

Spring Frameworks

9500085257

<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="validatorFactory"
class="org.springmodules.commons.validator.DefaultValidatorFactory">
<property name="validationConfigLocations">
<list>
<value>/WEB-INF/validator-rules.xml</value>
<value>/WEB-INF/validation.xml</value>
</list>
</property>
</bean>
<bean
id="beanValidator"
class="org.springmodules.commons.validator.DefaultBeanValidator">
<property name="validatorFactory" ref="validatorFactory" />
</bean>
<bean
id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property
name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean
id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/login.do">loginController</prop>
</props>
</property>
</bean>
<bean id="loginController" class="com.lara.login.LoginController">
<property name="formView" value="login"/>
<property name="commandClass" value="com.lara.login.Login"/>
<property name="commandName" value="login"/>
<property name="validator" ref="beanValidator"/>
<!--Commons Serverside validation -->
</bean>
</beans>
7. login.jsp
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="val" uri="http://www.springmodules.org/tags/commons-validator" %>
<core:hasBindErrors name="login">
<h2><font color="RED">PLEASE FIX THE ERRORS</font></h2>
</core:hasBindErrors>
<form:form onsubmit="return validateLogin(this)" method="post">
<core:message code="login.username"/>
<core:bind path="login.username">
<input type="text" name="username" value="${status.value}">
${status.errorMessage}

www.javaeasytoall.com

80

Radha Technologies

Spring Frameworks

9500085257

</core:bind><br>
<core:message code="login.password"/>
<core:bind path="login.password">
<input type="password" name="password" value="${status.value}">
${status.errorMessage}
</core:bind><br>
<input type="submit" value="submit">
</form:form>
<val:javascript formName="login"/>
8. Login.java
package com.lara.login;
public class Login
{
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
9. LoginController.java
package com.lara.login;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class LoginController extends SimpleFormController
{
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command,
errors)
throws Exception {
Login login = (Login)command;
System.out.println("USERNAME:"+login.getUsername());
System.out.println("Password:"+login.getPassword());
return new ModelAndView("success");
}
}

www.javaeasytoall.com

81

BindException

Radha Technologies

Spring Frameworks

9500085257

10. validation.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration
1.0//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_0.dtd">
<form-validation>
<formset>
<form name="login">
<field property="username" depends="required">
<arg0 key="login.username" />
</field>
<field property="password" depends="required">
<arg0 key="login.password" />
</field>
</form>
</formset>
</form-validation>
11. validator-rules.xml
copy the existing file into your WEB-INF floder
12. success.jsp
<%@ taglib prefix="core" uri="http://www.springframework.org/tags" %>
<core:message code="success.login"/>
Interacting with DB by using JDBC/DAO Module
1.
2.
3.
4.
5.

creating table schema


develop one pojo class with all table fields as attributes
develop one interface with our own methods
write one mapper class by implementing ResultSetExtractor
writer a row mapper class by extending RowMapper and override the mapRow
method.
6. Developing one implementation calss to our Interface.
7. develop one client class.
1. Creating Table Schema
sql.sql
create table books
(
id int auto_increment unique key,
title varchar(20),
author varchar(20)
);
2. Developing the pojo class
package com.lara.entity;
public class Book

www.javaeasytoall.com

82

Radha Technologies

Spring Frameworks
{

9500085257

public String getTitle()


{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
private String title;
private String author;

3. developing the interface with our own methods


package com.lara.db.dao;
import java.util.List;
import javax.sql.DataSource;
import com.lara.entity.Book;
public interface BookDAO
{
public void setDataSource(DataSource ds);
public void insert(String title, String author);
public void update(String fieldName, String initialKey, String finalKey);
public void delete(String fieldName, String key);
public List<Book> select(String title, String author);
public List<Book> selectAll();
}
4. Writing one Mapper class by implementing ResultSetExtractor
package com.lara.db.mapper;
import
import
import
import
import

java.sql.ResultSet;
java.sql.SQLException;
org.springframework.dao.DataAccessException;
org.springframework.jdbc.core.ResultSetExtractor;
com.lara.entity.Book;

public class BookResultSetExtractor implements ResultSetExtractor


{
public Object extractData(ResultSet arg0) throws SQLException,
DataAccessException

www.javaeasytoall.com

83

Radha Technologies

Spring Frameworks
{

9500085257

Book book = new Book();


book.setTitle(arg0.getString(1));
book.setAuthor(arg0.getString(2));
return book;

}
5. Writing the row mapper calss
package com.lara.db.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class BookRowMapper implements RowMapper
{

public Object mapRow(ResultSet arg0, int arg1) throws SQLException {


BookResultSetExtractor extractor = new BookResultSetExtractor();
return extractor.extractData(arg0);
}

6. Developing one implantation class to our interface


package com.lara.entity;
import
import
import
import
import

java.util.List;
javax.sql.DataSource;
org.springframework.jdbc.core.JdbcTemplate;
com.lara.db.dao.BookDAO;
com.lara.db.mapper.BookRowMapper;

public class BookDAOImpl implements BookDAO


{
private JdbcTemplate template = null;
public void setDataSource(DataSource ds)
{
template = new JdbcTemplate(ds);
}
public void insert(String title, String author)
{
template.update("insert into books(title, author) values(?,?)", new Object[]
{title, author});
}
public void update(String fieldName, String initialKey, String finalKey)
{
template.update("update books set " + fieldName + "='" + finalKey + "'
where " + fieldName + "='" + initialKey + "'");
}
public void delete(String fieldName, String key)
{

www.javaeasytoall.com

84

Radha Technologies

Spring Frameworks

9500085257

template.update("delete from books where " + fieldName + "='" + key + "'");


}
public List<Book> select(String title, String author)
{
return template.query("select title, author from books where title = ? and
author = ?", new Object[]{title, author}, new BookRowMapper());
}
public List<Book> selectAll()
{
return
template.query("select
title,
author
from
books",
new
BookRowMapper());
}
}
7. writing one client class
package com.lara.client;
import
import
import
import

java.util.List;
org.springframework.jdbc.datasource.DriverManagerDataSource;
com.lara.entity.Book;
com.lara.entity.BookDAOImpl;

public class Manager


{
public static void main(String args[])
{
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost/lara");
ds.setUsername("root");
ds.setPassword("");
BookDAOImpl dao = new BookDAOImpl();
dao.setDataSource(ds);
dao.delete("title", "abc");
}
}

ORM MODULE
Through spring using Hibernate is very easy by making use of ORM Module.
Simple Core-Application Development steps in ORM Module.
1. copy all relevant jar files to your`s application lib folder or update the build path with
relevant
jar files.
The relevant jar files are
spring-framework-2.0.4\dist\spring.jar
spring-framework-2.0.4\lib\cglib\cglib-nodep-2.1_3.jar
spring-framework-2.0.4\lib\dom4j\dom4j-1.6.1.jar
spring-framework-2.0.4\lib\hibernate\hibernate3.jar
spring-framework-2.0.4\lib\j2ee\jta.jar

www.javaeasytoall.com

85

Radha Technologies

Spring Frameworks

9500085257

spring-framework-2.0.4\lib\jakarta-commons\
spring-framework-2.0.4\lib\jakarta-commons\
spring-framework-2.0.4\lib\jakarta-commons\
spring-framework-2.0.4\lib\jakarta-commons\

commons-collections.jar
commons-dbcp.jar
commons-logging.jar
commons-pool.jar

2. create one table schema


use lara;
create table employee
(
id varchar(10),
name varchar(20),
age int(3),
salary int(10),
primary key (id)
);
3. Develop one pojo class with table-fields as attributes
package com.lara;
public class Employee
{
private String id;
private String name;
private int age;
private double salary;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
4. Develop one hbm file for that pojo class
<?xml version="1.0" encoding="UTF-8"?>

www.javaeasytoall.com

86

Radha Technologies

Spring Frameworks

9500085257

<!DOCTYPE hibernate-mapping PUBLIC


"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.lara.Employee" table="EMPLOYEE">
<id name="id" column="ID">
<generator class="assigned"/>
</id>
<property name="name" column="name"/>
<property name="age" column="age"/>
<property name="salary" column="salary"/>
</class>
</hibernate-mapping>

5. Develop one DAO class


package com.lara;
import
import
import
import
import

java.sql.SQLException;
org.hibernate.HibernateException;
org.hibernate.Session;
org.springframework.orm.hibernate3.HibernateCallback;
org.springframework.orm.hibernate3.HibernateTemplate;

public class EmployeeDao


{
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate()
{
return hibernateTemplate;
}

public void setHibernateTemplate(HibernateTemplate hibernateTemplate)


{
this.hibernateTemplate = hibernateTemplate;
}
public void saveOrUpdate(final Employee employee)
{
HibernateCallback callback=new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
session.saveOrUpdate(employee);
return null;
}
};
hibernateTemplate.execute(callback);
}

www.javaeasytoall.com

87

Radha Technologies

Spring Frameworks

9500085257

6. Develop one configuration file


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/lara" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean
id="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="mappingResources">
<list>
<value>com/lara/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>hibernate.dialect=org.hibernate.dialect.MySQLDialect</value>
</property>
</bean>
<bean
id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
<bean id="employeeDao" class="com.lara.EmployeeDao">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
</beans>
7. Develop one client class
package com.lara;
import
import
import
import

org.springframework.beans.factory.BeanFactory;
org.springframework.beans.factory.xml.XmlBeanFactory;
org.springframework.core.io.FileSystemResource;
org.springframework.core.io.Resource;

public class Manager


{
public static void main(String[] args)
{
Resource
resource=new
FileSystemResource("./src/com/lara/SpringHibernate.xml");
BeanFactory factory=new XmlBeanFactory(resource);
EmployeeDao employeeDao=(EmployeeDao)factory.getBean("employeeDao");
Employee employee=new Employee();
employee.setId("234");
employee.setName("Ramesh");

www.javaeasytoall.com

88

Radha Technologies

Spring Frameworks

9500085257

employee.setAge(35);
employee.setSalary(15000.00d);
employeeDao.saveOrUpdate(employee);
System.out.println("Done..........");
}
}

Web-app development in ORM Module


1. copy all relevant jar files to your`s application lib folder or update the build path with
relevant jar files.
The relevant jar files are
spring-framework-2.0.4\dist\spring.jar
spring-framework-2.0.4\lib\cglib\cglib-nodep-2.1_3.jar
spring-framework-2.0.4\lib\dom4j\dom4j-1.6.1.jar
spring-framework-2.0.4\lib\hibernate\hibernate3.jar
spring-framework-2.0.4\lib\j2ee\jta.jar
spring-framework-2.0.4\lib\jakarta-commons\ commons-collections.jar
spring-framework-2.0.4\lib\jakarta-commons\ commons-dbcp.jar
spring-framework-2.0.4\lib\jakarta-commons\ commons-logging.jar
spring-framework-2.0.4\lib\jakarta-commons\ commons-pool.jar
2. create one table schema
use lara;
create table employee
(
id varchar(10),
name varchar(20),
age int(3),
salary int(10),
primary key (id)
);
3. Develop one pojo class with table-fields as attributes
package com.lara.orm;
public class Employee
{
private String id;
private String name;
private int age;
private double salary;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {

www.javaeasytoall.com

89

Radha Technologies

Spring Frameworks

9500085257

this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
4. Develop one hbm file for that pojo class
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name=" com.lara.orm.Employee" table="EMPLOYEE">
<id name="id" column="ID">
<generator class="assigned"/>
</id>
<property name="name" column="name"/>
<property name="age" column="age"/>
<property name="salary" column="salary"/>
</class>
</hibernate-mapping>
5. Develop one DAO class
package com.lara.orm;
import
import
import
import
import
import

java.sql.SQLException;
java.util.List;
org.hibernate.HibernateException;
org.hibernate.Session;
org.springframework.orm.hibernate3.HibernateCallback;
org.springframework.orm.hibernate3.HibernateTemplate;

public class EmployeeDao


{
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate()
{
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate)
{
this.hibernateTemplate = hibernateTemplate;

www.javaeasytoall.com

90

Radha Technologies

Spring Frameworks

9500085257

}
public void saveOrUpdate(final Employee employee)
{
HibernateCallback callback=new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
session.saveOrUpdate(employee);
return null;
}
};
hibernateTemplate.execute(callback);
}
public List getList()
{
HibernateCallback callback=new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
return
session.createCriteria(com.lara.orm.Employee.class).list();
}
};
return (List)hibernateTemplate.execute(callback);
}
public List getDetailsForEdit(final String id)
{
HibernateCallback callback=new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
return
session.createCriteria(com.lara.orm.Employee.class,id).list();
}
};
return (List)hibernateTemplate.execute(callback);
}
}
6. Develop one configuration file
Webcontext\WEB-INF\applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/lara" />
<property name="username" value="root" />

www.javaeasytoall.com

91

Radha Technologies

Spring Frameworks

9500085257

<property name="password" value="" />


</bean>
<bean
id="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>com/lara/orm/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>hibernate.dialect=org.hibernate.dialect.MySQLDialect</value>
</property>
</bean>
<bean
id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<bean id="employeeDao" class="com.lara.orm.EmployeeDao">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
</beans>
7. web.xml
Webcontext\WEB-INF\ web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>orm-webapp</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>countries</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>countries</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
8. index.jsp

www.javaeasytoall.com

92

Radha Technologies

Spring Frameworks

9500085257

Webcontext\ index.jsp
<center>
<a href="add.do">Add Employee</a><br><br>
<a href="list.do">List All Employees</a>
</center>
9. countries-servlet.xml
Webcontext\WEB-INF\ countries-servlet.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD
BEAN
2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean
id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/list.do">listController</prop>
<prop key="/add.do">addController</prop>
</props>
</property>
</bean>
<bean id="listController" class="com.lara.orm.ListController"/>
<bean id="addController" class="com.lara.orm.AddController"/>
</beans>
10. AddController.jav
src\com\lara\orm\AddController.java
package com.lara.orm;
import
import
import
import
import
import
import

javax.servlet.ServletContext;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
org.springframework.context.ApplicationContext;
org.springframework.web.context.support.WebApplicationContextUtils;
org.springframework.web.servlet.ModelAndView;
org.springframework.web.servlet.mvc.Controller;

public class AddController implements Controller


{
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
ServletContext context=arg0.getSession().getServletContext();
ApplicationContext appContext=null;
appContext=WebApplicationContextUtils.getWebApplicationContext(context);
EmployeeDao
employeeDao=(EmployeeDao)appContext.getBean("employeeDao");
Employee employee=new Employee();
employee.setId("L10");
employee.setName("Stand-Alone-App");
employee.setAge(60);
employee.setSalary(2000.00d);
employeeDao.saveOrUpdate(employee);
return new ModelAndView("success.jsp");
}

www.javaeasytoall.com

93

Radha Technologies

Spring Frameworks

9500085257

}
11. ListController.java
src\com\lara\orm\AddController.java
package com.lara.orm;
import
import
import
import
import
import
import
import

java.util.List;
javax.servlet.ServletContext;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
org.springframework.context.ApplicationContext;
org.springframework.web.context.support.WebApplicationContextUtils;
org.springframework.web.servlet.ModelAndView;
org.springframework.web.servlet.mvc.Controller;

public class ListController implements Controller


{
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
ServletContext context=arg0.getSession().getServletContext();
ApplicationContext appContext=null;
appContext=WebApplicationContextUtils.getWebApplicationContext(context);
EmployeeDao
employeeDao=(EmployeeDao)appContext.getBean("employeeDao");
List<Employee> list=employeeDao.getList();
return new ModelAndView("list.jsp","list",list);
}
}
12. list.jsp
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<center>
<table border='1'>
<tr>
<td>EmpId</td>
<td>EmpName</td>
<td>EmpAge</td>
<td>EmpSalary</td>
</tr>
<core:forEach var="emp" items="${list}">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.age}</td>
<td>${emp.salary}</td>
</tr>
</core:forEach>
</table>
</center>
13. success.jsp

www.javaeasytoall.com

94

Radha Technologies

Spring Frameworks

9500085257

<center>
Employee Added Successfully
</center>
FAQS:1
1.What is Spring?
Spring is a lightweight inversion of control and aspect-oriented container framework.
2.Explain Spring?
Lightweight
Spring is lightweight when it comes to size and transparency. The basic version of spring
framework is around 1MB. And the processing overhead is also very negligible.
Inversion of control (IoC)
Loose coupling is achieved in spring using the technique Inversion of Control. The objects
give their dependencies instead of creating or looking for dependent objects.
Aspect oriented (AOP)
Spring supports Aspect oriented programming and enables cohesive development by
separating application business logic from system services.
Container
Spring contains and manages the life cycle and configuration of application objects.
Framework
Spring provides most of the intra functionality leaving rest of the coding to the developer.
3.What are the different modules in Spring framework?
The Core container module
Application context module
AOP module (Aspect Oriented Programming)
JDBC abstraction and DAO module
O/R mapping integration module (Object/Relational)
Web module
MVC framework module

4.What is the structure of Spring framework?

www.javaeasytoall.com

95

Radha Technologies

Spring Frameworks

9500085257

5.What is the Core container module?


This module is provides the fundamental functionality of the spring framework. In this
module BeanFactory is the heart of any spring-based application. The entire framework
was built on the top of this module. This module makes the Spring container.
6.What is Application context module?
The Application context module makes spring a framework. This module extends the
concept of BeanFactory, providing support for internationalization (I18N) messages,
application lifecycle events, and validation. This module also supplies many enterprise
services such JNDI access, EJB integration, remoting, and scheduling. It also provides
support to other framework.
7.What is AOP module?
The AOP module is used for developing aspects for our Spring-enabled application. Much of
the support has been provided by the AOP Alliance in order to ensure the interoperability
between Spring and other AOP frameworks. This module also introduces metadata
programming to Spring. Using Springs metadata support, we will be able to add
annotations to our source code that instruct Spring on where and how to apply aspects.
8.What is JDBC abstraction and DAO module?
Using this module we can keep up the database code clean and simple, and prevent
problems that result from a failure to close database resources. A new layer of meaningful
exceptions on top of the error messages given by several database servers
is bought in this module. In addition, this module uses Springs AOP module to provide
transaction management services for objects in a Spring application.

9.What are object/relational mapping integration module?

www.javaeasytoall.com

96

Radha Technologies

Spring Frameworks

9500085257

Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC
by providing the ORM module. Spring provide support to tie into several popular ORM
frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Springs transaction
management supports each of these ORM frameworks as well as JDBC.
10.What is web module?
This module is built on the application context module, providing a context that is
appropriate for web-based applications. This module also contains support for several weboriented tasks such as transparently handling multipart requests for file uploads and
programmatic binding of request parameters to your business objects. It also contains
integration support with Jakarta Struts.
11.What is web module?
Spring comes with a full-featured MVC framework for building web applications.
Although Spring can easily be integrated with other MVC frameworks, such as Struts,
Springs MVC framework uses IoC to provide for a clean separation of controller logic
from business objects. It also allows you to declaratively bind request parameters to
your business objects. It also can take advantage of any of Springs other services, such
as I18N messaging and validation.
12.What is a BeanFactory?
A BeanFactory is an implementation of the factory pattern that applies Inversion of
Control to separate the applications configuration and dependencies from the actual
application code.
13.What is AOP Alliance?
AOP Alliance is an open-source project whose goal is to promote adoption of AOP
and interoperability among different AOP implementations by defining a common
set of interfaces and components.
14.What is Spring configuration file?
Spring configuration file is an XML file. This file contains the classes information and
describes how these classes are configured and introduced to each other.
15.What does a simple spring application contain?
These applications are like any Java application. They are made up of several classes,
each performing a specific purpose within the application. But these classes are
configured and introduced to each other through an XML file. This XML file describes how
to configure the classes, known as the Spring configuration file.

16.What is XMLBeanFactory?

www.javaeasytoall.com

97

Radha Technologies

Spring Frameworks

9500085257

BeanFactory has many implementations in Spring. But one of the most useful one is
org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans
based on the definitions contained in an XML file. To create an XmlBeanFactory, pass a
java.io.InputStream to the constructor. The InputStream will provide the XML to the
factory. For example, the following code snippet uses a java.io.FileInputStream to
provide a bean definition XML file to XmlBeanFactory.

BeanFactory factory = new XmlBeanFactory(new


FileInputStream("beans.xml"));
To retrieve the bean from a BeanFactory, call the getBean() method by passing the
name of the bean you want to retrieve.

MyBean myBean = (MyBean) factory.getBean("myBean");


17.What are important
framework?

ApplicationContext

implementations

in

spring

ClassPathXmlApplicationContext This context loads a context definition from an


XML file located in the class path, treating context definition files as class path
resources.

FileSystemXmlApplicationContext This context loads a context definition from


an XML file in the filesystem.

XmlWebApplicationContext This context loads the context definitions from an


XML file contained within a web application.

18.Explain Bean lifecycle in Spring framework?


1. The spring container finds the beans definition from the XML file and
instantiates the bean.
2. Using the dependency injection, spring populates all of the properties as
specified in the bean definition.
3. If the bean implements the BeanNameAware interface, the factory calls
setBeanName() passing the beans ID.
4. If the bean implements the BeanFactoryAware interface, the factory calls
setBeanFactory(), passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called.

www.javaeasytoall.com

98

Radha Technologies

Spring Frameworks

9500085257

6. If an init-method is specified for the bean, it will be called.


7. Finally, if there are any BeanPostProcessors associated with the bean, their
postProcessAfterInitialization() methods will be called.
19.What is bean wiring?
Combining together beans within the Spring container is known as bean wiring or wiring.
When wiring beans, you should tell the container what beans are needed and how the
container should use dependency injection to tie them together.
20.How do add a bean in spring application?
21.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="foo" class="com.act.Foo"/>
<bean id="bar" class="com.act.Bar"/>
</beans>
In the bean tag the id attribute specifies the bean name and the class attribute specifies
the fully qualified class name.
21.What are singleton beans and how can you create prototype beans?
Beans defined in spring framework are singleton beans. There is an attribute in bean tag
named singleton if specified true then bean becomes singleton and if set to false then
the bean becomes a prototype bean. By default it is set to true. So, all the beans in
spring framework are by default singleton beans.

<beans>
<bean id="bar" class="com.act.Foo" singleton=false/>
</beans>
22.What are the important beans lifecycle methods?

www.javaeasytoall.com

99

Radha Technologies

Spring Frameworks

9500085257

There are two important bean lifecycle methods. The first one is setup which is called
when the bean is loaded in to the container. The second method is the teardown method
which is called when the bean is unloaded from the container.
23.How can you override beans default lifecycle methods?
The bean tag has two more important attributes with which you can define your own
custom initialization and destroy methods. Here I have shown a small demonstration.
Two new methods fooSetup and fooTeardown are to be added to your Foo class.

<beans>
<bean id="bar" class="com.act.Foo" init-method=fooSetup destroy=fooTeardown/>
</beans>
24.What are Inner Beans?
When wiring beans, if a bean element is embedded to a property tag directly, then that
bean is said to the Inner Bean. The drawback of this bean is that it cannot be reused
anywhere else.
25.What are the different types of bean injections?
There are two types of bean injections.
1. By setter
2. By constructor
26.What is Auto wiring?
You can wire the beans as you wish. But spring framework also does this work for you. It
can auto wire the related beans together. All you have to do is just set the autowire
attribute of bean tag to an autowire type.

<beans>
<bean id="bar" class="com.act.Foo" Autowire=autowire type/>
</beans>
27.What are different types of Autowire types?
There are four different types by which autowiring can be done.
o

byName

www.javaeasytoall.com

100

Radha Technologies

Spring Frameworks
o

byType

constructor

autodetect

9500085257

28.What are the different types of events related to Listeners?


There are a lot of events related to ApplicationContext of spring framework. All the
events are subclasses of org.springframework.context.Application-Event. They are

ContextClosedEvent This is fired when the context is closed.


ContextRefreshedEvent This is fired when the context is initialized or refreshed.

RequestHandledEvent This is fired when the web context handles any request.

29.What is an Aspect?
An aspect is the cross-cutting functionality that you are implementing. It is the aspect of
your application you are modularizing. An example of an aspect is logging. Logging is
something that is required throughout an application. However, because applications
tend to be broken down into layers based on functionality, reusing a logging module
through inheritance does not make sense. However, you can create a logging aspect and
apply it throughout your application using AOP.
30.What is a Jointpoint?
A joinpoint is a point in the execution of the application where an aspect can be plugged
in. This point could be a method being called, an exception being thrown, or even a field
being modified. These are the points where your aspects code can be inserted into the
normal flow of your application to add new behavior.
31.What is an Advice?
Advice is the implementation of an aspect. It is something like telling your application of
a new behavior. Generally, and advice is inserted into an application at joinpoints.
32.What is a Pointcut?
A pointcut is something that defines at what joinpoints an advice should be applied.
Advices can be applied at any joinpoint that is supported by the AOP framework. These
Pointcuts allow you to specify where the advice can be applied.
33.What is an Introduction in AOP?
An introduction allows the user to add new methods or attributes to an existing class.
This can then be introduced to an existing class without having to change the structure
of the class, but give them the new behavior and state.
34.What is a Target?

www.javaeasytoall.com

101

Radha Technologies

Spring Frameworks

9500085257

A target is the class that is being advised. The class can be a third party class or your
own class to which you want to add your own custom behavior. By using the concepts of
AOP, the target class is free to center on its major concern, unaware to any advice that
is being applied.

35.What is a Proxy?
A proxy is an object that is created after applying advice to a target object. When you
think of client objects the target object and the proxy object are the same.
36.What is meant by Weaving?
The process of applying aspects to a target object to create a new proxy object is called
as Weaving. The aspects are woven into the target object at the specified joinpoints.
37.What are the different points where weaving can be applied?

Compile Time

Classload Time

Runtime

38.What are the different advice types in spring?

Around : Intercepts the calls to the target method

Before : This is called before the target method is invoked

After : This is called after the target method is returned

Throws : This is called when the target method throws and exception

Around : org.aopalliance.intercept.MethodInterceptor

Before : org.springframework.aop.BeforeAdvice

After : org.springframework.aop.AfterReturningAdvice

Throws : org.springframework.aop.ThrowsAdvice

39.What are the different types of AutoProxying?

BeanNameAutoProxyCreator

DefaultAdvisorAutoProxyCreator

www.javaeasytoall.com

102

Radha Technologies

Spring Frameworks

9500085257

Metadata autoproxying

40.What is the Exception class related to all the exceptions that are thrown in
spring applications?
DataAccessException - org.springframework.dao.DataAccessException

41. What kind of exceptions those spring DAO classes throw?


The springs DAO class does not throw any technology related exceptions such as
SQLException. They throw exceptions which are subclasses of DataAccessException.
42.What is DataAccessException?
DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is
not forced to handle these kinds of exceptions.

43.How can you configure a bean to get DataSource from JNDI?


44.
<bean
id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/myDatasource</value>
</property>
</bean>
44.How can you create a DataSource connection pool?

<bean

id="dataSource"

</bean>

class="org.apache.commons.dbcp.BasicDataSource">
<property
name="driver">
<value>${db.driver}</value>
</property>
<property
name="url">
<value>${db.url}</value>
</property>
<property
name="username">
<value>${db.username}</value>
</property>
<property
name="password">
<value>${db.password}</value>
</property>

45.How JDBC can be used more efficiently in spring framework?

www.javaeasytoall.com

103

Radha Technologies

Spring Frameworks

9500085257

JDBC can be used more efficiently with the help of a template class provided by spring
framework called as JdbcTemplate.
46.How JdbcTemplate can be used?
With use of Spring JDBC framework the burden of resource management and error
handling is reduced a lot. So it leaves developers to write the statements and queries to
get the data to and from the database.

JdbcTemplate template = new JdbcTemplate(myDataSource);


A simple DAO class looks like this.
public

class

StudentDaoJdbc
private

implements
JdbcTemplate

public
void
setJdbcTemplate(JdbcTemplate
this.jdbcTemplate
=
}
more..

StudentDao
{
jdbcTemplate;
jdbcTemplate)
{
jdbcTemplate;

The configuration is shown below.


<bean

id="jdbcTemplate"

<ref
</property>
</bean>
<bean
<property
<ref
</property>
</bean>
<bean

class="org.springframework.jdbc.core.JdbcTemplate">
<property
name="dataSource">
bean="dataSource"/>

id="studentDao"

class="StudentDaoJdbc">
name="jdbcTemplate">
bean="jdbcTemplate"/>

id="courseDao"
<property

class="CourseDaoJdbc">
name="jdbcTemplate">
bean="jdbcTemplate"/>

<ref
</property>
</bean>

47.How do you write data to backend in spring using JdbcTemplate?


The JdbcTemplate uses several of these callbacks when writing data to the database. The
usefulness you will find in each of these interfaces will vary. There are two simple
interfaces. One is PreparedStatementCreator and the other interface is
BatchPreparedStatementSetter.

www.javaeasytoall.com

104

Radha Technologies

Spring Frameworks

9500085257

48.Explain about PreparedStatementCreator?


PreparedStatementCreator is one of the most common used interfaces for writing data
to database. The interface has one method createPreparedStatement().

PreparedStatement
throws SQLException;

createPreparedStatement(Connection

conn)

When this interface is implemented, we should create and return a PreparedStatement


from the Connection argument, and the exception handling is automatically taken care
off. When this interface is implemented, another interface SqlProvider is also
implemented which has a method called getSql() which is used to provide sql strings to
JdbcTemplate.
49.Explain about BatchPreparedStatementSetter?
If the user what to update more than one row at a shot then he can go for
BatchPreparedStatementSetter. This interface provides two methods

setValues(PreparedStatement

ps,

int

i)

throws

SQLException;

int getBatchSize();

The getBatchSize() tells the JdbcTemplate class how many statements to create. And
this also determines how many times setValues() will be called.
50.Explain about RowCallbackHandler and why it is used?
In order to navigate through the records we generally go for ResultSet. But spring
provides an interface that handles this entire burden and leaves the user to decide what
to do with each row. The interface provided by spring is RowCallbackHandler. There is
a method processRow() which needs to be implemented so that it is applicable for each
and everyrow.
void processRow(java.sql.ResultSet rs);

FAQS:2
1. What is IOC (or Dependency Injection)?
The basic concept of the Inversion of Control pattern (also known as dependency injection)
is that you do not create your objects but describe how they should be created. You don't

www.javaeasytoall.com

105

Radha Technologies

Spring Frameworks

9500085257

directly connect your components and services together in code but describe which services
are needed by which components in a configuration file. A container (in the case of the
Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external
entity that coordinates each object in the system. That is, dependencies are injected into
objects. So, IoC means an inversion of responsibility with regard to how an object obtains
references to collaborating objects.
2 What are the different types of IOC (dependency injection) ?
There are three types of dependency injection:
Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided
as constructor parameters.
Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans
properties (ex: setter methods).
Interface Injection (e.g. Avalon): Injection is done through an interface.
Note: Spring supports only Constructor and Setter Injection
3 What are the benefits of IOC (Dependency Injection)?
Benefits of IOC (Dependency Injection) are as follows:
Minimizes the amount of code in your application. With IOC containers you do not
care about how services are created and how you get references to the ones you
need. You can also easily add additional services by adding a new constructor or a
setter method with little or no extra configuration.
Make your application more testable by not requiring any singletons or JNDI lookup
mechanisms in your unit test cases. IOC containers make unit testing and switching
implementations very easy by manually allowing you to inject your own objects into
the object under test.
Loose coupling is promoted with minimal effort and least intrusive mechanism. The
factory design pattern is more intrusive because components or services need to be
requested explicitly whereas in IOC the dependency is injected into requesting piece
of code. Also some containers promote the design to interfaces not to
implementations design concept by encouraging managed objects to implement a
well-defined service interface of your own.
IOC containers support eager instantiation and lazy loading of services. Containers
also provide support for instantiation of managed objects, cyclical dependencies, life
cycles management, and dependency resolution between managed objects etc.
4 What is Spring ?
Spring is an open source framework created to address the complexity of enterprise
application development
. One of the chief advantages of the Spring framework is its layered architecture, which
allows you to be selective about which of its components you use while also providing a
cohesive framework for J2EE application development.
5.What are the types of Dependency Injection Spring supports?>
Setter Injection:
Setter-based DI is realized by calling setter methods on your beans after invoking a
no-argument constructor or no-argument static factory method to instantiate your
bean.

www.javaeasytoall.com

106

Radha Technologies

Spring Frameworks

9500085257

Constructor Injection:
Constructor-based DI is realized by invoking a constructor with a number of
arguments, each representing a collaborator.
6.What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory
holds Bean Definitions of multiple beans within itself and then instantiates the bean
whenever asked for by clients.
BeanFactory is able to create associations between collaborating objects as they are
instantiated. This removes the burden of configuration from bean itself and the beans
client.
BeanFactory also takes part in the life cycle of a bean, making calls to custom
initialization and destruction methods.
7.What is Application Context?
A bean factory is fine to simple applications, but to take advantage of the full power of the
Spring framework, you may want to move up to Springs more advanced container, the
application context. On the surface, an application context is same as a bean factory.Both
load bean definitions, wire beans together, and dispense beans upon request. But it also
provides:
A means for resolving text messages, including support for internationalization.
A generic way to load file resources.
Events to beans that are registered as listeners.
8.What is the difference between Bean Factory and Application Context ?
On the surface, an application context is same as a bean factory. But application context
offers much more..
Application contexts provide a means for resolving text messages, including support
for i18n of those messages.
Application contexts provide a generic way to load file resources, such as images.
Application contexts can publish events to beans that are registered as listeners.
Certain operations on the container or beans in the container, which have to be
handled in a programmatic fashion with a bean factory, can be handled declaratively
in an application context.
ResourceLoader support: Springs Resource interface us a flexible generic abstraction
for handling low-level resources. An application context itself is a ResourceLoader,
Hence provides an application with access to deployment-specific Resource instances.
MessageSource support: The application context implements MessageSource, an
interface used to obtain localized messages, with the actual implementation being
pluggable
9.What are the common implementations of the Application Context ?
The three commonly used implementation of 'Application Context' are
ClassPathXmlApplicationContext : It Loads context definition from an XML file
located in the classpath, treating context definitions as classpath resources. The
application context is loaded from the application's classpath by using the code .
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
FileSystemXmlApplicationContext : It loads context definition from an XML file in
the filesystem. The application context is loaded from the file system by using the

www.javaeasytoall.com

107

Radha Technologies

Spring Frameworks

9500085257

code
.
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
XmlWebApplicationContext : It loads context definition from an XML file contained
within a web application.
10.ow is a typical spring implementation look like ?
For a typical Spring Application we need the following files:
An interface that defines the functions.
An Implementation that contains properties, its setter and getter methods, functions
etc.,
Spring AOP (Aspect Oriented Programming)
A XML file called Spring configuration file.
Client program that uses the function.

11. What is the typical Bean life cycle in Spring Bean Factory Container ?
Bean life cycle in Spring Bean Factory Container is as follows:
The spring container finds the beans definition from the XML file and instantiates the
bean.
Using the dependency injection, spring populates all of the properties as specified in
the bean definition
If the bean implements the BeanNameAware interface, the factory calls
setBeanName() passing the beans ID.
If the bean implements the BeanFactoryAware interface, the factory calls
setBeanFactory(), passing an instance of itself.
If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called.
If an init-method is specified for the bean, it will be called.
Finally, if there are any BeanPostProcessors associated with the bean, their
postProcessAfterInitialization() methods will be called.
12.What do you mean by Bean wiring ?
The act of creating associations between application components (beans) within the Spring
container is reffered to as Bean wiring.
13.What do you mean by Auto Wiring?
The Spring container is able to autowire relationships between collaborating beans. This
means that it is possible to automatically let Spring resolve collaborators (other beans) for
your bean by inspecting the contents of the BeanFactory. The autowiring functionality has
five modes.
no
byName
byType
constructor
autodirect

www.javaeasytoall.com

108

Radha Technologies

Spring Frameworks

9500085257

14.What is DelegatingVariableResolver?
Spring provides a custom JavaServer Faces VariableResolver
implementation that extends the standard Java Server Faces managed beans mechanism
which lets you use JSF and Spring together. This variable resolver is called as
DelegatingVariableResolver
15 How to integrate Java Server Faces (JSF) with Spring?
JSF and Spring do share some of the same features, most noticeably in the area of IOC
services. By declaring JSF managed-beans in the faces-config.xml configuration file, you
allow the FacesServlet to instantiate that bean at startup. Your JSF pages have access to
these beans and all of their properties.We can integrate JSF and Spring in two ways:

DelegatingVariableResolver: Spring comes with a JSF variable resolver that lets you
use JSF and Spring together.

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"

"http://www.springframework.org/dtd/spring-beans.dtd">

<faces-config>

<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>

</faces-config>
The DelegatingVariableResolver will first delegate value lookups to the default
resolver of the underlying JSF implementation, and then to Spring's 'business
context' WebApplicationContext. This allows one to easily inject dependencies into
one's JSF-managed beans.
FacesContextUtils:custom VariableResolver works well when mapping one's properties
to beans in faces-config.xml, but at times one may need to grab a bean explicitly. The
FacesContextUtils class makes this easy. It is similar to WebApplicationContextUtils,
except that it takes a FacesContext parameter rather than a ServletContext parameter.

ApplicationContext

ctx

FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());

www.javaeasytoall.com

109

Radha Technologies

Spring Frameworks

9500085257

16.What is Java Server Faces (JSF) - Spring integration mechanism?


Spring provides a custom JavaServer Faces VariableResolver implementation that extends
the standard JavaServer Faces managed beans mechanism. When asked to resolve a
variable name, the following algorithm is performed:
Does a bean with the specified name already exist in some scope (request, session,
application)? If so, return it
Is there a standard JavaServer Faces managed bean definition for this variable
name? If so, invoke it in the usual way, and return the bean that was created.
Is there configuration information for this variable name in the Spring
WebApplicationContext for this application? If so, use it to create and configure an
instance, and return that instance to the caller.
If there is no managed bean or Spring definition for this variable name, return null
instead.
BeanFactory also takes part in the life cycle of a bean, making calls to custom
initialization and destruction methods.
As a result of this algorithm, you can transparently use either JavaServer Faces or
Spring facilities to create beans on demand.

17What is Significance of JSF- Spring integration ?


Spring - JSF integration is useful when an event handler wishes to explicitly invoke the bean
factory to create beans on demand, such as a bean that encapsulates the business logic to
be performed when a submit button is pressed.
18How to integrate your Struts application with Spring?
To integrate your Struts application with Spring, we have two options:
Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin,
and set their dependencies in a Spring context file.
Subclass Spring's ActionSupport classes and grab your Spring-managed beans
explicitly using a getWebApplicationContext() method.
19What are ORMs Spring supports ?
Spring supports the following ORMs :
Hibernate
iBatis
JPA (Java
Persistence API)
TopLink
JDO (Java Data Objects
)
OJB
20 What are the ways to access Hibernate using Spring ?
There are two approaches to Springs Hibernate integration:
Inversion of Control with a HibernateTemplate and Callback

www.javaeasytoall.com

110

Radha Technologies

Spring Frameworks

9500085257

Extending HibernateDaoSupport and Applying an AOP Interceptor


21 How to integrate Spring and Hibernate using HibernateDaoSupport?
Spring
and
Hibernate
can
integrate
using
Springs
LocalSessionFactory. The integration process is of 3 steps.

SessionFactory

called

Configure the Hibernate SessionFactory


Extend your DAO Implementation from HibernateDaoSupport
Wire in Transaction Support with AOP
22 What are Bean scopes in Spring Framework ?
The Spring Framework supports exactly five scopes (of which three are available only if
you are using a web-aware ApplicationContext). The scopes supported are listed below:
Scope

Description

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 webaware 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.

23What is AOP?
Aspect-oriented programming, or AOP, is a programming technique that allows
programmers to modularize crosscutting concerns, or behavior that cuts across the typical
divisions of responsibility, such as logging and transaction management. The core construct
of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable
modules.
24How the AOP used in Spring?
AOP is used in the Spring Framework: To provide declarative enterprise services,
especially as a replacement for EJB declarative services. The most important such service is
declarative transaction management, which builds on the Spring Framework's transaction
abstraction.To allow users to implement custom aspects, complementing their use of OOP
with AOP.

25What do you mean by Aspect ?

A modularization of a concern that cuts across multiple objects. Transaction management


is a good example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are

www.javaeasytoall.com

111

Radha Technologies

Spring Frameworks

9500085257

implemented using regular classes (the schema-based approach) or regular classes


annotated with the @Aspect annotation (@AspectJ style).
26What do you mean by JointPoint?
A point during the execution of a program, such as the execution of a method or the
handling of an exception. In Spring AOP, a join point always represents a method execution.

27What do you mean by Advice?


Action taken by an aspect at a particular join point. Different types of advice include
"around," "before" and "after" advice. Many AOP frameworks, including Spring, model an
advice as an interceptor, maintaining a chain of interceptors "around" the join point.
28What are the types of Advice?
Types of advice:
Before advice: Advice that executes before a join point, but which does not have the
ability to prevent execution flow proceeding to the join point (unless it throws an
exception).
After returning advice: Advice to be executed after a join point completes normally:
for example, if a method returns without throwing an exception.
After throwing advice: Advice to be executed if a method exits by throwing an
exception.
After (finally) advice: Advice to be executed regardless of the means by which a join
point exits (normal or exceptional return).
Around advice: Advice that surrounds a join point such as a method invocation. This
is the most powerful kind of advice. Around advice can perform custom behavior
before and after the method invocation. It is also responsible for choosing whether to
proceed to the join point or to shortcut the advised method execution by returning
its own return value or throwing an exception
29What are the types of the transaction management Spring supports ?
Spring Framework supports:
Programmatic transaction management.
Declarative transaction management.
30What are the benefits of the Spring Framework transaction management ?
The Spring Framework provides a consistent abstraction for transaction management that
delivers the following benefits:
Provides a consistent programming model across different transaction APIs such as
JTA, JDBC, Hibernate, JPA, and JDO.
Supports declarative transaction management.
Provides a simpler API for programmatic transaction management than a number of
complex transaction APIs such as JTA.
Integrates very well with Spring's various data access
abstractions.
31 Why most users of the Spring Framework choose declarative transaction
management ?

www.javaeasytoall.com

112

Radha Technologies

Spring Frameworks

9500085257

Most users of the Spring Framework choose declarative transaction


management because it is the option with the least impact on application code, and hence is
most consistent with the ideals of a non-invasive lightweight container.
32 Explain the similarities and differences between EJB CMT and the Spring
Framework's declarative transaction management ?
The basic approach is similar: it is possible to specify transaction
behavior
(or
lack
of
it)
down
to
individual
method
level.
It
is
possible to make a setRollbackOnly() call within a transaction context if necessary. The
differences are:
Unlike EJB CMT, which is tied to JTA, the Spring Frameworks
declarative
transaction
management
works
in
any
environment? It can work with JDBC, JDO, Hibernate or other
transactions under the covers, with configuration changes only.
The Spring Framework enables declarative transaction management to be applied to
any class, not merely special classes such as EJBs.
The Spring Framework offers declarative rollback rules: this is a feature with no EJB
equivalent. Both programmatic and declarative support for rollback rules is provided.
The Spring Framework gives you an opportunity to customize transactional behavior,
using AOP. With EJB CMT, you have no way to influence the container's transaction
management other than setRollbackOnly().
The Spring Framework does not support propagation of transaction contexts across
remote calls, as do high-end application servers.
33 When to use programmatic and declarative transaction management ?

Programmatic transaction management is usually a good idea only if


you
have
a
small
number
of
transactional
operations.
On the other hand, if your application has numerous transactional operations, declarative
transaction management is usually worthwhile. It keeps transaction management out of
business logic, and is not difficult to configure.
34 Explain about the Spring DAO support?
The Data Access Object (DAO) support in Spring is aimed at making it
easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way.
This allows one to switch between the persistence technologies fairly easily and it also
allows one to code without worrying about catching exceptions that are specific to each
technology.
35 What are the exceptions thrown by the Spring DAO classes?
Spring DAO classes throw exceptions which are subclasses of
DataAccessException(org.springframework.dao.DataAccessException).Spring
provides
a
convenient translation from technology-specific exceptions like SQLException to its own
exception class hierarchy with the DataAccessException as the root exception. These
exceptions wrap the original exception.
36 What is SQLExceptionTranslator ?
SQLExceptionTranslator, is an interface to be implemented by classes
that can translate between SQLExceptions and Spring's own data-access-strategy-agnostic
org.springframework.dao.DataAccessException.
37 What is Spring's JdbcTemplate ?

www.javaeasytoall.com

113

Radha Technologies

Spring Frameworks

9500085257

Spring's JdbcTemplate is central class to interact with a database


through JDBC. JdbcTemplate provides many convenience methods for doing things such as
converting database data into primitives or objects, executing prepared and callable
statements, and providing custom database error handling.

JdbcTemplate template = new JdbcTemplate(myDataSource);

38 What is PreparedStatementCreator ?
PreparedStatementCreator:

Is one of the most common used interfaces for writing data to database.
Has one method createPreparedStatement(Connection)
Responsible for creating a PreparedStatement.
Does not need to handle SQLExceptions.

39 What is SQLProvider ?
SQLProvider:
Has one method getSql()
Typically implemented by PreparedStatementCreator implementers.
Useful for debugging.
40 What is RowCallbackHandler ?
The RowCallbackHandler interface extracts values from each row of a ResultSet.
Has one method processRow(ResultSet)
Called for each row in ResultSet.
Typically stateful.

www.javaeasytoall.com

114

Radha Technologies

Spring Frameworks

9500085257

41 What are the differences between EJB and Spring ?


Spring and EJB feature comparison.
Feature
Transaction
management

EJB

Spring

Must
use
a
JTA
transaction manager.
Supports
transactions
that
span
remote
method calls.

Declarative
transaction
support

Can define transactions


declaratively
through
the
deployment
descriptor.
Can define transaction
behavior per method or
per class by using the
wildcard character *.
Cannot
declaratively
define rollback behavior
this must be done
programmatically.

Persistence

Declarative

Supports
multiple
transaction
environments
through
its
PlatformTransactionManager
interface, including JTA, Hibernate,
JDO, and JDBC.
Does
not
natively
support
distributed transactionsit must
be used with a JTA transaction
manager.
Can
define
transactions
declaratively through the Spring
configuration file or through class
metadata.
Can define which methods to apply
transaction behavior explicitly or
by using regular expressions.
Can declaratively define rollback
behavior per method and per
exception type.

Supports programmatic bean- Provides a framework for integrating with


managed
persistence
and several persistence technologies, including
declarative container managed JDBC, Hibernate, JDO, and iBATIS.
persistence.
Supports

www.javaeasytoall.com

declarative

115

No security implementation out-of-

Radha Technologies

Spring Frameworks
security

9500085257
security through users
and
roles.
The
management
and
implementation of users
and roles is container
specific.
Declarative security is
configured
in
the
deployment descriptor.

Distributed
computing

the box.
Acegi, an open source security
framework built on top of Spring,
provides
declarative
security
through the Spring configuration
file or class metadata.

Provides
container-managed Provides proxying for remote calls via
remote method calls.
RMI, JAX-RPC, and web services.

www.javaeasytoall.com

116

Radha Technologies

Anda mungkin juga menyukai