http://www.mkyong.com/tutorials/spring-tutorials/ http://static.springsource.org/spring/docs/2.5.x/reference/ index.html http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/ http://www.mkyong.com/struts2/struts-2-spring-integration-example/ http://r4r.co.in/java/struts/basic/tutorial/struts2.0/index.shtml http://www.java2s.com/Code/Java/Hibernate/CascadeSaveOrUpdate.htm http://www.techienjoy.com/struts2-upload-example.php http://www.techienjoy.com/Spring.php http://www.interview-questions-tips-forum.net/ http://r4r.co.in/java/ http://r4r.co.in/java/spring/basic/tutorial/spring2.5/ First Application Of Hibernate It is a first application which persist data into database: Step 1:- first we create a hibernate.cfg.xml file: Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment. // hibernate.cfg.xml <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <mapping resource="Emp.hbm.xml"/> </session-factory> </hibernate-configuration>
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Commonly used classes and interfaces exposed by hibernate for application developer:-
Configurtion:- Configuration object is used by the hibernate to stored configuration information in object form.Configuration information data is required by hibernate to connect to a database and information of classes that are to be managed by hibernate.
SessionFactory:- It is a factory class which is used by application developer to create session.A part from this it can also be used to manage second level cache .
Session:-This is a main interface throw which application eveloper interact. This interface provide method for persistance object,creating tansaction and query objects for each user a different session is provided.
Transaction:-This interface is used by appliction developer to transact execution query.
Query:- This interface is used by he application developer to execute HQL query. HQL is a object version of sql used by hibernate.
It is an object based version of SQL, it is used by hibernate to fetch data.
Hibernate even provide a criterion API that provide a type safe and object oriented
way to retrieve object from database.
Using SQL has following shortcoming:
1- SQL is standarized but it is vendor -dependent features.
2-SQL is designed more specifically to work with relational database tables but not object.
To overcome these issues Hibernate introduce its own object oriented query language called
Hibernate Query Language(HQL).
Advantages Of Using HQL:-
1- HQL queries are database independent.
2-HQL provide a support for ordering the result persist objects.
3-HQL is more object oriented which makes us write more easily than Sql.
4- HQL support pagination.
Step To Execute HQL queries Using Hibernate:-
The following three steps are required in executeing HQL queries.
1- Obtaining an instance of org.hibernate.Query
2-Customize the Query object
3-Execute the Query
Step 1- Obtaining an instance of org.hibernate.Query:-
A Query instance is obtained by calling Session.createQuery() or Session.getNamedQuery method.
The createQuery() method is used to create a new instance of Query for given HQL Query.
Step 2- Customize the Query object:-
After obtaining the query object we may want to customize it by setting query parameter ,cache mode ,
Flush mode,fetch size ,an upper limit for the result set.
Step 3- Execute the Query:-
After preparing the query object by setting all custom properties we use list(),scroll(),iterate or
uniqueResult().
Syntax Of HQL Queries:-
To fetch the all the object of a type:-
from classname as Alias
ex-
1- To fetch all the emp object:-
Query q=Session.createQuery("From Emp e")
-2- To fetch only Those object to class which satisfy given condition
from classname as Alias where condition
ex- To fetch all those employee who earn more 75000/month
from Emp e where e.salary>75000
3-To fetch name of all manager
select e.name from Emp e where e.job="manager"
Note:-HQL queries supports named as well as positioned parametersFirst Approach:-(positioned parameter):-Query q=session.createQuery("select e.name from Emp e e.job=?");q.setString(1,job);// value of positioned parameter is set.
Second Approach(Named parameter):-Query q=session.createQuery("from Emp e where e.salary>:salary");q.setInt("salary",s);
public class SessionProvider {static SessionFactory factory;static{Configuration cfg=new Configuration().configure();factory=cfg.buildSessionFactory();
out.println("<html");out.println("<body><table border=1>");out.println("<tr><td>name</td><td>student</td><td>specialisationin</td></tr>");out.println("following record are fetched:");out.print("<tr><td>");out.print(p.getName());out.print("</td>");out.print("<td>");out.print(p.getStudent());out.print("</td");out.print("<td>");out.print(p.getSpecializationin());out.print("</td");out.print("</tr>");out.println("</table></body>");out.println("</html>");
session.close();}}
web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 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"><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><servlet><description>This is the description of my J2EE component</description><display-name>This is the display name of my J2EE component</display-name><servlet-name>Detail</servlet-name><servlet-class>mypack.Detail</servlet-class></servlet>
51.How can integrate Struts 2.x and Spring Framework
51.1.Introduction:-The Struts 2.x is the web application framework in Java Technology, this framework provide the concept of Model View Controller (MVC) and Interceptor to develop the web application. The Spring framework provide the facility to integrate with other framework and Developed the application in java. This tutorial provide the facility how can integrate between Spring framework and Struts 2.x .
51.2.How can integrate Spring framework and Struts 2.x:-
Following steps are required to integrate Spring framework and Struts 2.x framework:-
Step 1:-First select the web project in our IDE and add the capability of spring 2.5 and Struts 2.x (it means that add the jar file ).
1.1 .Introduction :-The Spring Framework is a lightweight open source application framework that provide facility to develop enterprise application in java platform.
Spring is an application framework i.e based on two concept first one is IOC (Inversion of Control ) and second one is AOP (Aspect Oriented Programming ). This framework does not confined it self to any specific domain or API. It can be used a console application , web application , enterprise application etc. It mean that this is a general purpose framework.
1.2 .Overview :-The Spring Framework is a general purpose framework that provide following modules.
Modules of Spring Framework
1.3 .Scope of Spring Framework :- There are many scope of spring framework which are Core , AOP , Context , TX , JDBC , ORM , Web MVC , Web , Struts Integration , Enterprise Integration and Testing . Spring all scope which are describe following :-
Core:-This modules provide basic implementation of IOC container. It provide Dependency injection, Object creation and Lifecycle management .The important basic concept is factory method to control the object creation by the IOC container and application developer using singleton or prototype model.
AOP (Aspect Oriented Programming ):- This modules build over the core and provide the concept of cross-cutting concern. The cross-cutting concern first one is concern , the concern is a task that perform as part of an operation and second one is cross-cutting, the cross-cutting is a set of concern that participate multiple operation.
Context:- This modules build over the core and represent the advance implementation of IOC container.
TX (Transaction Management):-This modules build over the AOP and provide facility to manage transaction in spring.
JDBC:-This modules build over the TX modules and provide template implementation of JDBC.
ORM (Object Relation Mapping):-This modules build over the JDBC that provide the facility of integration spring application to ORM framework such as Hibernate , Toplink etc
Web:-This module is build over context provide automation of common operation of web application such as transfer of request ,data to domain object ,file uploading ,tiles convention etc.
Web MVC:-This module build over the web and provide an MVC implementation of spring for developing web application.
Struts Integration:-This module build over the web and provide facility to integrate spring application to struts.
Enterprise Integration:-This module provide facility of integration enterprise services such as JNDI ,JMS ,Java Mail ,Web Services etc. to Spring application.
Testing:-This module over the core and provide the facility of unit an integration of testing.
1.4 .Concept of Spring Framework :-The Spring Framework work in two concept which are following:-
A. IOC (Inversion of Control)
B. AOP (Aspect Oriented Programming)
Inversion of Control (IOC):- The inversion of control (IOC) provide the facility to creation of object ,dependency satisfaction and lifecycle management.
Aspect Oriented Programming (AOP):-The Aspect Oriented Programming (AOP) provide the concept of cross-cutting concern. The cross-cutting concern first one is concern , the concern is a task that perform as part of an operation and second one is cross-cutting, the cross-cutting is a set of concern that participate multiple operation.
2. IOC Concept of Spring Framework
2.1 .Introduction :-The spring framework work the concept inversion of control , this concept provide the facility to create an object ,satisfied the dependency and lifecycle management. In the case of conventional approach creation of an object ,dependency satisfaction and lifecycle management all of these task are responsible for application developer.
Problem associated with conventional usage of an object:-
1. An application developer need to focus on object creation ,dependency satisfaction and lifecycle management in addition to object usage.
2. Conventional method create tight coupling between object and there user. The tight coupling always create maintenance problem.
3. Conventional approach result in memory wastage because each user creates own object which prevent object reusability.
IOC propose the runtime environment called IOC container that should be used by the application developer to request object. If creation of an object their dependency satisfaction and lifecycle management is manage by IOC container then application developer can focus on used to object. Object can be shared among and loose coupling between object and user can be provided. Following two approach are used to provide the Implementation of IOC.
A. Dependency Injection
B. Dependency Lookup
2.2 .Dependency Injection (DI):-In case of DI (Dependency Injection) ,dependency of object are satisfied by IOC container on its own i.e IOC container are not ask to satisfied the dependency of an object.
2.3 .Dependency Lookup (DL):-In case of DL (Dependency Lookup) ,dependency of an object are satisfied only when IOC container is asked to do so.
Note:-The spring framework does not support dependency lookup (DL) only support dependency injection (DI) approach.
3. Terminology of Spring Framework
3.1 .Bean :-Bean definition object represented by the XmlBeanFactory (DefaultListableBeanFactory). the bean manage object creation ,dependency satisfaction through the IOC container which contain following details:-
the <bean> element is used to specify the configuration of a bean to IOC container. the syntax of <bean > element.
<bean id="UniqueIdentifier" name="alias" class="BeanClass" scope="singleton/prototype" factory-method="Name of factory method" factory-bean="Name of factory bean">
3.2 .Bean Tag Element:-There are many types of bean tag element in the spring framework which are following:-
1. id and name:-The bean identify in which type of bean class are requested by the user.
2. class:-The bean class provide the information of requested by user.
3. singleton and prototype:-The bean create object one time in the case of singleton and bean create object requirement of user it means more then one time in the case of proto type.
4. constructor argument:-This configuration provide value in constructor of the bean class if which are defined in bean class. This configuration used in constructor injection.
5. property bean:-This configuration set the value in setter method which are define in the bean class. This configuration used in setter injection.
3.3 .Identify Bean by IOC container:-IOC container usage id, name and class attribute is same sequence to identify a bean.
3.4 .Resource:-Resource is an interface provided by the framework it contain method for managing configuration information. The configuration information represent information required by IOC container for creating ,dependency satisfaction and lifecycle management of bean.
3.5 .BeanFactory:-BeanFactory is an interface provided by spring framework . This interface represent the functionality of basic IOC container . Implementation of it is provided by the framework.
4. Hello World Example in Spring Framework
Introduction:-The Hello world example in spring framework uses the constructor injection. It means that object is created by the IOC container through the constructor.
Class/Library File Descriptions:-First of all we are create bean class name Hello then define the parameterize constructor and define a method name display which are print string sanded by configuration XML file.
Configuration information syntax:-
<bean id="hello" class="org.r4r.Hello"><constructor-arg value="Hello World !"/></bean>Technologies used to run this source code:-
5.1 .Introduction :-In the Spring Framework provide the concept IOC container which are responsible for creation of an object, satisfied the dependency and lifecycle management. First task of the IOC container is creation of an objects. Objects can be create through constructor and factory method.
By default IOC container create object using constructor. In order to facilitate object creation using factory method. Information of the factory need to be provided.
5.2 .Type of Object Creation :-In the spring framework concept IOC container which are create an object following two type
a. Using Constructor
b. Using Factory Method
5.3 .Object Creation Using Constructor :-IOC container create object through the constructor, If we are creating object through IOC container first you are declare parameterize constructor in our bean class and define method to print any message through the configuration file. The following syntax used in configuration file if we are create object through the constructor
<bean id="hello" class="org.r4r.Hello"><constructor-arg value="Hello World !"/></bean>
5.4 .Object Creation Using factory method :-IOC container create object through the factory method, If we are creating object through IOC container first you are declare parameterize method in our bean class and print any message through the configuration file. The following syntax used in configuration file if we are create object through the factory method.<bean id="number" class="org.r4r.Complex" factory-method="getNumber" scope="prototype"/>
Factory method can be divided in following three way:-
5.4.1. Same class static factory:-
class A{
private(){
//Logic is written
}
public static A getA(){
return new A();
}
}
Following configuration need to provided to the IOC container to use getA() factory method.
<bean id="a" class="A" factory-method="getA"/>
5.4.2. Different class static factory:-
class B{
{
==
}
class A{ //Different class static factory
public static B getB(){
return new B();
}
}
Following configuration need to provided the IOC container to use getB() factory method.
<bean id="b" class="A" factory-method="getB"/>
5.4.3. Different class non-static factory:-
class B{
{
==
}
class A{ //Different class nonstatic factory
public B getB(){
return new B();
}
}
Following configuration need to provide the IOC container to use getB() factory method.
7.Object Create Example Using Same Class Static Factory
Introduction:-This example will used to create object through the same class static factory and print "Number you are enter and sum of number which are enter by you".
public NumberDisplay(int a, int b) {super();this.a = a;this.b = b;
}public static NumberDisplay getNumber(){
Scanner in=new Scanner(System.in);System.out.println("Enter the first number:-");int x=in.nextInt();System.out.println("Enter the second number:-");int y=in.nextInt();return new NumberDisplay(x,y);
}public void display(){
System.out.println("You are enter first number is:-\t"+a);System.out.println("You are enter second number is:-\t"+b);int x=a+b;System.out.println("Sum of both number is:-"+x);
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Obtaining numbers from the IOC Container...");NumberDisplay n1=(NumberDisplay)f.getBean("number");n1.display();
}
}
OutPut:-Obtaining numbers from the IOC Container...Enter the first number:-9876Enter the second number:-6789You are enter first number is:- 9876You are enter second number is:- 6789Sum of both number is:-16665
8.Object Create Example Using Different Class Static Factory
Introduction:-This example will used to create object through the different class static factory and print "Number you are enter and sum of number which are enter by you".
public class NumberFactory {public static NumberDisplay getNumber(){
Scanner in=new Scanner(System.in);System.out.println("Enter the first number:-");int x=in.nextInt();System.out.println("Enter the second number:-");int y=in.nextInt();return new NumberDisplay(x,y);
}
}
NumberDisplay.java
package org.r4r;
public class NumberDisplay {int a,b;
public NumberDisplay(int a, int b) {super();this.a = a;this.b = b;
}public void display(){
System.out.println("You are enter first number is:-\t"+a);System.out.println("You are enter second number is:-\t"+b);int x=a+b;System.out.println("Sum of both number is:-"+x);
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Obtaining numbers from the IOC Container...");NumberDisplay n1=(NumberDisplay)f.getBean("number");n1.display();
}
}
OutPut:-Obtaining numbers from the IOC Container...Enter the first number:-9876Enter the second number:-6789You are enter first number is:- 9876You are enter second number is:- 6789Sum of both number is:-16665
9.Object Create Example Using Different Class Non-Static Factory
Introduction:-This example will used to create object through the different class Non-static factory and print "Number you are enter and sum of number which are enter by you".
public class NumberFactory {static final int NumberDisplay=1;int number;
public NumberFactory(int number) {super();this.number = number;
}public void getNumberFactory(){
number=NumberDisplay;
}
public NumberDisplay getNumber(){Scanner in=new Scanner(System.in);System.out.println("Enter the first number:-");int x=in.nextInt();System.out.println("Enter the second number:-");int y=in.nextInt();return new NumberDisplay(x,y);
}
}
NumberDisplay.java
package org.r4r;
public class NumberDisplay {int a,b;
public NumberDisplay(int a, int b) {super();this.a = a;this.b = b;
}public void display(){
System.out.println("You are enter first number is:-\t"+a);System.out.println("You are enter second number is:-\t"+b);int x=a+b;System.out.println("Sum of both number is:-"+x);
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Obtaining numbers from the IOC Container...");NumberDisplay n1=(NumberDisplay)f.getBean("number");n1.display();
}
}
OutPut:-Obtaining numbers from the IOC Container...Enter the first number:-9876Enter the second number:-6789You are enter first number is:- 9876You are enter second number is:- 6789Sum of both number is:-16665
10.Scope attribute of bean
10.1 .Introduction:-Spring framework provide the facility how many time you creating object through the IOC container. If you want this object is create only one time or more the one time then you give the all information in our configuration file. Through "SCOPE" attribute Spring framework provide this solution. If you are define "SCOPE" attribute in bean tag element then developer choose two option first option if you create object only one time then give "SINGLETON BEAN" in scope attribute and you create object more then one time then give "PROTOTYPE BEAN" in scope attribute.
10.2 .Type of Scope attribute of bean:-There are two types of bean in SCOPE attribute which are following:-
1. Singleton Bean
2. Prototype Bean
10.2.1 .Singleton Bean:-This bean provide the facility to create only one bean if any user request bean then same bean provide more then one user.
10.2.2 .Prototype Bean:-This bean provide the facility to request more then one bean if any user request bean then different bean provide each request.
Introduction:-The singleton bean is the default bean of the scope attribute that provide the facility to the user create only one time object then give the reference of same object if requested by user for this object. If you are not mansion in configuration file this scope attribute give service by default.
public interface Number {public void display();public Number add(Number n);
}
Complex.java
package org.r4r;
import java.util.Scanner;
public class Complex implements Number {int r,i;
public Complex(int r, int i) {super();this.r = r;this.i = i;
}public static Number getNumber(){
Scanner in=new Scanner(System.in);System.out.println("Enter the rational part:-");int x=in.nextInt();System.out.println("Enter the imagenary part:-");int y=in.nextInt();return new Complex(x,y);
}
@Overridepublic Number add(Number n) {
Complex c=(Complex)n;int x=this.r+c.r;int y=this.i+c.i;return new Complex(x,y);
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);
System.out.println("Obtaining numbers n1 & n2 from the IOC Container...");Number n1=(Number)f.getBean("number");Number n2=(Number)f.getBean("number");System.out.println("Number n1 is:");n1.display();System.out.println("Number n2 is:");n2.display();Number n3=n1.add(n2);System.out.println("Sum of n1 and n2");n3.display();
}
}
OutPut:-
Obtaining numbers n1 & n2 from the IOC Container...Enter the rational part:-5Enter the imagenary part:-6Number n1 is:5+6iNumber n2 is:5+6iSum of n1 and n210+12i
12.Example of prototype bean
Introduction:-The prototype bean is the optional bean of the scope attribute that provide the facility to the user create more then one object if you are requested more then one time the prototype bean provide per request new object of same bean..
public interface Number {public void display();public Number add(Number n);
}
Rational.java
package org.r4r;
import java.util.Scanner;
public class Rational implements Number {int p,q;
public Rational(int p, int q) {super();this.p = p;this.q = q;
}public static Number getNumber(){
Scanner in=new Scanner(System.in);System.out.println("Enter the Numerator part:-");int p=in.nextInt();System.out.println("Enter the Denominator part:-");int q=in.nextInt();return new Rational(p,q);
}
@Overridepublic Number add(Number n) {
Rational r=(Rational)n;int x=this.p*r.q+this.q*r.p;int y=this.q*r.q;return new Rational(x,y);
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Obtaining numbers n1 & n2 from the IOC Container...");Number n1=(Number)f.getBean("number");Number n2=(Number)f.getBean("number");System.out.println("Number n1 is:");n1.display();System.out.println("Number n2 is:");n2.display();Number n3=n1.add(n2);System.out.println("Sum of n1 and n2");n3.display();
}
}
OutPut:-
Obtaining numbers n1 & n2 from the IOC Container...Enter the Numerator part:-6Enter the Denominator part:-5Enter the Numerator part:-4Enter the Denominator part:-8Number n1 is:6/5Number n2 is:4/8Sum of n1 and n268/40
13.Dependency Injection
13.1 .Introduction:-In case of DI (Dependency Injection) ,dependency of object are satisfied by IOC container on its own i.e IOC container are not ask to satisfied the dependency of an object.
13.2 .Approach of Dependency Injection:-There are two approach of Dependency Injection which are following:-
1. Constructor Dependency Injection
2.Setter Dependency Injection
13.2.1 .Constructor Dependency Injection:-In this approach the IOC container provide the facility to satisfied the dependency of an object in mandatory case and IOC container inject the dependency through the constructor.
13.2.1 .Setter Dependency Injection:- In this approach the IOC container inject the dependency through the default constructor and setter method. This approach is used in the case of optional dependency.
13.3 .Type of Dependency Injection:-There are three type of dependency injection which are following:-
1. Dependency on primitive values (String is consider primitive by String).
2. Dependency on Object.
3. Dependency on Collection.
13.3.1 .Dependency on primitive value:-In the case of constructor injection, constructor-arg is the sub element of <bean ......> is used to specified the dependency of a bean i.e to be satisfied to a constructor this elements uses values and reference attribute which are used to specified value primitive type and object respectively.
Syntax:-
<bean .................>
<constructor-arg value="primitive or String"/>
<constructor-arg ref="Reference of a bean"/>
................
</bean>
13.3.2 .Dependency on object:-In the case of constructor injection, constructor-arg is the sub element of <bean ......> is used to specify the dependency of an object i.e to be satisfied the constructor-arg element uses reference of an attribute which are used to specify object respectively.
Syntax:-
<bean .................>
<constructor-arg >
<list><ref bean="Reference of a bean"/>
................
</list></constructor-arg>
</bean>
13.3.2 .Dependency on collection:-In the case of constructor injection, constructor-arg is the sub element of <bean ......> is used to specify the dependency of a collection i.e to be satisfied
the constructor-arg element uses list ,set and map sub element to specify the dependency of list ,set and map respectively.
Syntax:-
<bean .................>
<constructor-arg >
<list or set or map>
<Value></value>
................
</list or set or map></constructor-arg>
</bean>
14.Example of Constructor Injection
Introduction:-In the dependency injection satisfied the dependency of an object through the constructor dependency injection. Following this example inject the dependency using the constructor.
public class Test {public static void main(String ar[]){
Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Constructor value are following");A a1=(A)f.getBean("ab");a1.display();
}
}
OutPut:-Constructor value are followingConstructor is invoked101 Mukund Singh
15.Example of Setter Injection
Introduction:-In the dependency injection satisfied the dependency of an object through the setter injection. Following this example inject the dependency using the default constructor and setter method.
A is instantiated using parameter constructor.Value of a:- 10A is instantiated using Default constructor.Value of A is set by setA() method.Value of a:- 100
16.Dependency on primitive value example
Introduction:-In the case of dependency on primitive value, The constructor-arg is the sub element of <bean ......> is used to specified the dependency of a bean i.e to be satisfied to a constructor this elements uses values and reference attribute which are used to specified value primitive type.
Technology use to run this source code:-
1. Spring 2.52. Eclipse3. JDK 1.6
Source Code:-
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"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.Dependency on primitive value
public class Test {public static void main(String ar[]){
Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Constructor value are following");A a1=(A)f.getBean("ab");a1.display();
}}
OutPut:-Constructor value are followingConstructor is invoked102 101
17.Dependency on objects example
Introduction:-In the case of Dependency on object, The constructor-arg is the sub element of <bean ......> is used to specify the dependency of an object i.e to be satisfied the constructor-arg element uses reference of an attribute which are used to specify object respectively.
public class Test {public static void main(String ar[]){
Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);Student a1=(Student)f.getBean("ab");System.out.println("Student information is,");System.out.println(a1);
}
}
OutPut:-Student information is,Name:MukundCourse detailsMCA 150000MBA 250000
18.Dependency on collection using List example
Introduction:-In the case of dependency on collection, constructor-arg is the sub element of <bean ......> is used to specify the dependency of a collection i.e to be satisfied the constructor-arg element uses list sub element to specify the dependency of list respectively.
public class Test {public static void main(String ar[]){
Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);Student a1=(Student)f.getBean("ab");System.out.println("Student information is,");System.out.println(a1);
}
}
OutPut:-
Student information is,Name: MukundCourse details: Core JavaJ2EEStrutsHibernateSpring
19.Dependency on collection using Set example
Introduction:-In the case of dependency on collection, constructor-arg is the sub element of <bean ......> is used to specify the dependency of a collection i.e to be satisfied the constructor-arg element uses set sub element to specify the dependency of set respectively.
public class Test {public static void main(String ar[]){
Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);Student a1=(Student)f.getBean("ab");System.out.println("Student information is,");System.out.println(a1);
}}
OutPut:-Student information is,Name: MukundCourse details: Core JavaJ2EEStrutsHibernateSpring
20.Dependency on collection using Map example
Introduction:-In the case of dependency on collection, constructor-arg is the sub element of <bean ......> is used to specify the dependency of a collection i.e to be satisfied the constructor-arg element uses MAP sub element to specify the dependency of MAP respectively.
public class Test {public static void main(String ar[]){
Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Constructor value are following");Institute a1=(Institute)f.getBean("ab");a1.display();
}
}
OutPut:-Constructor value are followingName: XYZCourse Name FeeMCA 150000MBA 250000BCA 50000BBA 100000
21.Setter Injection Dependency using Map example
Introduction:-In the case of dependency on collection using setter injection, property is the sub element of <bean ......> is used to specify the dependency of a collection i.e to be satisfied the property element uses MAP sub element to specify the dependency of MAP respectively.
22.1 .Introduction of an Autowiring:- An autowiring is the facility provided by framework to satisfied by dependency of manage bean without configuration information. It means that the autowiring solved problem to write very long configuration information.
22.2 .Type of method to Autowire:- The following four method are used by IOC container to autowire bean dependency.
1.Autowire by Type
2.Autowire by Name
3.Autowire by Constructor
4.Autowire by autodetect
22.2.1 .Autowire by Type:-In autowiring by type , The IOC container used the bean property by type to identified the beans to be injected i.e in order to used autowiring by type we need to simply configure one bean for each property of the target bean.
Note:- Facility of autowiring are used only with object type dependency i.e primitive dependency are note autowire.
1. Optional dependency are specified using by type because dependency are injected by setter method.
2. Autowiring by type can not be used if there are more than one beans. Configured for a properties type.
22.2.2 .Autowire by Name:-In this case IOC container uses the name of a bean property to fined out the bean for injecting i.e in this approach the configuration bean to be used for satisfied the dependency of the bean must have the same as the bean property.
1. Only optional dependency can be autowire for this approach.
2. This approach would work of a bean of different type is configure using the same name as the property of a bean which uses autowiring.
22.2.3 .Autowire by Constructor:-In this approach type of parameter of the constructor are used to identified the bean to be injected in case of overloaded constructed has a maximum parameter will choose.
This approach is same as autowiring by type accept dependency are injected through constructor in it.
22.2.4 .Autowire by Autodetect:-This approach is a combination of autowiring by constructor and autowiring by type in it dependency is injected using the type of property if target bean has a default constructor and dependency are injected using constructor injection if target bean has a parameterize constructor.
Note:-This is the default strategy of the autowiring.
<bean id="x" class="org.r4r.A"/><bean id="b" class="org.r4r.B" autowire="autodetect"/>22.3 .Limitation of Autowiring:-Major draw back of autowiring is understandability is loosed
23.Example of Autowire by Name
Introduction:-In the case of Autowire by Name, The IOC container uses the name of a bean property to fined out the bean for injecting i.e in this approach the configuration bean to be used for satisfied the dependency of the bean must have the same bean property.
Default constructor of B is invoked.A is instantiatedA is instantiatedsetA() method is invoked typeName a.setA() method is invoked typeName y.
24.Example of Autowire by Type
Introduction:-In case of autowiring by type , The IOC container used the bean property by type to identified the beans to be injected i.e in order to used autowiring by type we need to simply configure one bean for each property of the target bean.
OutPut:-Default constructor of B is invoked.A is instantiatedsetA() method is invoked.
25.Example of Autowire by Constructor
Introduction:-In the case of Autowire by constructor , in this approach type of parameter of the constructor are used to identified the bean to be injected in case of overloaded constructed has a maximum parameter will choose.
A is instantiatedParameterized constructor of B is invoked.
26.Example of Autowire by Autodetect
Introduction:-In the case of Autowire by Autodetect, this approach is a combination of autowiring by constructor and autowiring by type in it dependency is injected using the type of property if target bean has a default constructor and dependency are injected using constructor injection if target bean has a parameterize constructor.
Default constructor of B is invoked.A is instantiatedsetA() method is invoked typeName a.setA() method is invoked typeName y.
27.Lifecycle management of IOC container
27.1 .Introduction:-The IOC container provide the facility of notifying beans about the creation and destruction show that bean can perform initialization or cleanup perforation. It means that the IOC container provide the facility to notifying create of bean and destroy of bean. Initialization and destruction of a bean is notified to it.
The IOC container notifying the creation and destruction either of the following two way :-
1. Non-Intrusive approach
2. Intrusive approach
27.2 .Non-Intrusive approach:-A non-intrusive approach an initialization method is defined in the bean and is specified in the bean configuration using init-method attribute.
27.3 .Intrusive approach:-In the intrusive approach initialization bean interface provided by the framework is implemented in the bean class and initializing logic is contain with it after property set method. This method is provided by "InitializingBean" interface.
27.3.1 .InitializingBean:- The InitializingBean interface provide cleanup operation at the time of unloading of a bean either destroy-method attribute of bean is used.
This interface provide a method name which are following:-
27.3.2 .DisposableBean:- This bean interface is provided by framework is implemented. This interface provide a method name destroy() if is invoked by IOC container before unload by IOC container before unloaded bean.
This interface provide single method name destroy().
public void destroy();
28.Example of Intrusive approach
Introduction:-This approach provide the facility to initialize the bean through the InitializingBean interface. This interface implement in our bean class then its provide a method name afterPropertiesSet() to override in our bean class.
OutPut:-Obtaining bean one...One is instantiated...
One is given a chance to initializeObtaining bean two...Two is instantiated....Intrusive initialization of twoNonintrunsive initialization of two....
29.Example of Non-Intrusive approach
Introduction:-A non-intrusive approach an initialization method is defined in the bean and is specified in the bean configuration using init-method attribute.
OutPut:-Obtaining bean one...One is instantiated...One is given a chance to initializeObtaining bean two...Two is instantiated....Intrusive initialization of twoNonintrunsive initialization of two....
30.Example of Difference scope bean
Introduction:-In the case of different scope bean BeanFactoryAwar interface provide the facility to give the service one scope to more than one different scope. The BeanFactoryAwar interface provide a method name setBeanFactory() to override in our bean class than solved these problem in the spring framework.
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Obtaining attendant bean....");Attendant a=(Attendant)f.getBean("a");System.out.println("Requesting two burger.....");Burger b1=a.getBurger();System.out.println(b1);Burger b2=a.getBurger();System.out.println("Description of second burger...");System.out.println(b2);
}
}
OutPut:-Obtaining attendant bean....Attendant bean is created...Reference of IOC container is provided to attendant.Requesting two burger.....New burger is created...It is burger number:-1New burger is created...Description of second burger...It is burger number:-2
31.Method Injection in Spring Framework
31.1 .Introduction:-Spring 1.1 introducing method injection for a new IOC-Oriented feature with allows greater flexibility for interactions between collaborators.
31.2 .Type of Method Injection:-
The spring framework method injection provide this facility in to two way:-
1.Lookup Method Injection
2.Method replacement
31.3 .Lookup Method Injection:-The lookup method injection provide the facility to implement in our application one bean is depends on another bean with a different life cycle. It means that singleton bean depends on non-singleton bean. In this situation setter and constructor injection create instance of singleton bean not a non-singleton bean. In some case application require singleton bean obtain new instance of the non-singleton every time it requires the bean.
If we achieve this implementation in our application the implement BeanFactoryAware interface in our singleton bean. Then using BeanFactory instance, the singleton bean can lookup a new instance of a non-singleton dependency every time it needs it.
The Lookup Method Injection allows the singleton bean to declare that it requires a non-singleton dependency and receive a new instance of the non-singleton bean each time it needs to interact with it, without needing to implement any spring-specific interfaces.
31.4 .Method Replacement:-This Method injection provide a facility to replace the implementation of any method on a bean arbitrary, without changing our source code.
Note:-If we are use lookup method injection and method replacement in our application, the add the CGLIB jar file in our application.
32.Example of Lookup Method Bean
32.1 .Introduction:-The Lookup Method injection provide a facility to one singleton bean depends on a non-singleton. It means that singleton bean depends on prototype bean.
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Obtaining attendent bean....");NewAttendant a=(NewAttendant)f.getBean("na");System.out.println("Requesting two burgar.....");Burgar b1=a.getBurgar();System.out.println(b1);Burgar b2=a.getBurgar();System.out.println("Discription of second burgar...");System.out.println(b2);
}
}
OutPut:-
Obtaining attendent bean....Requesting two burgar.....New burgar is created...It is burger number:-1New burgar is created...Discription of second burgar...It is burger number:-2
33.AOP (Aspect Oriented Programming)
33.1.Introduction:-An Aspect Oriented Programming (AOP) is a programming model that compliments object oriented programming model and provides an efficient mechanism of implementing behaviors which have crosscutting concerns.
33.2.Terminology of AOP:- There are following terminology of AOP (Aspect Oriented Programming) in spring framework:-
1.Concerns:-A concerns represent a task i.e performed as part of an operation. A concerns is set to be crosscutting concerns is it participate of multiple operation.
2.Advice:-Implementation of a concerns is called Advice.
3.Joinpoint:- Joinpoint represent easily identifiable intersection point in the execution of an application where Advices can be inserted. Loading of classes, creation of an object, invocation of method etc. can be used as joinpoint. A spring AOP implementation only support method invocation joinpoint.
5.Pointcut:- A pointcut is a collection of Joinpoint.
6.Aspect:- An Aspect is a collection of Pointcut and Advices.
33.3.What is crosscutting concern in Spring AOP:-
A concern represent a task that is performed as part of an operation. A concern is set to be crosscutting is it participate of multiple operation.
Concerns can be divided in to multiple category such as:-
1.Implementation Concern
2.Business Concern
3.Organization Concern
etc.
1.Implementation Concern:- Implementation Concerns represents those task which are required before implementing for example:-Validation, Authorization, etc
2.Business Concern:- Business concern represent actual logic or main task of an operation.
3.Organization Concern:- Organization concern represent additional services, facility and requirement associated an operation by an organization.
33.4.What is Weaving in Spring AOP:-
The process of inserting advices is called weaving. Different AOP framework supports either weaving types:-
1.Compilation time weaving
2.Runtime weaving
1.Compilation time Weaving:- In Compilation time weaving advices are inserted at the time of Compilation at the special AOP compiler.
Advantage:- The major advantage of this approach are performance.
Disadvantage:- Special AOP compiler are required and application need to be recompile.
2.Runtime Weaving:- In this approach advices are dynamically inserted which the help of proxy object.
Advantage:- Special AOP compiler are not required and Application are not required to be modified or recompile each time . Number of concerns or order changed.
Disadvantage:- Performance are degrade because of additional overhead are proxy.
Note:-A Spring AOP support Runtime weaving.
34.Proxy in Spring Framework
34.1.Introduction:-A proxy is an Object that represents the functionality of an other Object. Proxy are used an abstraction of complex services expose by the Object to another Object in AOP proxy are use to add advices before or after method invocation.
34.2.Type of Proxy in Spring Framework:-
There are two type of Proxy Object in the Spring Framework:-
1.Static Proxy
2.Dynamic Proxy
34.3.Static Proxy:-Static Proxy are created by the developer at the time of development. Static Proxy develop in two way first through the developer and second through the used of any tools for example RMI compiler etc.
34.4.Dynamic Proxy:-Dynamic proxy are created at runtime. It is provided more flexibility.
34.5.Type of Dynamic Proxy:-There are two types of Dynamic Proxy in Spring Framework:-
1.JDK Dynamic Proxy
2.CGLIB Dynamic Proxy
34.6.JDK Dynamic Proxy:-JDK Dynamic Proxy is the facility provided by Sun micro System. In Reflection API to create dynamic proxy can not be created of those classes which implements some interface that is JDK dynamic proxy to implemented those method which are described by this interface implemented by target class.
A JDK Dynamic proxy represent in instance dynamic proxy class which extends java.leng.reflect proxy class implemented by the target class. JDK dynamic proxy uses on Object.
34.7.CGLIB Dynamic Proxy:-CGLIB dynamic proxy is proxy of all the method of class perspective of the interface are implemented by the class.
5.Example of JDK Dynamic Proxy
35.1.Introduction:-JDK dynamic proxy provided by sun micro system through the reflection API to create runtime proxy object then provide the services before invocation of method and after invocation of method.
throws Throwable {System.out.println("Handler invoked invoking\t"+method.getName()+"() one
target object.....");//advices can be inserted here before actual method call.Object r=method.invoke(target, args);//advices can be inserted here after actual method call.System.out.println("Method call completed, returning value\t"+"return by
System.out.println("invoking print() on proxy.....");proxy.print();
}catch(Exception e){
System.out.println(e);}
}
}
OutPut:-
Creating target object.....Creating handler....
Creating proxy,,,invoking print() on proxy.....Handler invoked invokingprint() one target object.....print() mathod of A is invoked..Method call completed, returning valuereturn by actual method
36.Example of MyFramework AOP Implementation
36.1.Introduction:-An Aspect Oriented Programming (AOP) is a programming model that compliments object oriented programming model and provides an efficient mechanism of implementing behaviors which have crosscutting concerns.
36.2 .Technology use to run this source code:-
1.Spring2.5 jar file
2.Eclips Id
3.Tomcat Server
Note:-In this example take two different package in src folder our Application. First package name is org.r4r.framework and second package name is org.r4r.client.
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Obtaining proxy of one..");Showable p=(Showable)f.getBean("proxy");System.out.println("Proxy obtaining invoked.");p.show();
}
}
OutPut:-Obtaining proxy of one..Proxy obtaining invoked.Before advice is applied.Show() method of One invoked..
37.Advices in Spring Framework
37.1.Introduction:-Implementation of a concerns is called Advice. It means that concerns represent a task i.e performed as part of an operation. Any operation are implemented through the concern is called Advices.
37.2.Type of Advices in Spring Framework:-There are four type of advices in spring framework which are following
1.Before Advice
2.After Advice
3.Around Advice
4.After Throws Advice
37.3.Before Advice:-This Spring Before advice provide the service before invoking the method. It means that Before advices represent those concern which are to be applied before a method is invoked. Which are applied in Validation, Authorization, etc. are the task which can be implemented using before advice.
Framework provide an interface named "MethodBeforeAdvice" this interface provide a method that is used by application developer to define the task that are to be executed before the invocation target method.
37.4.After Advice:-After advice represents those task which are to be performed after the completion of method. A Spring Framework implements After Advice are invoked from the implementation of AfterReturningAdvice interface.
This interface provide a method name AfterReturning which is invoked InvocationHandler after the actual method completed. Through this method reference of target method, argument, method object and value returned by the Object are provided to the developer. Application developer may used the return value but can not change it.
37.5.Around Advice:-An around advice are used when some operations are to be performed before and after method call and controlled over the return value of the method is to be gain.
To apply around advice implementation of "MethodInterceptor" interface need to be provided by the developer. This interface provide a method name invoke which received parameter of type of Invocation. MethodInvocation Object encapsulate invocation of the actual method of the target object and exposes the method name proceed() which is used by application developer to get the actual method invoked.
38.6.After Throws Advice:-An after throws advice is used to performed some operation between throwing and catching an exception.
To implements after throws advice implementation of "ThrowsAdvice" interface need to be provided. It is the marker interface. The class which implements this interface can define a method name afterThrowing() which can have either of the following signature.
public void afterThrowing(Exception e);
public void afterThrowing(Methid m, Object[] arg, Object target);
38.Example of Before Advice
38.Introduction:-This Spring Before advice provide the service before invoking the method. It means that Before advices represent those concern which are to be applied before a method is invoked. Which are applied in Validation, Authorization, etc. are the task which can be implemented using before advice.
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Obtaining proxy of one..");Showable p=(Showable)f.getBean("proxy");System.out.println("Proxy obtaining invoked.");p.show();
}
}
OutPut:-Obtaining proxy of one..Proxy obtaining invoked.Before advice is applied..Show() method of One invoked..
39.Example of After Advice
39.1.Introduction:-After advice represents those task which are to be performed after the completion of method. A Spring Framework implements After Advice are invoked from the implementation of AfterReturningAdvice interface.
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Obtaining proxy of one..");Showable p=(Showable)f.getBean("proxy");System.out.println("Proxy obtaining invoked.");p.show();
}
}
OutPut:-Obtaining proxy of one..Proxy obtaining invoked.Before advice is applied..Show() method of One invoked..After advisor is provide service..
40.Example of Around Advice
40.1.Introduction:-An around advice are used when some operations are to be performed before and after method call and controlled over the return value of the method is to be gain.
if(x>0){System.out.println("Show() of one invoked returning success");return "success";
}else{
System.out.println("Shows() of one invoked, throwing exception");throw(new IllegalArgumentException("It is thrown by show()"));
}}
}
ThrowAdvisor.java
package org.r4r;
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
public class ThrowAdvisor implements ThrowsAdvice {/*public void afterThrowing(Exception e){
System.out.println("In throws advice because of following exception"+e);}*/public void afterThrowing(Method m,Object args[],Object target,Exception e){
System.out.println("In throws advice because"+m.getName()+"() throw following exception "+e.getMessage()+" When invoked on the object of "+target.getClass().getName()+"
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");BeanFactory f=new XmlBeanFactory(r);System.out.println("Obtaining proxy of one..");Showable p=(Showable)f.getBean("proxy");try{
System.out.println("proxy obtained invoking show() with positive value");
String s=p.show(5);System.out.println(s+" Is received by the client");System.out.println("Invoking show() with negative value");p.show(-2);
}catch(Exception e){System.out.println("Following exception caught in main"+e);
}}
}
OutPut:-Obtaining proxy of one..proxy obtained invoking show() with positive valueShow() of one invoked returning successsuccess Is received by the clientInvoking show() with negative valueShows() of one invoked, throwing exceptionIn throws advice becauseshow() throw following exception It is thrown by show() When invoked on the object of org.r4r.One Class.Following exception caught in mainjava.lang.IllegalArgumentException: It is thrown by show()
42.Pointcut in Spring
42.1.Introduction:-By simply specify advices with bean in the configuration all the method of the bean are advice some time final control is required over the application of advices i.e an application developer may want applied some advices only to the selected method to the bean.
Final control over the application of advices is provided by pointcuts. A pointcut is used by the IOC container to find out wither an advice can be applied or not. Framework provide different implementation of pointcut most commonly used implementation of which.
42.2.NameMatchMethodPointcut:-This pointcut implementation uses method name as criteria of finding out the applicability of advices.
The pointcut simply specify a which method of a bean can be advice is does not specified the advices. Advices are associated to pointcut with the help of aspect implementation of aspect is called advisor in Spring AOP implementation framework provide predefine advisor. Most commonly used one these are before pointcut advisor.
Following application demonstrate an user of pointcut or advisor to apply advises of selective method of bean.
42.3.NameMatchMethodPointcutAdvice:-One of the disadvantage of using pointcuts is entry of configuration information solution of this problem is provided by PointcutAdvisor class.
A PointcutAdvisor class combined the functionality of a pointcut and advisor in to a single unit.
The NameMatchMethodPointcutAdvisor class combined the functionality of NameMatchMethodPointcut and DefaultPointcutAdvisor using this class the configuration information is reduced as follows.
43.Example of NameMatchMethodPointcut
43.1.Introduction:-This pointcut implementation uses method name as criteria of finding out the applicability of advices. The pointcut simply specify a which method of a bean can be advice is does not specified the advices. Advices are associated to pointcut with the help of aspect implementation of aspect is called advisor in Spring AOP implementation framework provide predefine advisor. Most commonly used one these are before pointcut advisor.
Proxy obtained invoking a().Before advice is applied..a() of one invokedProxy obtained invoking b()b() of one invokedAfter advisor is provide service..
44.Example of NameMatchMethodPointcutAdvice
44.1.Introduction:-One of the disadvantage of using pointcuts is entry of configuration information solution of this problem is provided by PointcutAdvisor class.
A PointcutAdvisor class combined the functionality of a pointcut and advisor in to a single unit.
The NameMatchMethodPointcutAdvisor class combined the functionality of NameMatchMethodPointcut and DefaultPointcutAdvisor using this class the configuration information is reduced as follows.
Proxy obtained invoking a().Before advice is applied..a() of one invokedProxy obtained invoking b()b() of one invokedAfter advisor is provide service..
45.Template Design Pattern in Spring
45.1.Introduction:-Template is a behavior design pattern i.e used to implement such method which invoked predefine sequence of steps. Implementation some of all the steps can be varies but that sequence can not be varies but that sequence can not be change.
Database operation implemented by JDBC are the candidate for template design pattern because each database operation as following steps:-
1.Connection is created / obtained.
2.Statement is created.
3.Query is Executed
4.Connection close
This sequence can not be altered but individual steps can be implemented in multiple ways.
Example:-
1.Connection can be created using DriverManager, It can be obtained from a pool or can be obtained from a directory server.
2.Statement can be created in multiple ways using Statement, PreparedStatement and CallableStatement interface.
3.Usualy method which involves the predefine sequence of steps out of which some step can be varies are implemented in such a way that common steps are repeated in multiple implementation.
4.Template design pattern tries to be remove this problem to facilities definition of common steps only one in a template method and by allowing individual develop to provide the own implementation to the variable steps following example demonstrate the concept of template design pattern.
//This is a template method that facilitate of two number can be read from the keyboard from a file or from the network. Result can be displayed on the console, can be saved to a file or can be sent over the network i.e out of these steps two are variable.
public void add()//template method that uses method steps to define the sequence
{
int numArray[]=getNumber();
int result=numArray[0]+numArray[1];
manageResult(result);
}
public abstract int[] getNumber();//stub method representing.
public void manageResult(int r);//variable step.
}
46.Without using template insert, update, delete and select data Example
46.1.Introduction:-This example provide the difference between template design pattern and simple design pattern to insert , update, delete and select all data from the data base.
try{Connection con=ConnectionProvider.getConnection();Scanner in=new Scanner(System.in);System.out.println("Enter the id:");
int id=in.nextInt(); in.nextLine();
System.out.println("Enter the name:"); String name=in.nextLine(); System.out.println("Enter the job:"); String job=in.nextLine(); System.out.println("Enter the salary:"); int salary=in.nextInt(); in.nextLine();
PreparedStatement stmt=con.prepareStatement("update emp set name=?, job=?, salary=? where id=?");
public static void main(String[] args) {Scanner in=new Scanner(System.in);EmpDao dao=new EmpDao();while(true){System.out.println("Enter the id:");
int id=in.nextInt(); in.nextLine(); System.out.println("Enter the name:"); String name=in.nextLine(); System.out.println("Enter the job:"); String job=in.nextLine(); System.out.println("Enter the salary:"); int salary=in.nextInt(); in.nextLine(); Emp emp=new Emp(id,name,job,salary); dao.save(emp); System.out.println("Insert continue write yes/no:"); String reg=in.nextLine(); if(reg.equals("no")) break;
}System.out.println("You are successfully insert data...");
}}
UpdateTest.java
package org.r4r;
public class UpdateTest {
public static void main(String[] args) {
System.out.println("Update Emp Object.....");EmpDao dao=new EmpDao();Emp emp=new Emp();dao.update(emp);System.out.println("You are successfully update");
}
}
DeleteTest.java
package org.r4r;
public class DeleteTest {
public static void main(String[] args) {System.out.println("Deleted Emp Object.....");EmpDao dao=new EmpDao();Emp emp=new Emp();dao.delete(emp);System.out.println("You are successfully delete");
}
}
OutPut:-
InsertTest
Enter the id:1005Enter the name:Mukund SinghEnter the job:Java DeveloperEnter the salary:25000Insert continue write yes/no:noYou are successfully insert data...
UpdateTest
Update Emp Object.....Enter the id:1005Enter the name:Bal MukundEnter the job:Spring DeveloEnter the salary:30000You are successfully update
DeleteTest
Deleted Emp Object.....Enter the id:1005You are successfully delete
47.Insert,update,delete and select data using Spring Template
47.1.Introduction:-This example provide the facility to insert, update, delete and fetch data using spring template design pattern then provide connect to JDBC.
System.out.println("Enter the id: ");int id=in.nextInt();stmt=con.prepareStatement
("update emp set name=?,job=?,salary=? where id=?");stmt.setInt(4, id);stmt.setString(1, e.getName());stmt.setString(2, e.getJob());stmt.setInt(3, e.getSalary());
public static void main(String[] args) {ApplicationContext ctx=new
ClassPathXmlApplicationContext("applicationContext.xml");System.out.println("Obtaining dao from IOC container");EmpTemplateDao dao=(EmpTemplateDao)ctx.getBean("dao");
public static void main(String[] args) {ApplicationContext ctx=new
ClassPathXmlApplicationContext("applicationContext.xml");System.out.println("Obtaining dao from IOC container");EmpTemplateDao dao=(EmpTemplateDao)ctx.getBean("dao");System.out.println("Dao update the Emp Object");Emp e=new Emp(222,"Mukund Singh","Software Engineer",55000);dao.update(e);System.out.println("Emp object Update");
public static void main(String[] args) {ApplicationContext ctx=new
ClassPathXmlApplicationContext("applicationContext.xml");System.out.println("Obtaining dao from IOC container");EmpTemplateDao dao=(EmpTemplateDao)ctx.getBean("dao");System.out.println("Deleting Emp Object");Emp e=new Emp();dao.delete(e);System.out.println("Emp object delete");
System.out.println("Obtaining dao from IOC container");EmpTemplateDao dao=(EmpTemplateDao)ctx.getBean("dao");System.out.println("Fetching Emp Objects");List<Emp> list=dao.getAllEmp();Iterator<Emp> itr=list.iterator();System.out.println("Following objects are fetched.");while(itr.hasNext()){
Obtaining dao from IOC containerDao saved the Emp ObjectEmp object SaveUpdateTest Result:-Obtaining dao from IOC containerDao update the Emp ObjectEnter the id: 102Emp object UpdateDeleteTest Result:-Obtaining dao from IOC containerDeleting Emp ObjectEnter the id: 102Emp object deleteSelectTest Result:-Obtaining dao from IOC containerFetching Emp ObjectsFollowing objects are fetched.
103 Amar Marketing 25000101 ArshRaj Develo 25000100 Amit Engi 25000
48.Spring MVC Implementation
48.1.Introduction:-In Spring MVC implementation the controller is an application component. Which is responsible for processing the request. It does not controlled the workflow of request processing as done by struts controller.
Workflow of request is controlled by front controller which is implemented by servlet name "DispatcherServlet" is provides a single entry point in to the application.
48.2.Model View Controller (MVC):-
Model:-Model component represent a data for spring MVC usually a map of model object is used as Model component.
View:-View is a generic component of the framework which is responsible for presenting data to the end user. Multiple implementation of view are provided the framework to support different presentation technique.
Controller:-Controller component provide the facility to change the state and flow the data. Controller component is responsible for the controlled the workflow of the web application in the spring framework.
48.3.How can implement spring MVC:-
Following steps are required to used spring MVC implementation:-
Step 1:-First select the web project in our IDE and add the capability of spring framework (it means that add the jar file). The following jar file are add before implement the spring MVC application
1.Spring 2.5 core Library
2.Spring 2.5 web Library
Step 2:-Servlet entry is to be made in web.xml file for DispatcherServlet class
<servlet-name>login</servlet-name> <url-pattern>*.spring</url-pattern> </servlet-mapping></web-app>Step 3:-Define in xml file to specified a mapping requested url and controller of spring application. This file is conventionally name as follows Example:-ServletName-servlet.xmlStep 4:-If DispatcherServlet is assign "frontController" name in web.xml then this file must be named as"frontController-servlet.xml" Step 5:-The file "frontController-servlet.xml" used the bean element to mapped request url and controller ClassExample:
<bean id="loginModel" class="org.r4r.LoginModel"/>Step 6:-Define controller class , Controller is a subclass of AbstractController class. AbstractController class provides anabstract method name handleRequestInternal(HttpServletRequest request,HttpServletResponse response);
which is invoked each time a request of the controller received. This method returned a ModelAndView object.
9.Example of Spring MVC Implementation
49.1.Introduction:-In Spring MVC implementation the controller is an application component. Which is responsible for processing the request. It does not controlled the workflow of request processing as done by struts controller.
Workflow of request is controlled by front controller which is implemented by servlet name "DispatcherServlet" is provides a single entry point in to the application.
HttpServletResponse response) throws Exception {PrintWriter out=response.getWriter();out.println("This view is generated by spring view....");out.println("First Name:-\t"+model.get("firstName"));out.println("Last Name:-\t"+model.get("lastName"));out.close();
50.1.Introduction:-In the Spring framework provide the facility to view the result in front of User through the "InternalResourceViewResolver" class. The Spring framework provide this class to present the information which processing after the controller of the Spring MVC pattern.
51.How can integrate Struts 2.x and Spring Framework
51.1.Introduction:-The Struts 2.x is the web application framework in Java Technology, this framework provide the concept of Model View Controller (MVC) and Interceptor to develop the web application. The Spring framework provide the facility to integrate with other framework and Developed the application in java. This tutorial provide the facility how can integrate between Spring framework and Struts 2.x .
51.2.How can integrate Spring framework and Struts 2.x:-
Following steps are required to integrate Spring framework and Struts 2.x framework:-
Step 1:-First select the web project in our IDE and add the capability of spring 2.5 and Struts 2.x (it means that add the jar file ).