Spring FrameWork
Spring FrameWork
com
Spring FrameWork
Agenda :
▪ Spring Framework Introduction
▪ Features of Spring framework
▪ Spring Architecture
▪ Modules of Spring framework
1. Core Module
2. DAO Module
3. ORM Module
4. JEE/Application Context Module
5. AOP Module
6. Web MVC Module
▪ Terminology
Framework:
Spring:
1
Karrasankar158@gmail.com
Introduction:
1. Spring framework is developed to simplify the development
of enterprise applications in Java technologies.
2. It is an open source framework begin developed by
Interface21.
3. The Spring provides light weight IoC Container and AOP
framework.
4. It provides support for JPA, Hibernate, Web services,
Schedulers, Ajax, Struts, JSF and many other frameworks.
5. The Spring MVC components can be used to develop MVC
based web applications.
6. The Spring 3.0 framework has been released with major
enhancements and support for the Java 5 [JDK1.5].
7. Spring can be used to configure declarative transaction
management, remote access to your logic using RMI or web
services, mailing facilities and various options in persisting
your data to a database.
8. Spring framework can be used in modular fashion, it allows
to use in parts and leave the other components which is not
required by the application.
2
Karrasankar158@gmail.com
3
Karrasankar158@gmail.com
4
Karrasankar158@gmail.com
Spring Architecture:
Spring is well-organized architecture consisting of
seven modules.
Modules in the Spring framework are:
5
Karrasankar158@gmail.com
2. DAO
3. ORM
4. JEE/Context
5. Web
6. MVC
7. AOP
Core Module:
1. It is base module for all modules.
2. Provides BeanFactory container which makes Spring as a
container
6
Karrasankar158@gmail.com
7
Karrasankar158@gmail.com
8
Karrasankar158@gmail.com
9
Karrasankar158@gmail.com
Terminology :
Spring is a open source, light weight, loosely
coupled, aspect oriented & dependency injection based
framework software which can be used to develop any
kind of java/j2ee application.
Lightweight:
11
Karrasankar158@gmail.com
▪ ApplicationContext container
6. abstract attribute
7. spring container based on FileSystemResource
8. purpose of getBean() method
9. lazy-init attribute
10. What is Wiring
▪ auto-wire attribute
▪ auto-wire="byName"
▪ auto-wire="byType"
12
Karrasankar158@gmail.com
parent attribute
▪
▪ local attribute
method
17. Bean Scopes and LifeCycle
▪ Initialization
▪ Destruction
13
Karrasankar158@gmail.com
Spring Containers :
Core container or IOC container or BeanFactroy container
1. Its an implementation class of an interface BeanFactory
2. It supports lazy loading.
▪ It means container will not create objects of configured
15
Karrasankar158@gmail.com
16
Karrasankar158@gmail.com
15. org.springframework.context.support.XmlWebAppl
icationContext: this class activates application context
container by locating spring configuration file in deployment
directory structure of web application by default in WEB-INF
folder.
Ex:
16. XmlWebApplicationContext ctx =
17. new
XmlWebApplicationContext("spring.cfg.xml");
18. In real time applications we can find regularly working
with Application Context container rather than working with
Bean Factory container.
19. Application context container can perform all modes of
dependency injection like bean factory container.
20. Application context container performs pre
instantiation on all singleton scoped on spring bean classes
of spring configuration file at the moment of application
context container gets activated.
21. Pre-instantiation means creating spring bean class
objects immediately after the application context container
activation.
22. BeanFactory cannot perform this pre instantiation on
spring bean classes.
23. when we call factory.getBean(_) then bean factory
container immediately creates the object and uses the same
for further requests on same id-value.
24. When we call ctx.getBean(_) then application context
container gives access to bean id related spring bean class
object which is created at pre-instantiation process.
25. Application context container can perform pre-
instantiation only on singleton scoped spring bean classes
that are configured in spring configuration file.
18
Karrasankar158@gmail.com
19
Karrasankar158@gmail.com
Example 1:
HelloService.java
package com.core;
xsi:schemaLocation="http://www.springframework.org/
schema/beans
http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd">
<bean id="helloService1"
class="com.core.HelloService"/>
<bean id="helloService2"
class="com.core.HelloService">
20
Karrasankar158@gmail.com
<constructor-arg>
<value>hello from configuration</value>
</constructor-arg>
</bean>
</beans>
HelloServiceTestCase.java
package com.core;
import
org.springframework.beans.factory.BeanFactory;
import
org.springframework.beans.factory.xml.XmlBeanFactor
y;
import
org.springframework.core.io.FileSystemResource;
BeanFactory beans=
new XmlBeanFactory(new
FileSystemResource("mybeans.xml"));
HelloService
hello1=(HelloService)beans.getBean("helloService1")
;
System.out.println(hello1.getMessage());
HelloService
hello2=(HelloService)beans.getBean("helloService2")
;
System.out.println(hello2.getMessage());
}//main
}//class
21
Karrasankar158@gmail.com
output :
msg from default Constructor
hello from configuration
22
Karrasankar158@gmail.com
}
applicationContext.xml
<bean id="emp" class="com.core.Employee">
<constructor-arg type="java.lang.String"
index="0">
<value type="java.lang.String">25</value>
</constructor-arg>
<constructor-arg type="java.lang.String"
index="1">
<value type="java.lang.String">Ashok</value>
</constructor-arg>
<constructor-arg type="java.lang.String"
index="2">
<value type="java.lang.String">HYD</value>
</constructor-arg>
</bean>
23
Karrasankar158@gmail.com
Requirement :
create a spring bean address with 3 properties and establish the
dependencies and ask the spring container to create the object
spring bean :In spring, java beans are considered as spring-
beans.
Address.java
package com.core;
24
Karrasankar158@gmail.com
}//class
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
25
Karrasankar158@gmail.com
xsi:schemaLocation="http://www.springframework.org/
schema/beans
http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd">
<property name="street">
<value type="java.lang.String">Apet</value>
</property>
<property name="city">
<value type="java.lang.String">HYD</value>
</property>
<property name="state">
<value type="java.lang.String">IND</value>
</property>
</bean>
</beans>
26
Karrasankar158@gmail.com
import
org.springframework.beans.factory.BeanFactory;
import
org.springframework.beans.factory.xml.XmlBeanFactor
y;
import
org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
27
Karrasankar158@gmail.com
Object o=container.getBean("addr");
Address a=(Address)o;
System.out.println("Street : "+a.getStreet());
System.out.println("City : "+a.getCity());
System.out.println("State : "+a.getState());
}//main
}
Output :
container :
org.springframework.beans.factory.xml.XmlBeanFactor
y@64883c:
defining beans [addr]; root of factory
hierarchy
Street : Apet
City : HYD
State : IND
28
Karrasankar158@gmail.com
abstract attribute :
import
org.springframework.beans.factory.BeanFactory;
import
org.springframework.beans.factory.xml.XmlBeanFactor
y;
import
org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
BeanFactory container=new
XmlBeanFactory(resource);
System.out.println("container : "+container);
}//main
30
Karrasankar158@gmail.com
implementation of
ApplicationContext.(org.springframework.context.support)
Requirement :
Implement dependency between an address object and
employee object
Address.java
package com.core;
32
Karrasankar158@gmail.com
}//class
Employee.java
package com.core;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Employee spring bean dependent on Address spring bean.
We have to configure the above 2 spring beans into
spring configuration file.
applicationContext.xml
<bean id="emp" class="com.core.Employee" >
<property name="no" value="1"/>
<property name="name" value="Ashok"/>
<property name="address">
<ref bean="addr"/>
</property>
</bean>
34
Karrasankar158@gmail.com
What is Wiring :
35
Karrasankar158@gmail.com
36
Karrasankar158@gmail.com
Requirement :
In the spring based project we always use multiple spring
bean configuration files because of the maintanance of the
project becomes easy
configure Employee bean into applicationContext.xml and
Address bean into customerContext.xml
37
Karrasankar158@gmail.com
Approach 1:
ApplicationContext container=new
ClassPathXmlApplicationContext(
new
String[]{"com/core/applicationContext.xml",
"com/core/customerContext.xml"});
container.getBean("addr");
container.getBean("emp");
Approach 2:
ApplicationContext container=new
ClassPathXmlApplicationContext(
"com/core/applicationContext.xml",
"com/core/customerContext.xml");
container.getBean("addr");
container.getBean("emp");
In the above configuration we are hard coding the
configuration file names instead of hard coding we
use wild character search
ApplicationContext container=
new
ClassPathXmlApplicationContext("com/core/*.xml");
//not working
BeanFactory
container.getBean("addr");
container.getBean("emp");
38
Karrasankar158@gmail.com
applicationContext.xml
<beans>
<import resource="customerContext.xml"/>
</beans>
ref tag :
ref tag takes multiple attributes they are : bean,
parent, local.
<ref bean="addr"/>
When we specified <ref bean="addr"/> spring container checks
whether the reference is available in current configuration file,
if not available it checks in all the imported configuration file and
create the object.
<ref local="addr"/>
When we specified <ref local="addr"/> spring container always
checks in the current configuration file only.
If it is not available in the current configuration file spring
container throws an exception.
<ref parent="addr"/>
When we specified <ref parent="addr"/> spring container
checks for reference in parent spring container.
In spring we can create multiple spring containers, we
can make some container are parent containers, some
containers are child containers.
39
Karrasankar158@gmail.com
ApplicationContext pContainer=new
ClassPathXmlApplicationContext(
"com/core/applicationContext.xml");
ApplicationContext cContainer=new
ClassPathXmlApplicationContext(
new
String[]{"com/core/customerContext.xml"},pContainer
);
cContainer.getBean("addr");
cContainer.getBean("emp");
40
Karrasankar158@gmail.com
41
Karrasankar158@gmail.com
<property name="male">
<value type="boolean">true</value>
</property>
<property name="salary">
<value type="double">1000.00</value>
</property>
Arrays :
String[] parents;
}
applicationContext.java
<bean id="emp" class="com.core.Employee">
<property name="parents">
<value>father,mother</value>
</property>
</bean>
Collections :
42
Karrasankar158@gmail.com
ArrayList :
To supply a value to arraylist property we use a tag "list"
Employee.java
package com.core;
import java.util.ArrayList;
ArrayList projects;
public ArrayList getProjects() {
return projects;
}
public void setProjects(ArrayList projects){
this.projects = projects;
}
}
applicationContext.xml
<bean id="emp" class="com.core.Employee">
<property name="projects">
<list>
<value>BMS project</value>
<value>ZING project</value>
</list>
</property>
</bean>
MyApp.java
package com.core;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApp
licationContext;
43
Karrasankar158@gmail.com
ApplicationContext container=new
ClassPathXmlApplicationContext(
"com/core/applicationContext.xml");
Employee e=(Employee)container.getBean("emp");
System.out.println(e.getProjects());
}//main
output :
Ex 2 :
We are created a project bean, the project bean is
responsible for holding the project information.
Project.java
package com.core;
44
Karrasankar158@gmail.com
this.projectName = projectName;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
An Employee can have multiple projects to store the
project information
We are using the following bean with ArrayList
property.
Employee.java
package com.core;
import java.util.ArrayList;
ArrayList projects;
public ArrayList getProjects() {
return projects;
}
public void setProjects(ArrayList projects){
this.projects = projects;
}
}
To supply ArrayList values with object, we use following tags
<bean name="bms" class="com.core.Project">
<property name="projectName" value="BMS project"/>
<property name="customerName" value="Ashok"/>
</bean>
45
Karrasankar158@gmail.com
Set :
Employee.java
package com.core;
import java.util.HashSet;
HashSet projects;
public HashSet getProjects() {
return projects;
}
public void setProjects(HashSet projects) {
this.projects = projects;
}
}
To configure setProperty to use set tag as shown below
applicationContext.xml
46
Karrasankar158@gmail.com
<property name="projects">
<set>
<value>LIC</value>
<value>KSRTC</value>
</set>
</property>
</bean>
Map :
Employee.java
package com.core;
import java.util.HashMap;
HashMap projects;
public HashMap getProjects() {
return projects;
}
public void setProjects(HashMap projects) {
this.projects = projects;
}
}
The following configuration for HashMap
Props :
47
Karrasankar158@gmail.com
Employee.java
package com.core;
import java.util.Properties;
Properties projects;
public Properties getProjects() {
return projects;
}
public void setProjects(Properties projects) {
this.projects = projects;
}
}
applicationContext.xml (spring configuration file)
48
Karrasankar158@gmail.com
package com.core;
int no;
String name;
String fatherName;
String motherName;
49
Karrasankar158@gmail.com
Parent.java
package com.core;
}
Student.java
package com.core;
int no;
String name;
50
Karrasankar158@gmail.com
}
configuration file :
<bean id="parents" class="com.core.Parent"
abstract="true">
<property name="fatherName" value="abc"/>
<property name="motherName" value="xyz"/>
</bean>
import
org.springframework.context.ApplicationContext;
import org.springframework.context.support.*;
51
Karrasankar158@gmail.com
ApplicationContext container=new
ClassPathXmlApplicationContext(
"com/core/applicationContext.xml");
Student s=(Student)container.getBean("students");
System.out.println(s.getNo());
System.out.println(s.getMotherName());
}//main
}
The advantage of above approach is we can inherit the
properties of abstract bean and use it.
Dependency Injection Example :
EmployeeServices.java
package com.core;
52
Karrasankar158@gmail.com
return true;
}
}
EmployeeDao.java
package com.core;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
53
Karrasankar158@gmail.com
}//setSal
public double getSal(int eno){
try{
con=dataSource.getConnection();
PreparedStatement pstmt=
con.prepareStatement("select sal from
emp where eno=?");
pstmt.setInt(1,eno);
ResultSet rs=pstmt.executeQuery();
if(rs.next())
return rs.getDouble(1);
throw new RuntimeException("Employee not
found");
}//try
54
Karrasankar158@gmail.com
catch(Exception e){
e.printStackTrace();
throw new RuntimeException();
}
finally{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}//finally
}
}
mybeans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation="http://www.springframework
.org/schema/beans
http://www.springframework.org/schema/beans/sp
ring-beans-2.5.xsd">
<bean id="empservices"
class="com.core.EmployeeServicesImpl">
<property name="employeeDao">
<ref local="dao"/>
</property>
</bean>
<bean id="ds"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@localhost:1521:xe</value>
</property>
<property name="username">
<value>system</value>
</property>
<property name="password">
<value>tiger</value>
</property>
</bean>
</beans>
EmployeeServicesTestCase.java
package com.core;
import
org.springframework.beans.factory.BeanFactory;
import
org.springframework.beans.factory.xml.XmlBeanFactor
y;
import
org.springframework.core.io.FileSystemResource;
BeanFactory beans=
new XmlBeanFactory(new
FileSystemResource("mybeans.xml"));
EmployeeServices empservices=
56
Karrasankar158@gmail.com
(EmployeeServices)beans.getBean("empservices");
empservices.incrementSalary(Integer.parseInt(args[0
]), 1000d);
}//main
}//class
Configuring Beans :
▪ The Spring Core Container supports the bean
configurations for different types of instantiations.
▪ This is one of the advantage of spring framework allowing
us to configure any existing java class to be instantiated and
managed by the spring container.
▪ Spring even supports the configuration of a static inner
class for instantiation.
Spring supports 3 types of instantiations :
1. Using constructor
2. Static factory method
3. Non-static factory method
Instantiating Bean using Constructor :
<!--instantiating bean with no argument
constructor-->
<bean id="bean1" class="MyBeanClass1"/>
57
Karrasankar158@gmail.com
</constructor-arg>
</bean>
<constructor-arg index="0">
<ref local="mybean"/>
</constructor-arg>
</bean>
syntax :
<bean id="mybean" class="com.core.MyFactoryBean"
factory-method="getInstance"/>
<bean id="con" class="java.sql.DriverManager"
factory-
method="getConnection">
<constructor-arg>
<value>jdbc:oracle:thin:@localhost:1521:xe</value>
</constructor-arg>
<constructor-arg>
<value>scott</value>
</constructor-arg>
<constructor-arg>
<value>tiger</value>
</constructor-arg>
<property name="autoCommit">
<value type="boolean">false</value>
</property>
58
Karrasankar158@gmail.com
</bean>
Scopes Description
▪ This is default scope.
▪ A bean defination configured with this scope is
instantiated only once per container
singleton instance.
▪ And all the requests for this bean or
references created for this bean in the context
will be given with the single object reference.
59
Karrasankar158@gmail.com
Initialization :
import
org.springframework.beans.factory.InitializingBean;
public BeanLifeCycle(){
//invoke before the bean properties are set
//can perform initializations, but bean properties
are not available
60
Karrasankar158@gmail.com
}
public void afterPropertiesSet()throws Exception{
//invoke after the bean properties are set
successfully
//can perform initializations, even using the bean
properties
}
}//class
Spring allows us to configure the default initialization method for
all the beans configured in an XML configuration file.
<beans default-init-method="initialize">
<bean id="mybean1"
class="com.core.BeanLifeCycle1"/>
<bean id="mybean2"
class="com.core.BeanLifeCycle2"/>
Destruction :
61
Karrasankar158@gmail.com
import
org.springframework.beans.factory.DisposableBean;
}//class
Spring allows us to configure the default destruction method for
all the beans configured in an XML configuration file.
<beans default-destroy-method="close">
<bean id="mybean1"
class="com.core.BeanLifeCycle1"/>
<bean id="mybean2"
class="com.core.BeanLifeCycle2"/>
<bean id="mybean3"
class="com.core.BeanLifeCycle3"
destroy-
method="destroy"/>
</beans>
Method Injection
LookUp Method Injection :
BusinessObject1.java
package com.core;
BusinessObject2 bo2=getBusinessObject2();
<bean id="businessObject2"
class="com.core.BusinessObject2"
scope="prototype"/>
64
Karrasankar158@gmail.com
65
Karrasankar158@gmail.com
resOne_en_US.properties
MyApp.java
"org.springframework.context.support.ResourceBundle
MessageSource">
Terminology :
1. Concern
2. Joinpoint
3. Advice
4. Pointcut
5. Aspect
6. Weaving
Spring AOP
Spring Advice API
▪ Before advice
▪ After returning advice
▪ Throws advice
▪ Around advice
Before Advice
public void before(Method m,)
Working with before advice :
67
Karrasankar158@gmail.com
AccountServices.java
package com.aop;
}
AccountServicesImpl.java
package com.aop;
public AccountServicesImpl(){ }
68
Karrasankar158@gmail.com
double bal=accountDAO.getBalance(accno);
bal-=amt;
if(bal>=1000){
accountDAO.setBalance(accno,bal);
return true;
}
return false;
}
}
MyException.java
package com.aop;
public MyException(){ }
}
AccountDAO.java
package com.aop;
}
AccountDAOTestImpl.java
package com.aop;
69
Karrasankar158@gmail.com
}
LoggingAdvice.java
package com.aop;
import java.lang.reflect.Method;
import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;
args.length+"arguments");
}//before
70
Karrasankar158@gmail.com
}
log4j.properties
log4j.rootLogger=info, myapp
#log4j.appender.myapp=org.apache.log4j.ConsoleAppen
der
log4j.appender.myapp=org.apache.log4j.FileAppender
log4j.appender.myapp.file=mylog.html
log4j.appender.myapp.layout=org.apache.log4j.HTMLLa
yout
log4j.appender.myapp.append=false
mybeans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/
schema/beans
http://www.springframework.org/schema/beans/spring-
beans-3.0.xsd">
<bean id="accDAO"
class="com.aop.AccountDAOTestImpl"/>
<bean id="accServices"
class="com.aop.AccountServicesImpl">
<constructor-arg>
<ref local="accDAO"/>
</constructor-arg>
</bean>
71
Karrasankar158@gmail.com
class="org.springframework.aop.framework.ProxyFacto
ryBean">
<property name="targetName">
<value>accServices</value>
</property>
<property name="proxyInterfaces">
<list>
<value>com.aop.AccountServices</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>logging</value>
</list>
</property>
</bean>
</beans>
AccountServicesTestCase.java
package com.aop;
import
org.springframework.beans.factory.BeanFactory;
import
org.springframework.beans.factory.xml.XmlBeanFactor
y;
import
org.springframework.core.io.FileSystemResource;
new XmlBeanFactory(new
FileSystemResource("src/mybeans.xml"));
AccountServices
as=(AccountServices)beans.getBean("accountServices"
);
System.out.println(as.withdraw(1, 1000));
System.out.println("\n");
System.out.println(as.deposit(1, 1000));
}
}
result :
Logging Advice applied for : withdraw
in withdraw method
true
MyBusinessObject.java
package com.aop;
}
else {
System.out.println("returning Hello...");
return "Hello from business service";
}
}
}
MyAfterReturningAdvice.java
package com.aop;
import java.lang.reflect.Method;
import
org.springframework.aop.AfterReturningAdvice;
74
Karrasankar158@gmail.com
}//class
MyException.java
package com.aop;
public MyException(){ }
}
MyBusinessObjectTestCase.java
package com.aop;
import
org.springframework.beans.factory.BeanFactory;
import
org.springframework.beans.factory.xml.XmlBeanFactor
y;
import
org.springframework.core.io.FileSystemResource;
75
Karrasankar158@gmail.com
try{
System.out.println("Testing flow when
MyException is thrown by advice");
System.out.println(bo.businessService(0));
}
catch (MyException e) {
System.out.println(e);
}
System.out.println("\n");
try{
System.out.println("Testing flow when
MyException is thrown by advice");
System.out.println(bo.businessService(1));
}
catch (Exception e) {
System.out.println(e);
}
}//main
}//class
mybeans.xml
<beans>
76
Karrasankar158@gmail.com
<bean id="afterReturning"
class="com.aop.MyAfterReturningAdvice"/>
<bean id="myServices"
class="org.springframework.aop.framework.ProxyFacto
ryBean">
<property name="targetName" value="myser"/>
<property name="interceptorNames">
<list>
<value>afterReturning</value>
</list>
</property>
</bean>
</beans>
result :
Testing normal flow ...
in business service
returning Hello...
In MyAfterReturningAdvice :businessService
Accessing return value...
return value found :Hello from business service
advice ending without throwing exception...
Hello from business service
77
Karrasankar158@gmail.com
THROWS ADVICE
Working with throws advice :
MyBusinessObject.java
package com.aop;
import
org.springframework.beans.factory.BeanFactory;
import
org.springframework.beans.factory.xml.XmlBeanFactor
y;
import
org.springframework.core.io.FileSystemResource;
try{
78
Karrasankar158@gmail.com
System.out.println("\n");
try{
System.out.println("Testing flow when
MyException2
is thrown by businessService()...");
bo.businessService(1);
}
catch (Exception e) {
System.out.println(e);
}
System.out.println("\n");
System.out.println("Testing flow when there is
no MyException thrown by
businessService()...");
bo.businessService(2);
}//main
}//class
MyException1.java
package com.aop;
public MyException1(){ }
super(message);
}
}
MyException2.java
package com.aop;
public MyException2(){ }
}
MyThrowsAdvice.java
package com.aop;
import org.springframework.aop.ThrowsAdvice;
80
Karrasankar158@gmail.com
System.out.println("In
afterThrowing(MyException2)");
}
}
mybeans.xml
<beans>
<bean id="exceptionHandler"
class="com.aop.MyThrowsAdvice"/>
<bean id="myServices"
class="org.springframework.aop.framework.ProxyFacto
ryBean">
<property name="targetName" value="myser"/>
<property name="interceptorNames">
<list>
<value>exceptionHandler</value>
</list>
</property>
</bean>
</beans>
MyBusinessObjectTestCase.java
package com.aop;
import
org.springframework.beans.factory.BeanFactory;
import
org.springframework.beans.factory.xml.XmlBeanFactor
y;
import
org.springframework.core.io.FileSystemResource;
81
Karrasankar158@gmail.com
try{
System.out.println("Testing flow when
MyException1 is
thrown by businessService()...");
bo.businessService(0);
}
catch (MyException1 e){
System.out.println(e);
}
System.out.println("\n");
try{
System.out.println("Testing flow when
MyException2 is
thrown by
businessService()...");
bo.businessService(1);
}
catch (Exception e) {
System.out.println(e);
}
System.out.println("\n");
System.out.println("Testing flow when there is
82
Karrasankar158@gmail.com
no MyException thrown by
businessService()...");
bo.businessService(2);
}//main
}//class
output :
Testing flow when MyException1 is thrown by
businessService()...
in business service
throwing MyException1...
In afterThrowing(MyException1)
com.aop.MyException1: MyException1 from
MyBusinessObject
AROUND ADVICE
Working with around advice :
MyBusinessObject.java
package com.aop;
if(id==0){
System.out.println("throwing MyException1...");
throw new MyException1("MyException1 from
MyBusinessObject");
}
else if(id==1){
System.out.println("throwing MyException2...");
throw new MyException2("MyException2 from
MyBusinessObject");
}
else if(id==2){
System.out.println("returning Test1...");
return "Test1";
}
else{
System.out.println("returning Test2...");
return "Test2";
}
}//businessService
}
MyAroundAdvice.java
package com.aop;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
if(o.equals("Test1")){
System.out.println("invoke() after executing
proceed()");
return "Method returned Test1 but advice has
changed";
}
return o;
}//try
catch (MyException1 e) {
System.out.println("invoke(), proceed() thrown
MyException1");
return "Hello, there was an Exception";
}
}//invoke
}
MyException1.java
package com.aop;
public MyException1(){ }
}
MyException2.java
package com.aop;
85
Karrasankar158@gmail.com
public MyException2(){ }
}
log4j.properties
log4j.rootLogger=info, myapp
#log4j.appender.myapp=org.apache.log4j.ConsoleAppen
der
log4j.appender.myapp=org.apache.log4j.FileAppender
log4j.appender.myapp.file=mylog.html
log4j.appender.myapp.layout=org.apache.log4j.HTMLLa
yout
log4j.appender.myapp.append=false
mybeans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/
schema/beans
http://www.springframework.org/schema/beans/spring-
beans-3.0.xsd">
86
Karrasankar158@gmail.com
<bean id="myServices"
class="org.springframework.aop.framework.ProxyFacto
ryBean">
<property name="targetName" value="myser"/>
<property name="interceptorNames">
<list>
<value>around</value>
</list>
</property>
</bean>
</beans>
MyBusinessObjectTestCase.java
package com.aop;
import
org.springframework.beans.factory.BeanFactory;
import
org.springframework.beans.factory.xml.XmlBeanFactor
y;
import
org.springframework.core.io.FileSystemResource;
87
Karrasankar158@gmail.com
System.out.println("\n");
System.out.println("Testing flow when
businessService() returns Test1...");
System.out.println(bo.businessService(2));
System.out.println("\n");
System.out.println("Testing flow when
businessService() returns Test2...");
System.out.println(bo.businessService(3));
}//main
}//class
output :
Testing flow when MyException1 is thrown by
businessService()...
invoke() method before calling proceed()
in business service
throwing MyException1...
invoke(), proceed() thrown MyException1
Hello, there was an Exception
88
Karrasankar158@gmail.com
Types of Pointcuts
1. Static Pointcut
89
Karrasankar158@gmail.com
2. Dynamic Pointcut
Static Pointcut
NameMatchMethodPointcut :
mybeans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/
schema/beans
http://www.springframework.org/schema/beans/spring-
beans-3.0.xsd">
<bean id="accdao"
class="com.pointcut.AccountDAOTestImpl"/>
<bean id="accServices"
class="com.pointcut.AccountServicesImpl">
<constructor-arg>
<ref local="accdao"/>
</constructor-arg>
</bean>
<bean id="logging"
class="com.pointcut.LoggingAdvice"/>
<bean id="mypointcut"
class="org.springframework.aop.support.NameMatchMet
hodPointcut">
90
Karrasankar158@gmail.com
<property name="mappedName">
<value>withdraw</value>
</property>
</bean>
<bean id="loggingAdvisor"
class="org.springframework.aop.support.DefaultPoint
cutAdvisor">
<property name="advice">
<ref local="logging"/>
</property>
<property name="pointcut">
<ref local="mypointcut"/>
</property>
</bean>
<bean id="accountServices"
class="org.springframework.aop.framework.ProxyFacto
ryBean">
<property name="targetName" value="accServices"/>
<property name="interceptorNames">
<list>
<value>loggingAdvisor</value>
</list>
</property>
</bean>
</beans>
Regular Expression Method Pointcut :
<bean id="mypointcut"
class="org.springframework.aop.support.JdkRegexpMet
hodPointcut">
<property name="patterns">
<list>
91
Karrasankar158@gmail.com
<value>.*get.*</value>
<value>.*set.*</value>
</list>
/property>
</bean>
Dynamic Pointcuts
Control Flow Pointcut :
<bean id="mypointcut"
class="org.springframework.aop.support.ControlFlowP
ointcut">
<constructor-arg>
<value>com.aop.WithDrawService</value>
</constructor-arg>
</bean>
Introduction :
92
Karrasankar158@gmail.com
}
JDBCTemplate is dependent on DataSource object.
▪ In spring we can use 3 categories of dataSource objects,
they are default the spring guys are develops so many
dummy connection pool programs.
They are available in a
package org.springframework.jdbc.dataSource.
▪ By default spring is integrated with DBCP connection
pool and C3P connection pool
▪ We can use Weblogic connection pool.
Procedure to use DAO module in Spring :
▪ To the Project add spring capabilities, to add DAO module
we need to check the checkbox spring 3.0 persistence
JDBC library.
▪ We try to use JDBCTemplate class by creating the object
manually.
package com.dao;
94
Karrasankar158@gmail.com
import org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.jdbc.datasource.DriverManagerDa
taSource;
applicationContext.xml
<bean id="ds"
class="org.springframework.jdbc.datasource.DriverMa
nagerDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="scott"/>
<property name="password" value="tiger"/>
</bean>
<bean id="jt"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="ds"/>
</property>
</bean>
The following java code to insert a record into DataBase server.
package com.dao;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApp
licationContext;
import org.springframework.jdbc.core.JdbcTemplate;
96
Karrasankar158@gmail.com
"com/core/applicationContext.xml");
JdbcTemplate
jt=container.getBean("jt",JdbcTemplate.class);
int no=jt.update("insert into product
values(23,'pone',3450)");
System.out.println(no);
}
<bean id="ds"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="scott"/>
<property name="password" value="tiger"/>
</bean>
<bean id="jt"
class="org.springframework.jdbc.core.JdbcTemplate">
97
Karrasankar158@gmail.com
<property name="dataSource">
<ref bean="ds"/>
</property>
</bean>
package com.dao;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApp
licationContext;
import org.springframework.jdbc.core.JdbcTemplate;
"com/dao/applicationContext.xml");
JdbcTemplate
jt=container.getBean("jt",JdbcTemplate.class);
int no=jt.update("insert into product
values(2,'pone', 3450)");
System.out.println("success");
}
98
Karrasankar158@gmail.com
5.
class="org.springframework.jndi.JndiObjectFacto
ryBean">
6. <property name="jndiName" value="myPool"/>
7. <property name="jndiEnvironment">
8. <props>
9. <prop key="java.naming.factory.initial">
10. weblogic.jndi.WLInitialContextFactory
11. </prop>
12. <prop key="java.naming.provider.url">
13. t3://localhost:7001/
14. </prop>
15. </props>
16. </property>
17. </bean>
18.
19. <bean id="ds" class=
20.
"org.springframework.jdbc.datasource.UserCreden
tialsDataSourceAdapter">
21. <property name="targetDataSource"
ref="jndiPool"/>
22. <property name="username" value="weblogic"/>
23. <property name="password" value="weblogic"/>
24. </bean>
25.
26.
27. <bean id="jt"
class="org.springframework.jdbc.core.JdbcTempla
te">
28. <property name="dataSource" ref="ds"/>
29. </bean>
32.
33. import
org.springframework.context.ApplicationContext;
34. import org.springframework.context.support.*;
35. import
org.springframework.jdbc.core.JdbcTemplate;
36.
37.
38. public class MyApp {
39. public static void main(String[] args) {
40. ApplicationContext container=
41. new
ClassPathXmlApplicationContext("com/dao/applica
tionContext.xml");
42. JdbcTemplate
jt=container.getBean("jt",JdbcTemplate.class);
43. int no=jt.update("insert into product
values(24,'pone',3450)");
44. }
45.
46. }
<bean id="jt"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"/>
</bean>
package com.dao;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApp
licationContext;
import org.springframework.jdbc.core.JdbcTemplate;
"com/dao/applicationContext.xml");
JdbcTemplate
jt=container.getBean("jt",JdbcTemplate.class);
String query="insert into product values(?,?,?)";
Object obj[]={4,"four",4000};
int no=jt.update(query,obj); //OR
int no1=jt.update(query,"5","five","5000");
System.out.println("success");
}
Callback Mechanism :
101
Karrasankar158@gmail.com
GetData.java
package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import
org.springframework.jdbc.core.ResultSetExtractor;
DataAccessException {
while(rs.next()){
System.out.println(rs.getString(1));
102
Karrasankar158@gmail.com
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}//while
return null;
}//extractData
}
We use a method query() to retrive the records and display it.
package com.dao;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApp
licationContext;
import org.springframework.jdbc.core.JdbcTemplate;
"com/dao/applicationContext.xml");
JdbcTemplate
jt=container.getBean("jt",JdbcTemplate.class);
String query="select * from product";
int no=jt.query(query, new GetData());
System.out.println("success");
}
103
Karrasankar158@gmail.com
104
Karrasankar158@gmail.com
}
GetData.java
package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.springframework.dao.DataAccessException;
import
org.springframework.jdbc.core.ResultSetExtractor;
DataAccessException {
ArrayList list=new ArrayList();
while(rs.next()) {
Product p=new Product();
p.setPid(rs.getString(1));
p.setPname(rs.getString(2));
p.setPrice(rs.getString(3));
list.add(p);
}//while
return list;
}//extractData
}
MyApp.java
package com.dao;
105
Karrasankar158@gmail.com
import java.util.ArrayList;
import
org.springframework.context.ApplicationContext;
import org.springframework.context.support.*;
import org.springframework.jdbc.core.JdbcTemplate;
"com/dao/applicationContext.xml");
JdbcTemplate
jt=container.getBean("jt",JdbcTemplate.class);
String query="select * from product";
ArrayList list=(ArrayList)jt.query(query, new
GetData());
java.util.Iterator i=list.iterator();
while(i.hasNext()){
Product p= (Product) i.next();
System.out.println(p.getPid());
System.out.println(p.getPname());
System.out.println(p.getPrice());
System.out.println("------");
}//while
System.out.println("success");
}//main
}
Spring guys are provided the following Template
classes as part of DAO module.
106
Karrasankar158@gmail.com
1. JdbcTemplate
2. NamedParameterJdbcTemplate
3. SimpleJdbcTemplate
4. SimpleJdbcInsert
5. SimpleJdbcCall
NamedParameterJdbcTemplate :
▪ The purpose of NamedParameterJdbcTemplate is instead
of using treditional '?' place holders we use variable names.
▪ The advantage of using NamedParameterJdbcTemplate is
it improves readability of queries.
▪ Ex:
▪
▪ insert into product values(:pid,:pname,:price);
▪ NamedParameterJdbcTemplate is dependent on
DataSource object.
▪ NamedParameterJdbcTemplate is uses constructor
injection.
Procedure to work with NamedParameterJdbcTemplate :
configure DataSource and NamedParameterJdbcTemplate by
using constructor injection.
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="scott"/>
<property name="password" value="tiger"/>
</bean>
107
Karrasankar158@gmail.com
<bean id="npjt"
class="org.springframework.jdbc.core.namedparam.Nam
edParameterJdbcTemplate">
<constructor-arg type="javax.sql.DataSource"
index="0">
<ref bean="dataSource"/>
</constructor-arg>
</bean>
MyApp.java
package com.dao;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApp
licationContext;
import
org.springframework.jdbc.core.namedparam.MapSqlPara
meterSource;
import
org.springframework.jdbc.core.namedparam.NamedParam
eterJdbcTemplate;
"com/dao/applicationContext.xml");
NamedParameterJdbcTemplate npjt=
container.getBean("npjt",NamedParameterJdbcTemplate
.class);
108
Karrasankar158@gmail.com
MapSqlParameterSource map=new
MapSqlParameterSource();
map.addValue("pid", "10");
map.addValue("pname", "scoda");
map.addValue("price", "500000");
npjt.update(query, map);
System.out.println("success");
}//main
SimpleJdbcTemplate :
SimpleJdbcTemplate class clubbed functionality of JdbcTemplate
and NamedParameterJdbcTemplate.
Product.java
package com.dao;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
ProductDAO.java
package com.dao;
import java.util.ArrayList;
import org.springframework.jdbc.core.JdbcTemplate;
110
Karrasankar158@gmail.com
}
ProductRowMapper.java
package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
p.setPid(rs.getString(1));
p.setPname(rs.getString(2));
p.setPrice(rs.getString(3));
return p;
}
}
Configure DataSource, JdbcTemplate, DAO in spring bean
configuration file.
<bean id="ds"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="scott"/>
<property name="password" value="tiger"/>
</bean>
<bean id="jt"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"/>
</bean>
import java.util.ArrayList;
112
Karrasankar158@gmail.com
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApp
licationContext;
"com/dao/applicationContext.xml");
ProductDAO
productDAO=container.getBean("productDao",ProductDA
O.class);
productDAO.storeProductDetails(6,"six",60000);
productDAO.updateProductDetails(66,"six");
productDAO.deleteProductDetails(66);
ArrayList list=productDAO.getAllProductRecords();
java.util.Iterator i=list.iterator();
while(i.hasNext()){
Product p= (Product) i.next();
System.out.println(p.getPid());
System.out.println(p.getPname());
System.out.println(p.getPrice());
System.out.println("------");
}//while
System.out.println("success");
}//main
113
Karrasankar158@gmail.com
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApp
licationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
114
Karrasankar158@gmail.com
"com/dao/applicationContext.xml");
JdbcTemplate
jt=container.getBean("jt",JdbcTemplate.class);
}//RowMapper
);
java.util.Iterator i=list.iterator();
while(i.hasNext()){
Product p= (Product) i.next();
System.out.println(p.getPid());
System.out.println(p.getPname());
System.out.println(p.getPrice());
System.out.println("------");
}//while
System.out.println("success");
}//main
115
Karrasankar158@gmail.com
}); //batchUpdate
}//batchUpdates
116
Karrasankar158@gmail.com
117
Karrasankar158@gmail.com
23.
org.springframework.web.servlet.DispatcherServl
et
24. </servlet-class>
25. <load-on-startup>1</load-on-startup>
26. </servlet>
27. <servlet-mapping>
28. <servlet-name>spring</servlet-name>
29. <url-pattern>*.htm</url-pattern>
30. </servlet-mapping>
31. </web-app>
32. Create another spring bean configuration file, the
name of the file must be spring-servlet.xml
33. Create a folder whose folder name is pages (this
folder is used to hold the jsp's of a project)
34. configure InternalResourceViewResolver into spring
bean configuration file
35. <bean id="jspView"
36.
class="org.springframework.web.servlet.view.Int
ernalResourceViewResolver">
37. <property name="prefix" value="/pages/"/>
38. <property name="suffix" value=".jsp"/>
39. </bean>
spring-servlet.xml
The following steps are carried out when we deployed spring
based application
1. Server reads the contents from web.xml
2. Server creates ServletContext object
3. Server raises an event and check for appropriate event
handler in web.xml (Listener)
118
Karrasankar158@gmail.com
119
Karrasankar158@gmail.com
14. import
org.springframework.web.context.support.XmlWebA
pplicationContext;
15.
16.
17. public class ContextLoaderListener implements
ServletContextListener {
18.
19. public void
contextInitialized(ServletContextEvent sce) {
20. ServletContext
application=sce.getServletContext();
21. String
fileName=application.getInitParameter("contextC
onfigLocation");
22. WebApplicationContext container=new
XmlWebApplicationContext(fileName);
23. }
24.
25. public void
contextDestroyed(ServletContextEvent sce) {
26. //close the spring container object
27. }
28.
29. }//class
120
Karrasankar158@gmail.com
}//class
In spring, if we want to carryout any work we must
develop controller classes.
Controller
121
Karrasankar158@gmail.com
ModelAndView
handleRequest(HttpServletRequest,HttpServletResponse)
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
org.springframework.web.servlet.ModelAndView;
import
org.springframework.web.servlet.mvc.Controller;
public ModelAndView
handleRequest(HttpServletRequest request,
HttpServletResponse
response)throws Exception {
System.out.println("we are in handleRequest()");
ModelAndView mav=null;
return mav;
122
Karrasankar158@gmail.com
}//class
Configure Controller in spring bean configuration file
<bean name="/fc.htm"
class="com.mvc.FirstController"/>
spring-servlet.xml
The following steps are carried out when the client send the
request to server, whose url-pattern ends with .htm
1. Server creates request and response object,if required
server create DispatcherServlet object and call init() method
2. This method creates spring container object call to spring
bean whose scope is singleton, DispatcherServlet service()
calls handleRequest() it returns ModelAndView object.
3. The service() responds ModelAndView contains null value,
DispatcherServlet service() method stop the execution of
request, (i.e., because ModelAndView is holding null value)
123
Karrasankar158@gmail.com
124
Karrasankar158@gmail.com
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
org.springframework.web.servlet.ModelAndView;
125
Karrasankar158@gmail.com
import
org.springframework.web.servlet.mvc.AbstractControl
ler;
public ModelAndView
handleRequestInternal(HttpServletRequest request,
HttpServletResponse response)throws
Exception {
System.out.println("we are in
handleRequestInternal()");
ModelAndView mav=new ModelAndView("one");
return mav;
}
}//class
The following is internal code of AbstractController
package com.mvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
org.springframework.web.servlet.ModelAndView;
import
org.springframework.web.servlet.mvc.Controller;
public ModelAndView
handleRequest(HttpServletRequest request,
126
Karrasankar158@gmail.com
handleRequestInternal(request,response);
//...............
return null;
}
}//class
127
Karrasankar158@gmail.com
public SecondController(){
String[] methods=new String[]{"POST"};
this.setSupportedMethods(methods);
}
public ModelAndView
handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws
Exception {
//................
return null;
}
}//class
It is not recommended to use setSupportedMethods() to
achieving by using spring bean configuration file as shown below
<bean name="/sc.htm"
class="com.mvc.SecondController">
<property name="supportedMethods">
<value>POST</value>
</property>
</bean>
spring-servlet.xml
▪ All modern browsers try to catch the website data , the dis-
advantage of this approach is if any modification is done in
server , the browser will not send the request , it's not
recommended to catch the data.
▪ In servlets, we are remove the browser cache by using
cache Control Header to achieve the same in spring , we
use a method setCacheSeconds(-).
public class SecondController extends
AbstractController{
128
Karrasankar158@gmail.com
public SecondController(){
this.setCacheSeconds(10);//disable cache memory
}
public ModelAndView
handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws
Exception {
//................
return null;
}
}//class
When we specified setCacheSeconds(-) browser catch the
data from 2 mins, if we don't want to allow browser to
catch the data we specified the value zero.
Reports :
▪ In every project we required reports, with out reports we will
never implement the project reports gives the information
about the health of the project.
▪ Generally the management uses reports to understand the
business.
129
Karrasankar158@gmail.com
package com.mvc;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
DocumentException{
Document doc=new Document();
130
Karrasankar158@gmail.com
PdfWriter.getInstance(doc, new
FileOutputStream("report.pdf"));
doc.open();
doc.add(table);
doc.close();
System.out.println("success");
}
}//class
standalone iText.jar
add jar file to IDE
iText in Action book download
iText in Action in PDF
The meaning of using jasper reports is create the object to a
class and call the methods.
ExcelSheet :
131
Karrasankar158@gmail.com
package com.mvc;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import
org.springframework.web.servlet.view.document.Abstr
actExcelView;
@Override
protected void buildExcelDocument(Map mm,
HSSFWorkbook book,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
HSSFSheet sheet=book.createSheet("dummySheet");
HSSFRow row=sheet.createRow(0);
HSSFCell cell=row.createCell(0);
cell.setCellValue("Eno");
cell=row.createCell(1);
cell.setCellValue("Name");
cell.setCellValue(2);
cell.setCellValue("Salary");
}
132
Karrasankar158@gmail.com
}//class
LoginController.java
package com.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
org.springframework.web.servlet.ModelAndView;
import
org.springframework.web.servlet.mvc.Controller;
133
Karrasankar158@gmail.com
LoginModel loginModel;
public void setLoginModel(LoginModel lm){
loginModel=lm;
}
public ModelAndView
handleRequest(HttpServletRequest request,
HttpServletResponse response)
throws Exception {
String userName=request.getParameter("userName");
String password=request.getParameter("password");
System.out.println("userName : "+userName);
System.out.println("password : "+password);
String type =
loginModel.getValidate(userName,password);
System.out.println("type : "+type);
if(type==null)
return new ModelAndView("/login.html");
else if(type.equals("admin"))
return new ModelAndView("/pages/admin.jsp");
else
return new ModelAndView("/pages/user.jsp");
} //handleRequest
}
LoginModel.java
package com.controller;
134
Karrasankar158@gmail.com
import
org.springframework.dao.EmptyResultDataAccessExcept
ion;
import org.springframework.jdbc.core.JdbcTemplate;
try{
return jdbcTemplate.queryForObject(sql,
String.class);
}catch (EmptyResultDataAccessException e) {
return null;
}
} //getValidate()
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
135
Karrasankar158@gmail.com
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation="http://java.sun.com/xml/ns
/javaee
http://java.sun.com/xml/ns/javaee/web-
app_2_5.xsd">
<servlet>
<servlet-name>ds</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherSer
vlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
</web-app>
ds-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/
schema/beans
http://www.springframework.org/schema/beans/spring-
beans-3.0.xsd">
136
Karrasankar158@gmail.com
<bean id="loginModel"
class="com.controller.LoginModel">
<constructor-arg>
<ref local="jdbcTemplate"/>
</constructor-arg>
</bean>
<bean id="loginController"
class="com.controller.LoginController">
<property name="loginModel">
<ref local="loginModel"/>
137
Karrasankar158@gmail.com
</property>
</bean>
<bean id="myUrlMapping"
class="org.springframework.web.servlet.handler.Simp
leUrlHandlerMapping">
<property name="mappings">
<props>
<prop
key="/login.spring">loginController</prop>
</props>
</property>
</bean>
</beans>
adminHome.jsp
Wel come to Admin page <br/>
userHome.jsp
Wel come to User page <br/>
139
Karrasankar158@gmail.com
140
Karrasankar158@gmail.com
1. contextClass :
2. namespace :
3. contextConfigLocation :
4. publishContext :
5. publishEvents :
6. detectAllHandlerMappings :
7. detectAllHandlerAdapters :
8. detectAllHandlerExceptionResolvers :
9. detectAllViewResolvers :
10. cleanupAfterInclude :
<servlet>
<servlet-name>ds</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherSer
vlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/myconfigs/applicationControllers.xml
</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
141
Karrasankar158@gmail.com
5. HandlerAdapter
6. HandlerExceptionResolver
7. RequestToViewNameTranslator
8. ViewResolver
▪ All the special frame work objects initialized by the
DispatcherServlet using the WebApplicationContext and
based on the detectAllXXX initialization parameters
configured to this servlet.
▪ Once if all these objects are initialized successfully, the
DispatcherServlet instance is put into service, which
provides an entry point to serve the client requests using
the special frame work objects.
143
Karrasankar158@gmail.com
Types of Phases :
1. Prepare the request context
2. Locate The Handler
3. Execute Interceptors preHandle methods
4. Invoke Handler
5. Execute Interceptors postHandle methods
144
Karrasankar158@gmail.com
6. Handle Exceptions
7. Render the View
8. Execute Interceptors afterCompletion methods
145
Karrasankar158@gmail.com
146
Karrasankar158@gmail.com
147
Karrasankar158@gmail.com
148
Karrasankar158@gmail.com
149
Karrasankar158@gmail.com
▪ The org.springframework.web.servlet.handler.BeanNam
eUrlHandlerMapping is one of the implementation of
HandlerMapping interface.
▪ This implementation defines the navigation strategy that
maps the request URL's servlet-path to the bean names.
▪ This handler mapping strategy is very simple but powerful.
The BeanNameUrlHandlerMapping is the default handler
mapping when no handler mapping is configured in the
application context.
150
Karrasankar158@gmail.com
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.Bean
NameUrlHandlerMapping"/>
<bean name="/addEmployee.spring"
class="com.spring.AddEmployeeController">
<!-- set the dependencies -->
</bean>
<bean name="/removeEmployee.spring"
class="com.spring.RemoveEmployeeController">
<!-- set the dependencies -->
</bean>
</beans>
SimpleUrlHandlerMapping
▪ The org.springframework.web.servlet.handler.SimpleUrl
HandlerMapping is one of the implementation of
HandlerMapping interface.
▪ This implementation defines the navigation strategy that
maps the request URL's servlet-path to the mapping
configured. i.e., It locates the handler(controller) by
151
Karrasankar158@gmail.com
<bean id="addEmp"
class="com.spring.AddEmployeeController">
<!-- configure dependencies -->
</bean>
<bean id="removeEmp"
class="com.spring.RemoveEmployeeController">
<!-- configure dependencies -->
</bean>
<bean id="searchEmp"
class="com.spring.SearchEmployeeController">
<!-- configure dependencies -->
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.Simp
leUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/addEmployee.spring">addEmp</prop>
<prop
key="/removeEmployee.spring">removeEmp</prop>
<prop
key="/searchEmployee.spring">searchEmp</prop>
</props>
152
Karrasankar158@gmail.com
</property>
</bean>
</beans>
This configuration is suitable for configuring non-
singleton beans
OR
<beans>
<bean id="addEmp"
class="com.spring.AddEmployeeController">
<!-- configure dependencies -->
</bean>
<bean id="removeEmp"
class="com.spring.RemoveEmployeeController">
<!-- configure dependencies -->
</bean>
<bean id="searchEmp"
class="com.spring.SearchEmployeeController">
<!-- configure dependencies -->
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.Simp
leUrlHandlerMapping">
<property name="mappings">
<map>
<entry key="/addEmployee.spring">
<ref local="addEmp"/>
</entry>
<entry key="/removeEmployee.spring">
153
Karrasankar158@gmail.com
<ref local="removeEmp"/>
</entry>
<entry key="/searchEmployee.spring">
<ref local="searchEmp"/>
</entry>
</map>
</property>
</bean>
</beans>
This configuration is suitable for configuring
singleton beans
ControllerClassNameHandlerMapping
▪ The org.springframework.web.servlet.mvc.support.Cont
rollerClassNameHandlerMapping is one of the
implementation of HandlerMapping interface.
▪ This handler mapping implementation is newly introduced in
spring 2.0
▪ The ControllerClassNameHandlerMapping follows a simple
convention for generating URL path mappings.
▪ The convention for simple Controller implementations is to
take the short names of the controller class.
Ex : If the controller class name
is com.emp.AddEmployeeController then the path
is addemployee*
<beans>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.
support.ControllerClassNameHandlerMapping"/>
154
Karrasankar158@gmail.com
<bean id="addEmp"
class="com.spring.AddEmployeeController">
<!-- configure dependencies -->
</bean>
<bean id="removeEmp"
class="com.spring.RemoveEmployeeController">
<!-- configure dependencies -->
</bean>
<bean id="searchEmp"
class="com.spring.SearchEmployeeController">
<!-- configure dependencies -->
</bean>
</beans>
CommonsPathMapHandlerMapping
▪ The org.springframework.web.servlet.handler.Common
sPathMapHandlerMapping is one of the implementation
of HandlerMapping interface.
▪ The org.springframework.web.servlet.handler.Common
sPathMapHandlerMapping is designed to recognize
Commons attributes meta data attributes of
type PathMap defined in the application controller and
automatically wires them in to the current
DiapatcherServlet's Web-application context.
▪ To use this HandlerMapping the controller class must have
a class level metadata of the
form @org.springframework.web.servlet.handler.comm
onsattribures.PathMap("/mypath.spring").
▪ We can configure multiple path maps for a single controller.
155
Karrasankar158@gmail.com
@org.springframework.web.servlet.handler.commonsatt
ribures.PathMap(
"/mypath.spring")
public ModelAndView
handleRequest(HttpServletRequest request,
HttpServletResponse
response)throws Exception {
System.out.println("we are in handleRequest()");
ModelAndView mav=null;
return mav;
}
Note : To use commons attributes path mapping , we
must compile application classes with Commons
Attributes, and run the Commons attributes indexer
tool on the application classes, which must be in a
Jar rather than in WEB-INF/classes as an individual
classes.
156
Karrasankar158@gmail.com
157
Karrasankar158@gmail.com
158
Karrasankar158@gmail.com
159
Karrasankar158@gmail.com
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
160
Karrasankar158@gmail.com
import
org.springframework.web.servlet.HandlerInterceptor;
import
org.springframework.web.servlet.ModelAndView;
/*
Do some preprocessing like check the security etc
return false;
}
System.out.println("afterCompletion() executes at
phase 5");
//Do some postprocessing
}
161
Karrasankar158@gmail.com
System.out.println("afterCompletion() executes at
phase 5");
//Do finalizations
}
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.Bean
NameUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="myInterceptor"/>
</list>
</property>
</bean>
</beans>
164
Karrasankar158@gmail.com
165
Karrasankar158@gmail.com
The HandlerAdapter :
1. The HandlerAdapter implementation takes the responsibility
of identifying the type of handler and invokes its appropriate
methods.
2. The use of HandlerAdapter facilitates us to use Plain Old
Java Objects (POJOs) with any method encapsulating the
handler behavior , as a handler.
3. Spring provides the built-in HandlerAdapter
implementations supporting different types of handlers to
work with.
4. The various types of handlers supported by the Spring built-
in HandlerAdapter are controller types, HttpRequestHandler
types, Servlet types, and ThrowawayController types.
5. The org.springframework.web.servlet.HandlerAdapter
interface declares three methods (supports(), handle(),
getLastModified()) that have to be implemented by the
HandlerAdapter implementations to help DiapatcherServlet
in delegating the request to the handlers.
Spring built-in HandlerAdapter implementations :
1. SimpleControllerHandlerAdapter
2. ThrowawayControllerHandlerAdapter
3. HttpRequestHandlerAdapter
4. SimpleServletHandlerAdapter
Note :
▪ By default only the SimpleControllerHandlerAdapter and
ThrowawayControllerHandlerAdapter handler adapters are
available to the DispatcherServlet.
166
Karrasankar158@gmail.com
package com.spring;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
org.springframework.web.servlet.HandlerAdapter;
import
org.springframework.web.servlet.ModelAndView;
if(view==null)
return null;
else if(model==null)
return new ModelAndView(view);
else
return new ModelAndView(view,model);
return -1;
}
}
package com.spring;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
ModelAndView :
168
Karrasankar158@gmail.com
169
Karrasankar158@gmail.com
170
Karrasankar158@gmail.com
171
Karrasankar158@gmail.com
172
Karrasankar158@gmail.com
173
Karrasankar158@gmail.com
In this step the work flow obtains the next element from the
iterator prepared in step 1, and casts into
HandlerExceptionResolver type reference.
Step 3 : Invoke resolveException() method :
▪ After getting the HandlerExceptionResolver of the current
iteration the resolveException() method is invoked to handle
the exception.
▪ If the resolveException() method returns a valid
ModelAndView object reference then the workflow proceeds
to phase 7 for rendering a response.
▪ If the resolveException() method returns null then it finds
whether the next element is available in the iterator.
▪ If so, then the work flow proceeds to step2 of this phase. If
the next element is not available, then the workflow
proceeds to phase 8 which then ends the request
processing by throwing the same exception.
<beans>
<bean id="handlerExceptionResolver"
class="org.springframework.web.servlet.handler.Simp
leMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop
key="org.springframework.dao.EmptyResultDataAccessE
xception">
/sqlError.html
</prop>
<prop
key="org.springframework.web.HttpRequestMethodNotSu
pportedException">
/myError.html
174
Karrasankar158@gmail.com
</prop>
</props>
</property>
</bean>
</beans>
login.html
<body>
<form action="/login.spring" > <br> // / is
optional
User Name : <input type="text" name="userName">
<br>
Password: <input type="password" name="password">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
LoginController.java
package com.spring;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
org.springframework.web.servlet.ModelAndView;
import
org.springframework.web.servlet.mvc.Controller;
LoginModel loginModel;
public void setLoginModel(LoginModel lm){
175
Karrasankar158@gmail.com
loginModel=lm;
}
public ModelAndView
handleRequest(HttpServletRequest request,
HttpServletResponse response)
throws Exception {
String userName=request.getParameter("userName");
String password=request.getParameter("password");
System.out.println("userName : "+userName);
System.out.println("password : "+password);
String type =
loginModel.getValidate(userName,password);
System.out.println("type : "+type);
if(type==null)
//return new ModelAndView("/login.html");
throw new MyException("User details are not
valid");
else if(type.equals("admin"))
return new ModelAndView("/pages/admin.jsp");
else
return new ModelAndView("/pages/user.jsp");
} //handleRequest
}
LoginModel.java
package com.spring;
import
org.springframework.dao.EmptyResultDataAccessExcept
ion;
import org.springframework.jdbc.core.JdbcTemplate;
176
Karrasankar158@gmail.com
try{
return jdbcTemplate.queryForObject(sql,
String.class);
}catch (EmptyResultDataAccessException e) {
return null;
}
} //getValidate()
}
admin.jsp
Wel come to Admin page <br/>
177
Karrasankar158@gmail.com
</body>
ds-servlet.xml
<beans>
<bean id="loginModel"
class="com.spring.LoginModel">
<constructor-arg>
<ref local="jdbcTemplate"/>
</constructor-arg>
</bean>
178
Karrasankar158@gmail.com
<bean id="loginController"
class="com.spring.LoginController">
<property name="loginModel">
<ref local="loginModel"/>
</property>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.Simp
leUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/login.spring">loginController</prop>
</props>
</property>
</bean>
<bean id="handlerExceptionResolver"
class="org.springframework.web.servlet.handler.Simp
leMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.spring.MyException">
/myError.html
</prop>
</props>
</property>
</bean>
</beans>
web.xml
<web-app>
<servlet>
179
Karrasankar158@gmail.com
<servlet-name>ds</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherSer
vlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
</web-app>
180
Karrasankar158@gmail.com
181
Karrasankar158@gmail.com
182
Karrasankar158@gmail.com
183
Karrasankar158@gmail.com
184
Karrasankar158@gmail.com
185
Karrasankar158@gmail.com
186
Karrasankar158@gmail.com
188
Karrasankar158@gmail.com
189
Karrasankar158@gmail.com
1. Controller
2. AbstractCommandController
3. SimpleFormController
4. WizardFormController
5. MultiActionController
Controller (I)
The Controller interface declares only one method, i.e.,
handleRequest(-,-).
public ModelAndView
handleRequest(HttpServletRequest request,
HttpServletResponse response) throws
Exception
AbstractCommandController (C)
protected ModelAndView handle(HttpServletRequest
request,
HttpServletResponse
response,
Object command,
BindException errors)throws
Exception
190
Karrasankar158@gmail.com
</form>
</body>
LoginController.java
package com.spring;
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.AbstractCommand
Controller;
LoginModel loginModel;
public void setLoginModel(LoginModel lm){
loginModel=lm;
}
String type =
loginModel.getValidate((UserDetails)command);
System.out.println("type : "+type);
if(type==null)
//return new ModelAndView("/login.html");
191
Karrasankar158@gmail.com
} //handleRequest
}
LoginModel.java
package com.spring;
import
org.springframework.dao.EmptyResultDataAccessExcept
ion;
import org.springframework.jdbc.core.JdbcTemplate;
try{
return jdbcTemplate.queryForObject(sql,
String.class);
}catch (EmptyResultDataAccessException e) {
192
Karrasankar158@gmail.com
return null;
}
} //getValidate()
}
UserDetails.java
package com.spring;
}
ds-servlet.xml
<beans>
193
Karrasankar158@gmail.com
</property>
<property name="url">
<value>jdbc:oracle:thin:@localhost:1521:xe</value>
</property>
<property name="username">
<value>lms</value>
</property>
<property name="password">
<value>scott</value>
</property>
</bean>
<bean id="loginModel"
class="com.spring.LoginModel">
<constructor-arg>
<ref local="jdbcTemplate"/>
</constructor-arg>
</bean>
<bean id="loginController"
class="com.spring.LoginController">
<property name="loginModel">
<ref local="loginModel"/>
</property>
194
Karrasankar158@gmail.com
<value
type="java.lang.Class">com.spring.UserDetails</valu
e>
</property>
<property name="commandName">
<value>UserDetails</value>
</property>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.Simp
leUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/login.spring">loginController</prop>
</props>
</property>
</bean>
<bean id="handlerExceptionResolver"
class="org.springframework.web.servlet.handler.Simp
leMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.spring.MyException">
/myError.html
</prop>
</props>
</property>
</bean>
195
Karrasankar158@gmail.com
</beans>
web.xml
<web-app>
<servlet>
<servlet-name>ds</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherSer
vlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
</web-app>
admin.jsp
Wel come to Admin page <br/>
196
Karrasankar158@gmail.com
Understanding Validators
step 1 : write a validator class
public boolean supports(Class c)
public void validate(Object target, Errors errors)
public boolean supports(Class c) {
return c.equals(UserDetails.class);
}
<property name="commandName">
<value>UserDetails</value>
</property>
<property name="validator">
<bean class="com.spring.UserValidator"/>
</property>
197
Karrasankar158@gmail.com
</bean>
import org.springframework.validation.Errors;
import
org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"userName",
"field.required", "The userName field cannot
be empty<br>");
198
Karrasankar158@gmail.com
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"password",
"field.required", "The password field
cannot be empty<br>");
errors.rejectValue("password", "field.minlength",
new Object[]{Integer.valueOf(5)},
"The password must contain minimum
5 characters.<br>");
}//if
} //validate
} //class
LoginController.java
package com.spring;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import
org.springframework.web.servlet.ModelAndView;
import
org.springframework.web.servlet.mvc.AbstractCommand
Controller;
LoginModel loginModel;
public void setLoginModel(LoginModel lm){
loginModel=lm;
}
if(errors.hasErrors()){
System.out.println("Errors in validation");
PrintWriter out=response.getWriter();
out.println("errors in data submitted : <br>");
out.println("no of errors :
"+errors.getErrorCount()+"<br>");
return null;
}
200
Karrasankar158@gmail.com
String type =
loginModel.getValidate((UserDetails)command);
System.out.println("type : "+type);
if(type==null)
//return new ModelAndView("/login.html");
throw new MyException("User details are not
valid ..");
else if(type.equals("admin"))
return new ModelAndView("/pages/admin.jsp");
else
return new ModelAndView("/pages/user.jsp");
} //handleRequest
}
LoginModel.java
package com.spring;
import
org.springframework.dao.EmptyResultDataAccessExcept
ion;
import org.springframework.jdbc.core.JdbcTemplate;
+user.getUserName()+"\' and
password=\'"+user.getPassword()+"\' ";
try{
return jdbcTemplate.queryForObject(sql,
String.class);
}catch (EmptyResultDataAccessException e) {
return null;
}
} //getValidate()
}
UserDetails.java
package com.spring;
}
MyException.java
202
Karrasankar158@gmail.com
package com.spring;
public MyException(String s) {
super(s);
}
}
admin.jsp
Wel come to Admin page <br/>
203
Karrasankar158@gmail.com
<value>scott</value>
</property>
</bean>
<bean id="loginModel"
class="com.spring.LoginModel">
<constructor-arg>
<ref local="jdbcTemplate"/>
</constructor-arg>
</bean>
<bean id="loginController"
class="com.spring.LoginController">
<property name="loginModel">
<ref local="loginModel"/>
</property>
<property name="commandName">
204
Karrasankar158@gmail.com
<value>UserDetails</value>
</property>
<property name="validator">
<bean class="com.spring.UserValidator"/>
</property>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.Simp
leUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/login.spring">loginController</prop>
</props>
</property>
</bean>
<bean id="handlerExceptionResolver"
class="org.springframework.web.servlet.handler.Simp
leMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.spring.MyException">
/myError.html
</prop>
</props>
</property>
</bean>
</beans>
web.xml
<web-app>
205
Karrasankar158@gmail.com
<servlet>
<servlet-name>ds</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherSer
vlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
</web-app>
result :
errors in data submitted :
no of errors : 2
userName fields errors :
The userName field cannot be empty
password fields errors :
The password field cannot be empty
SimpleFormController
home.jsp
<html>
<body>
<a href="addEmployee.spring">Add Employee</a>
</body>
</html>
addEmployee.jsp
<%@taglib
uri="http://www.springframework.org/tags/form"
prefix="form"%>
<html>
206
Karrasankar158@gmail.com
<body>
<form:errors path="EmpDetails.name"/> <br> <br>
<form:errors path="EmpDetails.eno"/>
</body>
</html>
addEmployeeSuccess.jsp
<html>
<body>
Employee details added Successfully
</body>
</html>
AddEmployeeController.java
package com.form;
import
org.springframework.web.servlet.mvc.SimpleFormContr
oller;
EmployeeServices employeeServices;
207
Karrasankar158@gmail.com
}
EmpValidator.java
package com.form;
import org.springframework.validation.Errors;
import
org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"name", "fiels.required","The name field cannot
be empty");
208
Karrasankar158@gmail.com
if(empDetails.getEno()<10){
errors.rejectValue("eno", "field.minvalue",
new Object[]{Integer.valueOf(9)},"The deptno
should be greater than 9");
}
else if(empDetails.getEno() > 99){
errors.rejectValue("eno", "field.maxvalue",
new Object[]{Integer.valueOf(99)},"The deptno
should be less than 99");
}
System.out.println("Emp Validator");
}//validate
} //class
EmployeeServices.java
package com.form;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.jdbc.core.PreparedStatementSett
er;
209
Karrasankar158@gmail.com
} //PreparedStatementSetter
); //update()
}//create
}
EmpDetails.java
package com.form;
import java.sql.Date;
}
ds-servlet.xml
<beans>
</property>
<property name="url">
<value>jdbc:oracle:thin:@localhost:1521:xe</value>
</property>
<property name="username">
<value>lms</value>
</property>
<property name="password">
<value>scott</value>
</property>
</bean>
<bean id="empServices"
class="com.form.EmployeeServices">
<constructor-arg>
<ref local="jdbcTemplate"/>
</constructor-arg>
</bean>
<bean name="/addEmployee.spring"
class="com.form.AddEmployeeController">
<property name="employeeServices">
<ref local="empServices"/>
</property>
<property name="commandClass">
<value
type="java.lang.Class">com.form.EmpDetails</value>
</property>
212
Karrasankar158@gmail.com
<property name="commandName">
<value>EmpDetails</value>
</property>
<property name="validator">
<bean class="com.form.EmpValidator"/>
</property>
<property name="formView">
<value>/addEmployee.jsp</value>
</property>
<property name="successView">
<value>/addEmployeeSuccess.jsp</value>
</property>
</bean>
</beans>
web.xml
<web-app>
<servlet>
<servlet-name>ds</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherSer
vlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
213
Karrasankar158@gmail.com
</web-app>
http://localhost:8001/spring/home.jsp
Result :
setEmployees from controller
Emp Validator
Emp services update
doSubmitAction from controller
WizardFormController
registration1.html
<html>
<body>
<form name="form1" action="registration.spring"
method="post">
<table border="0" align="left">
<tr>
<td colspan="2">
<div align="center"><strong>Registration Step 1
:</strong> </div>
</td>
</tr>
<tr><td> </td><td> </td></tr>
<tr>
<td>User Name :</td>
<td><input type="text" name="uname"
id="uname"></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="pass"
id="pass"></td>
</tr>
<tr>
<td>Re-Password :</td>
214
Karrasankar158@gmail.com
<tr>
<td colspan="2">
<div align="center">
<input type="submit" name="Submit" value="Next >">
</div></td>
</tr>
</table>
<input type="hidden" name="_page" value="1">
</form>
</body>
</html>
registration2.html
<html>
<body>
<form name="form1" action="registration.spring"
method="post">
<table border="0" align="left" width="45%">
<tr>
<td colspan="2">
<div align="center"><strong>Registration Step 2
:</strong> </div>
</td>
</tr>
<tr><td> </td><td> </td></tr>
<tr>
<td>First Name :</td>
215
Karrasankar158@gmail.com
<tr>
<td colspan="2">
<div align="center">
<input type="submit" name="Submit" value="Next >">
</div></td>
</tr>
</table>
<input type="hidden" name="_page" value="2">
216
Karrasankar158@gmail.com
</form>
</body>
</html>
registrationFinal.html
<html>
<body>
<form name="form1" action="registration.spring"
method="post">
<table border="0" align="left" width="45%">
<tr>
<td colspan="3" align="center">
<div><strong>Registration Final Step :</strong>
</div>
</td>
</tr>
<tr><td> </td><td> </td></tr>
<tr>
<td colspan="2"><strong>Address : </strong></td>
</tr>
<tr>
<td> Address1 :</td>
<td><input type="text" name="addr" id="addr"></td>
</tr>
<tr>
<td> Street :</td>
<td><input type="text" name="street"
id="street"></td>
</tr>
<tr>
<td> City :</td>
<td><input type="text" name="city" id="city"></td>
</tr>
<tr>
<td> State :</td>
<td><input type="text" name="mobile"
id="mobile"></td>
</tr>
217
Karrasankar158@gmail.com
<tr>
<td> Country :</td>
<td><input type="text" name="phone"
id="phone"></td>
</tr>
<tr><td> </td><td> </td></tr>
<tr>
<td colspan="2">
<div align="center">
<input type="submit" name="Submit" value="Finish">
</div></td>
</tr>
</table>
<input type="hidden" name="_finish" value="Finish">
</form>
</body>
</html>
RegistrationContoller.java
package com.wizard;
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.AbstractWizardF
ormController;
@SuppressWarnings("deprecation")
public class RegistrationController extends
AbstractWizardFormController {
@Override
protected ModelAndView
processFinish(HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException exceptions) throws
Exception {
UserDetails userDetails=(UserDetails)command;
boolean flag=userDAO.create(userDetails);
if(flag)
return new
ModelAndView("registrationSuccess.jsp");
return new ModelAndView("registrationFail.jsp");
}//processFinish
}
UserDetails.java
package com.wizard;
this.dob = dob;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
221
Karrasankar158@gmail.com
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
UserDAO.java
package com.wizard;
}
UserDAOImpl.java
package com.wizard;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.jdbc.core.PreparedStatementSett
er;
222
Karrasankar158@gmail.com
ps.setString(1,userDetails.getUname());
ps.setString(2,userDetails.getPass());
ps.setString(3,userDetails.getEmail());
ps.setString(4,userDetails.getFname());
ps.setString(5,userDetails.getLname());
ps.setString(6,userDetails.getMiddle());
ps.setString(7,userDetails.getDob());
ps.setString(8,userDetails.getMobile());
ps.setString(9,userDetails.getPhone());
ps.setString(10,userDetails.getAddr());
ps.setString(11,userDetails.getStreet());
ps.setString(12,userDetails.getCity());
ps.setString(13,userDetails.getState());
ps.setString(14,userDetails.getCountry());
}//setValues()
} //PreparedStatementSetter()
); //update
return (count==1 ||
count==Statement.SUCCESS_NO_INFO );
} //create
}
RegistrationFail.html
<html>
<body>
223
Karrasankar158@gmail.com
<bean name="/registration.spring"
class="com.wizard.RegistrationController">
<constructor-arg>
<ref bean="userDAO"/>
</constructor-arg>
<property name="commandClass">
<value
type="java.lang.Class">com.wizard.UserDetails</valu
e>
</property>
<property name="commandName">
<value>UserDetails</value>
</property>
224
Karrasankar158@gmail.com
<property name="allowDirtyForward">
<value>false</value>
</property>
</bean>
</beans>
applicationDAOs.xml
<beans>
</beans>
web.xml
225
Karrasankar158@gmail.com
<web-app>
<servlet>
<servlet-name>ds</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherSer
vlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationControllers.xml
/WEB-INF/applicationDAOs.xml
</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
</web-app>
create users table in DataBase :
create table users(uname varchar2(15), pass
varchar2(15),
email varchar2(15), fname
varchar2(15),
lname varchar2(15),mname
varchar2(15),
dob varchar2(15), moble
varchar2(15),
phone varchar2(15),addr
varchar2(15),
street varchar2(15),city
varchar2(15),
226
Karrasankar158@gmail.com
state varchar2(15),country
varchar2(15));
result:
http://localhost:8001/spring/registration.spring
MultiActionController
ArithmeticController.java
package com.multi;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
org.springframework.web.servlet.ModelAndView;
import
org.springframework.web.servlet.mvc.multiaction.Mul
tiActionController;
227
Karrasankar158@gmail.com
}
home.jsp
<html>
<body>
<% if(request.getAttribute("result")!=null) { %>
Result of previous request (<%=
request.getParameter("submit") %>) :
<b>
<%= request.getParameter("operand1")%>,
<%= request.getParameter("operand2")%>
is : <%= request.getAttribute("result")%>
</b>
<%} %>
</form>
</body>
</html>
<beans>
<bean id="myMethodResolver"
class="org.springframework.web.servlet.mvc.multiact
ion.ParameterMethodNameResolver">
<property name="paramName" value="submit"/>
</bean>
<bean name="/myPath.spring"
class="com.multi.ArithmeticController">
<property name="methodNameResolver"
ref="myMethodResolver"/>
</bean>
</beans>
web.xml
<web-app>
<servlet>
<servlet-name>ds</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherSer
vlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
</web-app>
229
Karrasankar158@gmail.com
View Resolver
1. UrlBasedViewResolver
2. InternalResourceViewResolver
3. ResourceBundleViewResolver
4. BeanNameViewResolver
5. XmlViewResolver
UrlBasedViewResolver
applicationContext.xml
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBase
dViewResolver">
<property name="prefix" value="/WEB-INF/jsps"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass"
value="org.springframework.web.servlet.view.Interna
lResourceView"/>
</bean>
InternalResourceViewResolver
230
Karrasankar158@gmail.com
<bean id="viewResolver"
class="org.springframework.web.servlet.view.Interna
lResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass"
value="org.springframework.web.servlet.view.Interna
lResourceView"/>
</bean>
ResourceBundleViewResolver
<bean id="viewResolver"
class="org.springframework.web.servlet.view.Resourc
eBundleViewResolver">
<property name="basename" value="myViews"/>
</bean>
myViews.properties
BeanNameViewResolver
<bean id="viewResolver"
class="org.springframework.web.servlet.view.BeanNam
eViewResolver"/>
XmlViewResolver
<bean id="viewResolver"
class="org.springframework.web.servlet.view.XmlView
Resolver">
231
Karrasankar158@gmail.com
<bean
class="org.springframework.web.servlet.view.BeanNam
eViewResolver">
<property name="order" value="1"/>
</bean>
<bean
class="org.springframework.web.servlet.view.Interna
lResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlVie
w"/>
<property name="order" value="2"/>
</bean>
Understanding View :
MyGifView.java
package com.view;
import java.util.Map;
232
Karrasankar158@gmail.com
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.View;
EmpDAO.java
EmpDAOImplDB.java
EmpRowMapper.java
EmpDetails.java
services-contect.xml
webConfig-context.xml
search.jsp
employeeDetails.jsp
employeeList.jsp
234
Karrasankar158@gmail.com
dbError.jsp
notANumberError.jsp
ApplicationResources_en.properties
web.xml
235