Spring
Spring
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.
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
www.javaeasytoall.com
Radha Technologies
Spring Frameworks
9500085257
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.
UI
Tier
Web browser
Presen
tation
Tier
HTML/JSP
Busi
ness
Tier
J2EE
Integ
ratio
n
Tier
JDBC/DAO
Data
Base
Tier
EIS
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
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;
}
}
www.javaeasytoall.com
BEAN
2.0//EN"
Radha Technologies
Spring Frameworks
9500085257
<value>Cricket</value>
</list>
</property>
<property name="mails">
<list>
<value>[email protected]</value>
<value>[email protected]</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.
*/
}
Another Simple Core Development in Ioc Module
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
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>[email protected]</value>
<value>[email protected]</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>
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.
Example:-1
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="[email protected]"/>
<constructor-arg index="2" type="java.lang.String" value="india"/>
</bean>
</beans>
www.javaeasytoall.com
14
Radha Technologies
Spring Frameworks
9500085257
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="[email protected]"/>
<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>
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
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="[email protected]"/>
<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
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;
}
}
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.
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;
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
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"
www.javaeasytoall.com
25
Radha Technologies
Spring Frameworks
9500085257
XmlBeanFactory(new
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
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
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
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
java.lang.reflect.Method;
org.aopalliance.intercept.MethodInvocation;
org.springframework.aop.IntroductionInterceptor;
org.springframework.aop.AfterReturningAdvice;
org.springframework.aop.ThrowsAdvice;
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;
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
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
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
command,
9. success.jsp
Spring-app1\WebContent\success.jsp
www.javaeasytoall.com
41
Radha Technologies
Spring Frameworks
9500085257
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
"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;
www.javaeasytoall.com
44
Radha Technologies
Spring Frameworks
9500085257
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
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;
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
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;
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
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
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;
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;
}
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.
www.javaeasytoall.com
82
Radha Technologies
Spring Frameworks
{
9500085257
java.sql.ResultSet;
java.sql.SQLException;
org.springframework.dao.DataAccessException;
org.springframework.jdbc.core.ResultSetExtractor;
com.lara.entity.Book;
www.javaeasytoall.com
83
Radha Technologies
Spring Frameworks
{
9500085257
}
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
{
java.util.List;
javax.sql.DataSource;
org.springframework.jdbc.core.JdbcTemplate;
com.lara.db.dao.BookDAO;
com.lara.db.mapper.BookRowMapper;
www.javaeasytoall.com
84
Radha Technologies
Spring Frameworks
9500085257
java.util.List;
org.springframework.jdbc.datasource.DriverManagerDataSource;
com.lara.entity.Book;
com.lara.entity.BookDAOImpl;
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
www.javaeasytoall.com
86
Radha Technologies
Spring Frameworks
9500085257
java.sql.SQLException;
org.hibernate.HibernateException;
org.hibernate.Session;
org.springframework.orm.hibernate3.HibernateCallback;
org.springframework.orm.hibernate3.HibernateTemplate;
www.javaeasytoall.com
87
Radha Technologies
Spring Frameworks
9500085257
org.springframework.beans.factory.BeanFactory;
org.springframework.beans.factory.xml.XmlBeanFactory;
org.springframework.core.io.FileSystemResource;
org.springframework.core.io.Resource;
www.javaeasytoall.com
88
Radha Technologies
Spring Frameworks
9500085257
employee.setAge(35);
employee.setSalary(15000.00d);
employeeDao.saveOrUpdate(employee);
System.out.println("Done..........");
}
}
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;
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
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;
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;
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
www.javaeasytoall.com
95
Radha Technologies
Spring Frameworks
9500085257
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.
ApplicationContext
implementations
in
spring
www.javaeasytoall.com
98
Radha Technologies
Spring Frameworks
9500085257
<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
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
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
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
<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>
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.
class
StudentDaoJdbc
private
implements
JdbcTemplate
public
void
setJdbcTemplate(JdbcTemplate
this.jdbcTemplate
=
}
more..
StudentDao
{
jdbcTemplate;
jdbcTemplate)
{
jdbcTemplate;
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>
www.javaeasytoall.com
104
Radha Technologies
Spring Frameworks
9500085257
PreparedStatement
throws SQLException;
createPreparedStatement(Connection
conn)
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.
"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
www.javaeasytoall.com
110
Radha Technologies
Spring Frameworks
9500085257
SessionFactory
called
Description
singleton
Scopes a single bean definition to a single object instance per Spring IoC
container.
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
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.
www.javaeasytoall.com
111
Radha Technologies
Spring Frameworks
9500085257
www.javaeasytoall.com
112
Radha Technologies
Spring Frameworks
9500085257
www.javaeasytoall.com
113
Radha Technologies
Spring Frameworks
9500085257
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
EJB
Spring
Must
use
a
JTA
transaction manager.
Supports
transactions
that
span
remote
method calls.
Declarative
transaction
support
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.
www.javaeasytoall.com
declarative
115
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