Core Spring and MVC
Core Spring and MVC
SPRING
COURSE MATERIAL
BY
NAGOOR BABU
{SPRING
Volume -1} 1
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3.Core Module
1.Introduction
2.IOC Containers
1. BeanFactory
1.XmlBeanFactory
2. Resources
1.ByteArrayResource
3
2.FileSystemResource
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
7.webSocket scope
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4.ContextClosedEvent
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3.SpEL Variables
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
5.Spring ORM
1.Introduction
2.Hibernate Integration with Spring
1.Hibernate Introduction
2.Hibernate Application Development
3.Spring with Hibernate Integration.
3.JPA Integration with Spring
1.JPA Introduction.
9
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1.Before Advice
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
7.Spring Transactions
1.Introduction
2.Transaction Attributes
3.Isolation Levels
4.Programaatic Based Transactions
5.Declarative Based Transactions.
6.Annotation Based Transactions
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
13
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
{CORE MODULE}
14
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
15
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
16
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
script functions.
5.User interface will provide very good environment to send different request types from
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. It is heart of the enterprise application, it can be used to define and execute all business
rules and regulations which are required by the clients actually.
2. In Enterprise Application development, to prepare
Business Processing layer we have to use a separate logic called as "Business Logic".
3. To provide Business Logic we have to use the technologies like Servlets, EJBs, DAOs, .....
1. This layer is bottom most layer in enterprise applications, it will provide very good
environment to interact with databases in order to perform persistence operations.
2. To prepare this layer in enterprise applications we have to use a separate logic called as
"Persistence Logic".
3. To provide persistence logic we have to use a set of technologies like JDBC, EJBs-Entity
Beans, Hibernate ,....
System Arch.:
To define level or height of the enterprise applications we have to use System Arch.
EX:
1-Tier Arch.
2-Tier Arch.
3-Tier Arch.
n-Tier Arch.
18
1-Tier Arch.
Page
1. In 1-Tier Arch, we have to prepare and execute the complete enterprise application with
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
19
2-Tier Arch:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. IN 2-Tier Arch, we have to distribute the complete enterprise application over two
machines.
2. In 2-Tier Arch, Tier-1 machine is able to manage presentation logic and Business Logic,
Tier-2 machine is able to manage Persistence Logic.
3. In 2-Tier Arch, we are able to get loosely coupled design when compared with 1-Tier
Arch, because, Persistence layer is separated from Presentation layer and Business Layer.
4. In 2-Tier Arch, database components are shared to client applications, so that,
sharability and Reusability are increased.
5. 2-Tier Arch will provide multi user environment to access application.
Note: If want to use 2-Tier arch for web applications then we have use Tier-1 is for client , it
has to manage presentation layer and Tier-2 is for Server , it has to manage Business Layer
and Persistence Layer.
3. 3-Tier Arch:
--> This arch will propose to use three machines in order to execute the complete
enterprise application.
--> In 3-Tier Arch, we will provide Presentation Layer at Tier-1 Machine, Business Layer at
Tier-2 machine and Persistence layer at Tier-3 machine.
20
--> 3-Tier arch will provide more more loosely coupled design to design applications. -
Page
-> 3-Tier Arch will provide Multi User environment, it will improve sharability and
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Q)What are the differences between Web Applications and Distributed Applications?
Ans:
----
1. Web Application is a Client-Server Application, where the complete application logic is
distributed over Server machine.
21
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. The main intention of Web applications is to generate dynamic response from server.
4. Web applications are executed by both web servers and application servers.
5. Web application is the collection of web components like servlets, jsps,... , which are
executed by web containers.
Distributed Application is the Collection of distributed components like EJBs, which are
executed by EJB Container.
To prepare web applications, SUN Microsystems has provided the following Modeled Arch.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1 .Model-I Arch.
2. Model-II Arch.
1. Model-I Arch.
In Model-I Web Application Arch, we will use a JSP page as controller as well as
Presentation part and a Java Bean component is acting as Model Component.
In Model-I web application Arch, a JSP page is acting as Controller to controll the complete
web application, so that, Model-I Web application Arch is also called as "Page-Centric
Arch".
In Model-I web application Arch, a JSP page is taking responsibility to take requests from
client, so that, Model-I web application Arch is also called as "JSP Front".
IN Model-I web application Arch, we will use JSP pages as Controller and for presentation,
there is no clear cut seperation between Controller logic and presentation logic, it will provide
tightly coupled design in web applications, it is not suggestible in web applications.
In Model-I web applicatio Arch., a JSP page is acting controller, to perform controller
functionalities the existed JSP features are not sufficient, where it is required to write java
code inside JSP pages, it is against to JSP rules and regulations.
In Model-I web applicatio Arch., a JSP page is acting controller, to perform controller functionalities the
existed JSP features are not sufficient, where it is required to write java code inside JSP pages, it is against
to JSP rules and regulations.
23
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Model-II Arch :
In Model-II web application Arch, we will use a Servlet as controller, a set of JSP pages as
View part and Java bean, DAO, JDBC,... as used as Model Components.
In Model-II Arch, a servlet is acting as controller to control the complete web applications,
so that, Model-II web Arch is called as "Servlet-Centric Arch".
In Model-II Arch, a servlet is taking responsibility to take all the requests from Client , so
that, Model-II Arch is also be called as "Servlet Front Arch".
Note: Model-II Arch is an implantation of MVC Arch, on the basis of Model-II Arch only the
web frameworks like Struts, JSF,... are designed.
24
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. MVC is a design pattern, it will define a standard template to prepare web applications.
3. In MVC based web applications, we must use a Servlet as controller and a set of JSP
pages as view part.
4. In MVC based web applications, we must provide single controller per application.
5. In MVC based web applications, Controller component must take all the requests which
are coming from clients and View part must take the responsibility to generate response to
client.
6. IN MVC based web applications, both controller and view part are not responsibile to
interact with database, they have to interact with database through Model component.
7. In MVC based web applications, Controller is able to set data to model component, not
to get data from model component and View part is able to get data from model
component , not to set data to Model component.
8. IN MVC based web applications, we can provide any no of pages as view part, but we
must provide all the pages as Java code less.
9. IN MVC based web applications, we can provide no of pages as view part, where we
must not provide page-to-page communication directly, where we have to provide page-
controller-page communication.
enterprise application.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In the above situation, some third party organizations like Apache Software
Foundations, Soft Tree, .... has provided the common 70% of the implementation in the
form of their own products called as "Frameworks".
Framework is a pre fabricated Software components that programmer can reuse, share and
customize inorder to simplify enterprise application development.
Framework is a semi implemented application, it will provide very good environment to
prepare enterprise applications as per developers convenience.
Framework is the Collection of Tools and APIs, it will provide very good environment
to prepare enterprise applications in simplified manner.
1. Web Frameworks
26
Web frameworks will provide environment to design and execute only web applications.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2. Application Frameworks
Application Frameworks will provide very good environment to prepare all the types of
applications like Standalone Applications, Web Applications, Distributed Applications,.....
EX: Spring
Q)What are the differences between Struts, JSF and Spring?
Ans:
1. Struts and JSF are web frameworks, which we will provide very good environment to
prepare and execute web applications only.
2. Struts and JSF are designed on the basis of only MVC design pattern.
In Spring , only WEB Module is designed on the basis of MVC, SPriong is using no of other
design patterns like IOC[Dependency Injection], Locater design patterns, Creational Design
Patterns, Decorator Design pattern,.....
3. Struts is controller layered framework, it has very good focus on controller layer in
MVC.
JSF is is view layered Framework, it has very good focus on View layer in
MVC. Spring Framework has provided very good support for all Controller Layer, Model
Layer and View Layer.
4. In Enterprise Application Development, Struts and JSF are used to prepare mainly
Presentation layer.
27
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Spring Framework is providing very good support for all basic services like I18N,
Validations, Exception Handling ... and the Middleware services like JAAS, JNDI, JTA, Java
Mail, JMS, JCA......
6. Struts and JSF are not modularized Frameworks, to prepare any application in Struts
and JSF we have to load all the jar files irrespective of their utilization.
7. Struts and JSF are more API dependent; they are not having POJO/POJI kind of
implementations.
8. Due to the above reasons, debugging and testing are difficult in Struts and JSf.
10. Struts and JSF are not providing any predefined support to integrate the other
applications like JDBC, EJBS, Hibernate, JPA, RMI,....
Spring has provided very good predefined support to integrate the other
applications like JDBC, EJBS, Hibernate, JPA, RMI,....
28
Page
11. Struts and JSF are allowing the basic view related technologies like Html, JSp, ..... to
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Spring has provided very good Aspect Oriented Programming to prepare Applications.
Spring History:
1.Home: Interface1
2.Author: Mr. Rod Janson
3.Objective: To simplify and Accelerate the complete Enterprise Applications.
4.Type: Open Source Software.
5.Type of Framework: Application Framework.
6.Initial Version: Spring1.0[Oct, 2004]
7.Used Version: Spring3.x[Dec, 2014]
8.Latest Version: Spring4.3.8[April, 2017]
9.Website: http://spring.io
10.Designed on: Java[JAVA SE API, Servlets API]
11.Compatibility:Supported by All IDEs and all Servers
12:Designi Tool: STS[Spring tool Suit][Designed on the top of Eclipse]
Spring Modules:
Spring1.x version:
29
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Spring3.x Version:
30
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Module5.x Version
31
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
It is fundamental module in Spring Framework; it has provided basic foundation for all
other modules of spring framework.
This module is able to provide the features like IOC Containers, Beans, Dependency
Injection.....
In the above context, to improve sharability and Reusability we have to provide loosely
coupled design , to get loosely coupled design we have to apply Aspect Oriented
Programming.
In Aspect Oriented Programming, we will declare each and every service as an aspect and
we will inject these aspects in Business Logic at runtime.
JDBC/DAO Modules:
The main intention of this module is to interact with database from Spring
application inorder to perform database operations with JDBC Persistance mechanism.
JDBC/DAO modules are able to abstract common JDBC implementation inorder to simplify
Database interaction from spring applications by providing template classes.
EX:
In JDBC, if we want to interact with database then we have to use the following steps.
32
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In the above JDBC Steps, Load and Register Driver, Establish Connection and Create
Statement and close the Connection are vary common in all the JDBC applications, here
Spring JDBC/DAO modules are able to abstract the commonly used steps and giving option
to the developers to provided variable part , that is, Executing Sql queries .
Spring DAO and JDBC modules are having their own Exception Classes hierarchy to expose
the exception details.
Spring DAO/JDBC modules are converting the JDBC generates checked exceptions to Spring
defined Unchecked Exceptions by using Exceptions Re-Throwing Mechanism.
EX:
try{
---Exception-1 ----JDBC Checked Exception
}
catch(Exception_Name e){
----Exception-2---Spring Unchecked Exception
33
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ORM is the mapping between a table, properties or columns and primary key column
with the respective bean component provided Bean class name, ID property, normal
properties,
ORM has define a set of rules and regulations to provide mapping between Object Oriented
Data Model and Relational Data Model in order to achieve data persistency.
EX:
Configuration cfg=new Configuration();
cfg.configure();
sf.close();
Page
cfg.close();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In the above Hibernate Application steps, Create Configuration class object, Creation
SessionFactory object , create Session object and close SessionFactory and Configuration
steps are very common in all hibernate applications, in this case, Spring ORM module is
able to abstract all the common instructions in order to simplify Data persistence in
enterprise applications.
Spring ORM module has provided its own Exceptions hierarchy to expose behalf of the
under lying Persistence mechanism like Hibernate, JPA,.... provided checked exceptions.
JAVA EE/Context/Remoting:
The main intetion of this module to integrate Spring applications with the
diustributed tech applications like EJBs, RMI,.... it able to get moddleware services like JNDI,
JTA, JAAS,.... from J2EE .
WEB/WEB-MVC Modules:
WEB Module has provided very good environment to integrate other MVC based
framework applications like Struts, JSF, XWork2,.....
Test:
Spring Framework has provided its own testing environment to test the enterprise
applications by the developers[Unit Testing] in their own way in the form of Test module.
Note: Spring framework has provided Test module right from its Spring3.x version.
Instrumentation:
35
source code.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Spring Framework has provided Messaging module along with its Spring4.x version to
provide Messaging Services what JMS is providing previously as part of J2EE.
Note: When we perform any transactions in bank application , we are able to recieve
mobile updations, in this context, if our mobile device is not ready to recieve messages
WEB Module has provided very good environment to integrate other MVC based framework applications
like Struts, JSF, XWork2,.....
then we have to keep the respective message in Messaging Containier or JMS Server to
send the respective message when the target machine / device is ready.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note:
Prepare User Defined Library[Spring4.1.6_Lib_New] only one time and use the same
for all Spring applications, not required to prepare for each and every application.
The main intention of Bean classes in Spring applications is to manage properties and
their setXXX() and getXXX() methods and some other Business Methods.
To prepare Bean classes in Spring applications we have to use the following Guidlines.
a) Bean classes must be POJO classes, they must not extend or implement any
predefined Library excepr java.io.Serializable marker interface.
b) Bean must be declared as "public" , "Non-abstract" and "non-final".
---->The main intention of declaring bean class as "public" is to make available bean
class scope to IOC Container inorder to create objects.
---->The main intention to declare bean class as "Non-abstract" is to allow to create
object .
---->The main intention to declare bean classes as "Non-final" is to extend one bean
class to another bean class inorder to improve reusability.
c) In Bean classes, we have to declare all properties as "private" and all behaviours as
"public", it will improve "Encapsulation".
38
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To create bean class in Eclipse IDE, we have to use the following steps.
1. Right Click on "src" flder.
2. Select "New".
3. Select "Class".
4. Provide package name and class name.
package name: com.durgasoft.beans
class name: HelloBean
5. Click on "Finish" button.
6. As per the requirement provide properties and setXXX() and getXXX() with the
following steps.
a) Declare variables manually.
b) Right Click and Select "Source".
c) Select "Generate Getters and Setters".
d) select "Select All" button.
e) Click on "OK" button.
7. Provide Business Methods as per the requirement.
EX: HelloBean.java
--------------------
package com.durgasoft.beans;
public class HelloBean {
public String sayHello(){
return "Hello User!";
}
}
The main intention of Bean COnfiguration File is to provide all the bean
39
components configuration details like logical name, fully qualified names of the bean
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Bean Configuration File is an XML file, it will use the following XML tags to configure bean
classes.
Where "id" attribute will take identity name or logical name to the Bean component.
Where "name" attribute will take fully qualified name of the bean class.
To prepare bean confguration file in Eclipse IDE we have to use the following steps.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To prepare Test application in Eclipse IDE we have to use the following steps.
a) Right Click on "SRC".
b) Select "New".
c) Select "Class".
d) Provide the following details.
41
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX: Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.HelloBean;
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new ClassPathXmlApplicationContext
("/com/durgasoft/cfgs/spring_beans_config.xml");
HelloBean bean=(HelloBean) context.getBean("hello");
System.out.println(bean.sayHello());
}
}
In this approach, we have to set value to bean properties programatically from Test
42
application.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
Test.java
package com.durgasoft.test;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
import com.durgasoft.beans.HelloBean;
In the above approach, we have to recompile the Test application when we change
messages, it is not suggestible in application development. To overcome this problem we
have to use beans configuration file to prepare messages inorder to send to Bean object.
To provide messages to the bean properties through their setXXX() methods from bean
configuration file we have to use the following tag in beans configuration file.
</bean>
----
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
app2:
-----
HelloBean.java
----------------
package com.durgasoft.beans;
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"
45
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
----------
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.HelloBean;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1.Installation Process:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
User.java
48
package com.durgasoft.beans;
public class User {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
setXXX()
getXXX()
}
6) Prepare COnfiguration File:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
spring_beans_config.xml
<beans>
<bean id="user" class="com.durgasoft.beans.User">
<property name="uname" value="Durga"/>
<property name="uqual" value="MTech"/>
<property name="uage" value="28"/>
<property name="uaddr" value="Hyd"/>
<property name="uemail" value="[email protected]"/>
<property name="umobile" value="91-9988776655"/>
</bean>
</beans>
Test class already created at the time of creating project, where provide
application logic.
Test.java
----------
package com.durgasoft.test;
import com.durgasoft.beans.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("/com/durgasoft/cfgs/spring_beans_config.xml");
User user=(User)context.getBean("user");
user.display_User_Details();
50
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The main intention of IOC Container is to read bean configurations from configuration
file , creating Bean objects and Providing bean Objects to Spring applications.
1. BeanFactory
2. ApplicationContext
1. BeanFactory
-->To represent BeanFactory IOC Container, SPring framework has provided an interface
in the form of
"org.springframework.beans.factory.BeanFactory".
-->If we want to use BeanFactory IOC Container in Spring applications then we have to
use the following steps.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
-->To represent Resource object, Spring Framework has provided a predefined interface
in the form of
"org.springframework.core.io.Resource"
-->For Resource interface, Spring Framework has provided the following implementation
classes.
1. org.springframework.core.io.ByteArrayResource:
--> It able to represent all the beans configuration details which are available in the form
of byte[].
2. org.springframework.core.io.FileSystemResource:
--> It able to get all the beans confguration details which are available in the form of a file
in our system
hard disk.
3. org.springframework.core.io.ClassPathResource:
--> It able to get all the beans configuration details which are existed at "classpath"
environment variable
refered locations.
4. org.springframework.core.io.InputStreamResource:
52
--> It able to get all the beans configuration which are existed in the form of InputStream.
5. org.springframework.core.io.UrlResource:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
6. org.springframework.web.context.support.ServletContextResource:
--> It able to get all the beans configuration details which are existed in ServletContext.
--> It will be used in spring web applications.
7. org.apringframework.web.portlet.context.PortletContextResource:
--> It able to get all the beans configuration details which are existed in PortletContext.
--> It will be used in spring web applications designed on the basis of portlets.
EX:
Resource res=new ClassPathResource("beans.xml");
To get Bean object from BeanFactory we have to use the following method.
public Object getBean(String id_Name)
EX:
HelloBean bean=(HelloBean)factory.getBean("hello");
Example:
HelloBean.java
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloBean" class="com.durgasoft.beans.HelloBean"/>
</beans>
Test.java
----------
package com.durgasoft.test;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.durgasoft.beans.HelloBean;
54
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. It will take bean configuration file name and location from Resource object.
2. It will search for the respective bean configuration file at the specified location.
3. If the respective bean configuration file is available then Beanfactory container will
load that xml file to the memory.
4. After XML file loading, BeanFactory Container will parse that xml file, that is, it will
check all the tags in XML file are provided properly or not, all attributes are available
properly or not.
5. After the XML file parsing, BeanFactory Container will read data from Beans
configuration file and stores in Resource object.
After getting BeanFactory Object, when we access getBean(-) method then BeanFactory
will perform the following actions.
1. BeanFactory will search for the respective Bean configuration in Resource object on
the basis of the provided identity.
2. If any bean configuration is identified in Resource object on the basis of the
provided identity then BeanFactory container will take the respective bean class
name and its location.
3. BeanFactory Container will search for the respective bean class at the specified
55
location, if it is available then BeanFactory Container will load all the bean class
bytecode to the memory.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ApplicationContext:
1.ClassPathXmlApplicationContext:
--> It able to get all the beans configuration details from confguration file which is existed
in application classpath.
2.FileSystemXmlApplicationContext:
--> It able to get all the beans configuration details from Configuration file which is
existed at our system harddisk.
56
3.WebXmlApplicationContext:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
HelloBean.java
--------------
package com.durgasoft.beans;
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloBean" class="com.durgasoft.beans.HelloBean"/>
</beans>
Test.java
57
package com.durgasoft.test;
import org.springframework.beans.factory.xml.XmlBeanFactory;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
import com.durgasoft.beans.HelloBean;
1. It will take bean configuration file name and location from Container class constructor.
2. It will search for the respective bean configuration file at the specified location.
3. If the respective bean configuration file is available then ApplicationCntext container
will load that xml file to the memory.
4. After XML file loading, ApplicationContext Container will parse that xml file, that is, it
will check all the tags in XML file are provided properly or not, all attributes are available
properly or not.
5. After the XML file parsing, ApplicationContext Container will read data from Beans
configuration file.
6. If any bean configuration is identified in beans configuration file the
ApplicationContext container will take beans classes and their locations.
7. ApplicationContext Container will search for the respective beans at the specified
locations, if they are available then IOC Container will load all the bean classes bytecode
58
to the memory.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In the above context, if we access getBean("--") method over Container reference then
ApplicationContext Container will search for the Bean object on the basis of the provided
bean identity , if it is available then AppliationContext Container will return Bean object.
2) BeanFactory is not supporting to integrate AOP services like Security, JTA,... to the
spring applications.
3)BeanFactory is not suitable for web applications which we are going to prepare on the
basis of Spring web module.
ApplicationContext is suitable for the web applications which we want to prepare on the
basis of Spring web module.
59
4)BeanFactory is able to prpare Singleton objects when we send first request for bean,
that is, Lazy Instantiation/Initialization.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ApplicationContext is supporting almost all the Spring scopes like Singleton, Prototype,
request, session, globalSession, webSocket,...
a) Bean classes must be POJO classes, they must not extend or implement any
predefined Library except java.io.Serializable marker interface.
----> The main intention to declare bean classes as "Non-final" is to extend one bean
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
c) In Bean classes, we have to declare all properties as "private" and all behaviours as
"public", it will improve "Encapsulation".
d) If we want to provide any constructor in bean class then provide a constructor , it must
be 0-arg constructor and "public" constructor, because, IOC Container will search and
execute public and 0-arg constructor while instantiating bean.
If we want to use Beans in Spring applications then we must configure that bean classes
in spring beans configuration file , because, IOCContainer will recognize and create Bean
objects by getting bean class details from beans configuration file only.
1. XML Configuration
2. Java Based Configuration
3.Annotations Configuration
1. XML Configuration
To provide beans configurations in beans configuration file we have to use the following
xml tags.
<beans>
</bean>
</beans>
Where <bean> tag is able to provide configuration details of a particular bean class.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Q)What is the difference between "id" attribute and "name" attribute in <bean> tag?
Ans: 'id' attribute is able to take exactly one identity to the bean object, it will not allow
more than one identity.
'name' attribute in <bean> tag is able to allow more than one identity name to the bean
object, where in multiple values only first value is treated as th actual bean identity and
the remaining names are alias names for the bean object. In this context, while providing
alias names to the bean object we have to use either ',' or ';' or [space] as
delimiter[seperator].
EX1:
<beans>
<bean id="bean1" class="com.durgasoft.beans.MyBean"/>
</beans>
MyBean mb=(MyBean)ctx.getBean("bean1");
Status: Valid.
EX2:
<beans>
<bean id="bean1 bean2 bean3" class="com.durgasoft.beans.MyBean"/>
</beans>
MyBean mb=(MyBean)ctx.getBean("bean1");
Status: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean
named 'bean1' is defined
Note: SImilarily the following cases are also be invalid.
62
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX3:
<beans>
<bean name="bean1" class="MyBean"/>
</beans>
MyBean mb=(MyBean)ctx.getBean("bean1");
Status: Valid
EX4:
Note: It is possible to use both 'id' attribute and 'name' attribute in single <bean> tag.
EX5:
Note: It is possible to provide bean alias names explicitly from out side of the bean
definition in configuration file by using <alias> tag.
63
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX6:
<beans>
<bean name="bean1" class="MyBean"/>
<alias name="bean1" alias="bean2"/>
<alias name="bean2" alias="bean3"/>
</bean>
</beans>
MyBean mb1=ctx.getBean(bean1); --> Valid
MyBean mb2=ctx.getBean(bean2); --> Valid
MyBean mb3=ctx.getBean(bean3); --> Valid
Bean Scopes:
In J2SE applications, we are able to define scopes to the data by using the access
modifiers like public, protected, <default> and private.
Similarily, in Spring framework to define scopes to the beans spring framework has
provided the following scopes.
1. singleton Scope:
64
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
This approach will return the same bean object for every time requesting bean object.
When we request bean object first time then IOCContainer will create bean object really
and it will be stored in Cache memory, then , every time accessing bean object ,
IOCContainer will return the same bean object reference value with out creating new
Bean objects.
EX:
beans.xml
<beans>
<bean id="bean1" class="com.durgasoft.MyBean" scope="singleton"/>
<bean id="bean2" class="com.durgasoft.MyBean" scope="singleton"/>
</beans>
System.out.println(ctx.getBean("bean1"));//MyBean@a111
System.out.println(ctx.getBean("bean1"));//MyBean@a111
System.out.println(ctx.getBean("bean2"));//MyBean@a222
System.out.println(ctx.getBean("bean2"));//MyBean@a222
2. prototype Scope:
EX:
beans.xml
---------
65
<beans>
<bean id="bean1" class="com.durgasoft.MyBean" scope="prototype"/>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
System.out.println(ctx.getBean("bean1"));//MyBean@a111
System.out.println(ctx.getBean("bean1"));//MyBean@a222
System.out.println(ctx.getBean("bean2"));//MyBean@a333
System.out.println(ctx.getBean("bean2"));//MyBean@a444
3. requestScope:
This scope is not usefull in Standalone Applications[Spring Core MOdule], it will be used
in Web applications which are prepared on the basis of Spring Web module.
RequestScope is able to create a seperate bean object for each and every request object.
4. sessionScope:
This Scope will be used web applications which are prepared on the basis of Spring web
module and it is not applicable in Standalone Applications.
sessionScope allows to create a seperate bean object for each and every Session object in
web applications.
5. globalSession Scope:
This scope is not usefull in standard applications, it is usefull in portlet applications which
are prepared on the basis of SPring web module.
globalSession scope allows to create a seperate bean object for each and every portlet
Session.
6. application Scope:
ApplicationScope allows to create a seperate bean object for each and every
ServletContext object.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
This scope is usefull in web applications which are prepared on the basis of spring web
module.
websocket scope allows to create a seperate bean object for single websocket lifecycle.
Note: Spring Framework has provided environment to customize the existed scopes ,
but, it is not suggestible. Spring framework has provided environment to create new
scopes in spring applications.
To define and use custom scopes in Spring Framework we have to use the following
steps.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: In the following example, we have defined threadScope as user defined scope,
that is, it able to create a seperate bean object for each and every thread.
Example:
CustomThreadLocal.java
package com.durgasoft.scopes;
import java.util.HashMap;
68
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ThreadScope.java
package com.durgasoft.scopes;
import java.util.Map;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
@Override
public String getConversationId() {
69
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public void registerDestructionCallback(String arg0, Runnable arg1) {
// TODO Auto-generated method stub
@Override
public Object remove(String name) {
Object obj = scope.remove(name);
return obj;
}
@Override
public Object resolveContextualObject(String arg0) {
// TODO Auto-generated method stub
return null;
}
HelloBean.java
package com.durgasoft.beans;
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.HelloBean;
import com.durgasoft.scopes.ThreadScope;
System.out.println(bean4.sayHello());
System.out.println(bean5.sayHello());
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
</beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
org.springframework.context.annotation.@Configuration
--> It able to represent a class as configuration class.
org.springframework.context.annotation.@Bean
--> It will be used at method to represent the return object is bean object.
Example:
HelloBean.java
package com.durgasoft.beans;
}
public String sayHello() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HelloBeanConfig.java
package com.durgasoft.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.durgasoft.beans.HelloBean;
@Configuration
public class HelloBeanConfig {
@Bean
public HelloBean helloBean() {
return new HelloBean();
}
}
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.durgasoft.beans.HelloBean;
import com.durgasoft.config.HelloBeanConfig;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Bean Lifecycle:
In spring framework applications, when IOC Container recognizes all the beans definitions
in beans configuration file then IOC Container will execute that bean by using the
following lifecycle actions.
When IOC Container recognized fully qualified names of the bean classes in beans
configuration file then IOC Container will load the specified bean class byte code to the
memory. To load bean class bytecode to the memory, IOC Container will use the
following method.
2. Bean Instantiation
75
In Spring applications, after loading bean class bytecode to the memory, IOC Container
will create object for the bean class.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to create bean objects by using constructors then we must provide 0-arg
costructor in bean class irrespective of bean class constructor scopes.
Note: In Bean class , if we provide parameterized constructor then IOC Container will rise
an exception.
EX:
HelloBean.java
applicationContext.xml
<beans>
<bean id="hello" class="HelloBean"/>
76
</beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
class Test{
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
HelloBean bean=(HelloBean)context.getBean("hello");
System.out.println(bean.sayaHello());
}
}
In this approach, first we have to define static factory method in Bean class and we have
to configure that static factory method in bean defination in beans configuration file.
EX:
HelloBean.java
applicationContext.xml
<beans>
77
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
class Test{
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
HelloBean bean=(HelloBean)context.getBean("hello");
System.out.println(bean.sayaHello());
}
}
In this approach, we have to define a seperate factory class with instance factory method
and we have to configure factory class as bean in beans configuration file then we have
to configure factory class and factory method in the original bean class definition by using
"factory-bean" and
"factory-method" attributes.
EX:
HelloBeanFactory.java
HelloBean.java
78
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
<beans>
<bean id="hello" class="HelloBean"
factory-method="getBeanInstance"
factory-bean="factory" />
<bean id="factory" class="HelloBeanFactory"/>
</beans>
Test.java
class Test{
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
HelloBean bean=(HelloBean)context.getBean("hello");
System.out.println(bean.sayaHello());
}
}
Bean Initialization and Bean Destruction:
As part of Beans lifecycle, IOC Container has to perform Beans initialization after the
Bean Instantiation and IOC Container has to perform Bean destruction after executing the
business logic or at the time of shutdown the IOC Container.
There are three ways to perform Beans initialization and destruction in Spring
Framework.
79
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In this approach, we have to define user defined initialization and destruction methods
with any name and we have to configure that user defined methods in beans definitions
in beans configuration file by using "init-method" and "destroy-method" attributes in
<bean> tag.
EX:
WelcomeBean.java
package com.durgasoft.beans;
applicationContext.xml
<beans>
<bean id="wel" class="com.durgasoft.beans.WelcomeBean"
80
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.WelcomeBean;
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
WelcomeBean bean=(WelcomeBean)context.getBean("wel");
System.out.println(bean.sayWelcome());
context.registerShutdownHook();
}
}
Note: This method will be executed by the container after executing all the setXXX()
methods of bean class by ApplicationContext.
EX:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.beans;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
applicationContext.xml
<beans>
82
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.WelcomeBean;
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
WelcomeBean bean=(WelcomeBean)context.getBean("wel");
System.out.println(bean.sayWelcome());
context.registerShutdownHook();
}
}
@PostConstruct annotation will make a method to execute by the IOC Container while
performing Beans iniitalization.
@Predestroy annotation will make a method to execute by the IOC Container while
performing Bean Destruction.
EX:
Welcome.java
package com.durgasoft.beans;
83
import javax.annotation.PostConstruct;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
<beans >
<context:annotation-config/>
<bean id="wel" class="com.durgasoft.beans.WelcomeBean">
<property name="message" value="Welcome To Durgasoft"/>
</bean>
84
</beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
Note: IN general, in spring framework applications, we are able to use either of the above
three approaches to perform beans initialization and destruction, we are not using all
three approaches at a time. If we use all the above three approaches in single bean theni
IOC Container will execute the above three approaches provided intialization methods
and destruction methods in the following order.
Initialiazation order:
Destruction Order:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
Welcome.java
spring_beans_config.xml
86
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
In the above context, we are able to reuse one bean configuration details in another bean
configurations like normal java classes inheritance inorder to improve reusability and
inorder to reduce no of configurations in spring configuration file by declaring parent and
chaild beans configurations.
EX:
WishBean.java
87
package com.durgasoft.beans;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
setXXX()
getXXX()
}
HelloBean.java
package com.durgasoft.beans;
public class HelloBean {
private String wish_Message;
private String name;
setXXX()
getXXX()
88
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
WelcomeBean.java
package com.durgasoft.beans;
public class WelcomeBean {
private String wish_Message;
private String name;
setXXX()
getXXX()
spring_beans_config.xml
<beans>
<bean id="wishBean" class="com.durgasoft.beans.WishBean" init-method="init"
destroy-method="destroy">
<property name="wish_Message" value="Durga Software Solutions"/>
<property name="name" value="Anil"/>
89
</bean>
<bean id="helloBean" class="com.durgasoft.beans.HelloBean" parent="wishBean">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.HelloBean;
import com.durgasoft.beans.WelcomeBean;
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("/com/durgasoft/cfgs/ spring_beans_config.xml");
HelloBean hello=(HelloBean)context.getBean("helloBean");
System.out.println(hello.sayHello());
System.out.println();
WelcomeBean welcome=(WelcomeBean)context.getBean("welcomeBean");
System.out.println(welcome.sayWelcome());
context.registerShutdownHook();
}
}
To declare a bean definition as template we have to use "abstract" attribute with "true"
value in <bean> tag , in this context, it is not required to use "class" attribute in bean tag.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
<beans>
<bean id="wishBean" abstract="true" .... >
</bean>
<bean id="helloBean" class="HelloBean" parent="wishBean">
</bean>
<bean id="welBean" class="WelcomeBean" parent="wishBean">
</bean>
</beans>
Example:
WishBean.java
package com.durgasoft.beans;
}
public void setWish_Message(String wish_Message) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HelloBean.java
package com.durgasoft.beans;
}
public String getName() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
WelcomeBean.java
package com.durgasoft.beans;
}
public String getName() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.HelloBean;
import com.durgasoft.beans.WelcomeBean;
import com.durgasoft.beans.WishBean;
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Nested Beans:
IN Bean class, if we declare any property of User defined class type then we have to use
<bean> tag for the user defined class as value to the respective property under
<property> tag.
<beans>
95
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
</bean>
</beans>
EX:
Account.java
package com.durgasoft.beans;
public class Account {
private String accNo;
private String accName;
private String accType;
private long balance;
setXXX()
getXXX()
}
Employee.java
package com.durgasoft.beans;
public class Employee {
private String eid;
private String ename;
private float esal;
private String eaddr;
private Account acc;
setXXX()
getXXX()
96
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
<beans>
<bean id="emp" class="com.durgasoft.beans.Employee">
<property name="eid" value="E-111"/>
<property name="ename" value="Durga"/>
<property name="esal" value="10000"/>
<property name="eaddr" value="Hyd"/>
<property name="acc">
<bean id="account" class="com.durgasoft.beans.Account">
<property name="accNo" value="abc123"/>
<property name="accName" value="Durga"/>
<property name="accType" value="Savings"/>
<property name="balance" value="20000"/>
</bean>
</property>
97
</bean>
</beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Employee;
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
Employee emp=(Employee)context.getBean("emp");
emp.displayEmpDetails();
}
}
BeanPostProcessor:
--> This method will be executed just before performing bean initialization and
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
BeanPostProcessorImpl.java
package com.durgasoft.processor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import com.durgasoft.beans.Customer;
public class BeanPostProcessorImpl implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String name) throws
BeansException {
System.out.println("postProcessAfterInitialization()");
Customer cust=(Customer)bean;
cust.setCmobile("91-9988776655");
return cust;
}
99
@Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Customer.java
package com.durgasoft.beans;
public class Customer {
private String cid;
private String cname;
private String caddr;
private String cemail;
private String cmobile;
public Customer(){
System.out.println("Customer Bean Object Creating");
}
public void init(){
System.out.println("Customer Bean Object Initialization through init()
method");
}
public void destroy(){
System.out.println("Customer Object Destroying through destroy()
method");
}
setXXX()
100
getXXX()
public void getCustomerDetails(){
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
<beans>
<bean id="cust" class="com.durgasoft.beans.Customer" init-method="init" destroy-
method="destroy">
<property name="cid" value="C-111"/>
<property name="cname" value="Durga"/>
<property name="caddr" value="Hyd"/>
</bean>
<bean class="com.durgasoft.processor.BeanPostProcessorImpl"/>
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Customer;
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
Customer cust=(Customer)context.getBean("cust");
cust.getCustomerDetails();
context.registerShutdownHook();
101
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1.Dependency Lookup
2.Dependency Injection
1. Dependency Lookup
In Dependency Lookup, Service Provider will create the services and mainatined that
services either in the regisry Softwares or in the containers , where we have to perform
lookup operations inorder to get the required services.
1. Dependecy Pull:
In Dependency Pull, Service Provider will create services and it will keep that services in any
registry softwares, where we have to perform lookup operation inorde to get the required
services, that is, pull the required services from registry softwares.
102
EX1: When we start application Servers like Weblogic, JBOSS , Websphere and Glassfish ,
Page
automatically, Application Servers will create Datasource object and Application Servers
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX2:IN RMI Applications, User defined Registry Application will create Remote object and it
will keep that Remote object in RMIRegistry with a particular logical name , here to get the
required Remote object in Client Application we have to perform lookup operation over
RMIRegistry on the basis of the logical name.
103
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
IN this mechanism, Service Provider will create the services and manage services , in this
context, we have to perform lookup operation inorder to get the required services from
Service Provider.
EX: In general, in web applications, when we start application Server then container will
recognize all the web applications and container will deploy all the web applications into
the server, when web applications are deployed in server , container will create
ServletContext object automatically and Container will manage ServletContext object , in
this context , to get ServletContext object we have to use getServletContext() method from
GenericServlet directly with out using any reference variable, from ServletConfig object
reference and from ServletRequest object reference, that is, performing lookup operation
in Container to get ServletContext object.
2. Dependency Injection
104
IN this mechanism, Service Provider will create the services and inject the required services
to the application directly with out performing lookup operations and with out getting
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
105
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we inject dependent values to the Bean object through Constructor then this type of
Dependency Injection is called as "Constructor Dependency Injection".
<beans>
</bean>
----
</beans>
EX:
Course.java
------------
package com.durgasoft.beans;
this.cid=cid;
this.cname=cname;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
<beans>
<bean id="crs" class="com.durgasoft.beans.Course">
<constructor-arg value="C-111"/>
<constructor-arg value="JAVA"/>
<constructor-arg value="5000"/>
</bean>
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Course;
107
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we inject dependent values to the Bean through setXXX() methods then it is called as
"Setter Method Dependency Injection".
To inject primive values and String value to the bean object then we have to use "value"
attributes in <property> or <constructor-arg> tags in beans configuration file, but, If we
want to inject User defined data types , that is, Object reference values then we have to
use "ref" attribute in <property> tag or in <constructor-arg> tag.
EX:
Account.java
package com.durgasoft.beans;
setXXX()
getXXX()
}
108
Employee.java
package com.durgasoft.beans;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
setXXX()
getXXX()
System.out.println("Employee Details");
System.out.println("-------------------");
System.out.println("Employee Id :"+eid);
System.out.println("Employee Name :"+ename);
System.out.println("Employee Salary :"+esal);
System.out.println("Employee Address:"+eaddr);
System.out.println("Account Details");
System.out.println("-------------------");
System.out.println("Account Number :"+acc.getAccNo());
System.out.println("Account Name :"+acc.getAccName());
System.out.println("Account Type :"+acc.getAccType());
System.out.println("Account Balance:"+acc.getBalance());
}
}
applicationContext.xml
<beans>
<bean id="acc" class="com.durgasoft.beans.Account">
109
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Employee;
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
Employee emp=(Employee)context.getBean("emp");
emp.getEmployeeDetails();
}
}
Different Types of Elements Injection:
In Spring applications, if we want to inject User defined data types then we have to use
either "ref" attribute in <property> and <constructor-arg> tags or we have to use <ref>
nested tag under <property> and <constructor-arg> tags
EX:
110
<beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
</bean>
</beans>
In spring applications, if we want to inject List of elements in beans then we have to declare
the corresponding property as java.util.List and we have to provide values in configuration
file by using <list> tag in <property> tag or in <constructor-arg> tag.
EX:
---
<beans>
<bean id="---" class="--">
<property name="--">
<list>
<value>value1</value>
<value>value2</value>
----
----
</list>
</property>
</bean>
</beans>
In Spring applications, if we want to inject Set of elements in Bean object then we have to
declare the corresponding property as java.util.Set and we have to provide values in
configuration file by using <set> tag under <property> tag or <constructor-arg> tag.
EX:
---
111
<beans>
<bean id="---" class="--">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Spring applications, if we want to inject Map of elements in Bean object then we have to
declare the corresponding property as java.util.Map and we have to provide Key-Value
pairs in configuration file by using <map> and <entry> tags under <property> tag or
<constructor-arg> tag.
EX:
---
<beans>
<bean id="--" class="--">
<property name="--">
<map>
<entry key="key1" value="value1"/>
<entry key="key2" value="value2"/>
----
</map>
</property>
</bean>
</beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
Student.java
package com.durgasoft.beans;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
setXXX()
getXXX()
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Address.java
package com.durgasoft.beans;
public class Address {
private String pno;
private String street;
private String city;
private String country;
setXXX()
getXXX()
applicationContext.xml
114
<beans>
<bean id="addr" class="com.durgasoft.beans.Address">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Student;
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
Student std=(Student)context.getBean("std");
std.getStudentDeails();
}
}
In Spring applications, if more than one bean objects are depending on each other through
116
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Ex:
Student.java
package com.durgasoft.beans;
Branch.java
package com.durgasoft.beans;
appliocationContext.xml
<beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Branch;
import com.durgasoft.beans.Student;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Branch.java
package com.durgasoft.beans;
applicationContext.xml
<beans>
<bean id="student" class="com.durgasoft.beans.Student">
<property name="branch" ref="branch"/>
</bean>
<bean id="branch" class="com.durgasoft.beans.Branch">
<property name="student" ref="student"/>
</bean>
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Branch;
119
import com.durgasoft.beans.Student;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Q)In Spring applications, if we provide both Setter method dependency injection and
Constructor dependency injection to a single bean then what will happen in Spring
Application?
------------------------------------------------------------------------
Ans:
----
If we provide both Constructor dependency injection and Setter method dependency
injection to a single bean then IOC Container will perform constructor dependency
injection first at the time of creating Bean object , after that, IOC Container will perform
Setter method dependency injection, that is, Constructor Dependency Injection provided
values are overridden with setter method dependency injection provided values, finally,
Bean object is able to manage Setter method dependency Injection provided values.
Example:
Student.java
package com.durgasoft.beans;
public class Student {
private String sid;
private String sname;
120
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
setXXX()
getXXX()
applicationContext.xml
------------------------
<beans>
<bean id="std" class="com.durgasoft.beans.Student">
<constructor-arg index="0" value="S-111"/>
<constructor-arg index="1" value="AAA"/>
<constructor-arg index="2" value="Hyd"/>
Test.java
package com.durgasoft.test;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Q)What are the differences between Constructor Dependency Injection and Setter Method
Dependency Injection?
-------------------------------------------------------------------------
Ans:
----
1. In Constructor dependency injection, dependent values injected through a particular
constructor.
In Setter method dependency injection, dependent values are injected through properties
respective setXXX() methods.
In setter method Dependency injection Readability is very good, because, in Setter method
Dependency injection we are able to identify that to property we are able to inject the
dependent values.
dependent objects are getting ready, if dependent objects are not ready then Constructor
dependency injection is not possible.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4.In case of constructor dependency injection ,partial dependency injection is not possible,
because, we have to access the constructor by passing the required no of parameter
values.
5.IN case of constructor dependency injection, it is not simple to change the values in bean
object.
In case of Setter method dependency injection , it is very simple to change the values in
bean object.
6.In Constructor dependency injection, for every change on values a new bean object is
created, because, for every change we have to call constructor explicitly.
In Setter method dependency injection, for every change on values new object is not
created, because, for every change we can access setXXX() method explicitly.
7.Constructor dependency injection will make the bean object as "Immutable Object".
Setter method dependency injection will make the bean object as "mutable Object".
8.If we provide both Constructor and setter method dependency injection to a single bean
object then setter method dependency injection overrides constructor dependency
injection, but, constructor dependency injection is not overriding setter cmethod
dependency injection.
Setter method dependency injection will not provide circular dependency injection.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Setter method dependency injection will not give guarantee for dependency injection.
p-Namespace:
Note: To use p-namespace in spring configration file we have to define "p" namespace in
XSD like below.
xmlns:p="http://www.springframework.org/schema/p"
To provide value as attribute by using "p" namespace in <bean> tag we have to use the
following syntax.
If we want to specify object referernce variable as dependent value the we have to use "-
ref" along with property.
C-Namespace:
124
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: To use c-namespace in spring configration file we have to define "c" namespace in
XSD like below.
xmlns:c="http://www.springframework.org/schema/c"
To provide value as attribute by using "c" namespace in <bean> tag we have to use the
following syntax.
If we want to specify object referernce variable as dependent value then we have to use "-
ref" along with argument_Name.
If we want to specify dependent values in beans configuration file on the basis of index
values then we have to use xml code like below.
Example:
Employee.java
package com.durgasoft.beans;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
setXXX()
getXXX()
Address.java
package com.durgasoft.beans;
setXXX()
126
getXXX()
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.beans;
Course.java
package com.durgasoft.beans;
String cid;
String cname;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
<beans -------
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
-----
>
<bean id="emp" class="com.durgasoft.beans.Employee"
p:eid="E-111" p:ename="AAA" p:esal="15000" p:eaddr-ref="addr"/>
<bean name="addr" class="com.durgasoft.beans.Address"
p:hno="23/3rt" p:street="M G Road" p:city="Hyd" p:state="Tel"/>
</beans>
Test.java
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Employee;
import com.durgasoft.beans.Student;
129
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
"Autowiring" feature of spring framework will make the IOC Container to inject
dependent objects to the bean objects automatically on the basis of the properties
names or on the basis of properties types with out checking <property> tags and
<constructor-arg> tags.
2.byName
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1.no
It is representing "no" autowiring for the beans injection, we must provide explicit
configuration for the beans injection.
2.byName
It will provide autowiring on the basis of the properties names. In this autowiring
mode, IOC Conainer will search for dependent bean objects by matching bean
properties names with the identity values of the beans configuration in spring
configuration file.
3.byType
It will provide autowiring on the basis of the properties data types. In this autowiring
mode, IOC Container will identify the dependent bean objects by matching properties
data types with the bean data types[ class attribute values] in bean configuration.
Note: In Beans configuration file, only one bean definition must be existed with the
same type , if we provide more than one bean configuration with the same type in
beans configuration file then IOC Container will rise an exception.
4.constructor
It is same as "byType" autowiring mode, but, "byType" autowiring will provide setter
method dependency injection and "constructor" autowiring mode will provide
constructor dependency injection on the basis of the types.
Example:
131
Address.java
Page
package com.durgasoft.beans;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
setXXX()
getXXX()
Account.java
package com.durgasoft.beans;
public class Account {
private String accNo;
private String accName;
private String accType;
private long balance;
setXXX()
getXXX()
Employee.java
package com.durgasoft.beans;
public class Employee {
private String eid;
private String ename;
private Address eaddr;
132
setXXX()
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
<beans>
<bean id="eaddr" class="com.durgasoft.beans.Address">
<property name="hno" value="23/3rt"/>
<property name="street" value="PS Road"/>
<property name="city" value="Hyd"/>
<property name="state" value="Tel"/>
</bean>
133
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Employee;
public class Test {
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
Employee emp=(Employee)context.getBean("emp");
emp.getEmpDetails();
}
}
If we want to provide example for "constructor" autowiring then we have to use the
following components in the above example
Example:
134
Address.java
Page
package com.durgasoft.beans;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
setXXX()
getXXX()
Account.java
package com.durgasoft.beans;
public class Account {
private String accNo;
private String accName;
private String accType;
private long balance;
setXXX()
getXXX()
}
Employee.java
this.ename=ename;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
<beans>
<bean id="eaddr" class="com.durgasoft.beans.Address">
same as above
</bean>
<bean id="eacc" class="com.durgasoft.beans.Account">
same as above
136
</bean>
<bean id="emp" class="com.durgasoft.beans.Employee" autowire="constructor">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Employee;
public class Test {
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
Employee emp=(Employee)context.getBean("emp");
emp.getEmpDetails();
}
}
Note: If we want to block any bean object in autowiring then we have to use "autowire-
candidate" attribute with "false" value in <bean> tag in beans configuration file.
EX:
<beans>
<bean id="scourse" class="com.durgasoft.beans.Course"
autowire-candidate="false">
----
</bean>
<bean id="student" class="com.durgasoft.beans.Student" autowire="byType">
----
137
</bean>
</beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1.@Required
2.@Autowired
3.@Qualifier
1.@Required
This annotation will make IOC Container to inject a particular bean object in another
bean object is mandatory. We have to use this annotation at method level, that is, just
before setXXX() method. After providing this annotation, if we are not providing the
respectiove bean injection then IOC Container will rise an exception .
2.@Autowired
3.@Qualifier
In the case of "byType" autowiring mode, that is, in the case of @Autowired annotation
138
configuration file must provide only one bean configuration with the respective type, if
we provide more than one bean configuration with the same type then IOC Container
Page
will rise an exception. In this context, to resolve the ambiguity of beans injection we
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
Student.java
package com.durgasoft.beans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
return scourse;
}
Page
@Autowired(required=true)
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.beans;
public class Course {
private String cid;
private String cname;
private int ccost;
setXXX()
getXXX()
}
applicationContext.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Student;
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
Student std=(Student)context.getBean("std");
std.getStudentDetails();
}
}
Example:
141
Student.java
Page
package com.durgasoft.beans;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
@Autowired
public Student(String sid, String sname,
@Qualifier("adv_Java")Course scourse){
this.sid=sid;
this.sname=sname;
this.scourse=scourse;
}
public void getStudentDetails(){
System.out.println("Student Details");
System.out.println("--------------------");
System.out.println("Student Id :"+sid);
System.out.println("Student Name :"+sname);
System.out.println("Course Details");
System.out.println("----------------");
System.out.println("Course Id :"+scourse.getCid());
System.out.println("Course Name :"+scourse.getCname());
System.out.println("Course Cost :"+scourse.getCcost());
}
}
Course.java
package com.durgasoft.beans;
142
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
setXXX()
getXXX()
}
applicationContext.xml
<beans>
<context:annotation-config/>
<bean id="core_Java" class="com.durgasoft.beans.Course">
<property name="cid" value="C-111"/>
<property name="cname" value="Core Java"/>
<property name="ccost" value="10000"/>
</bean>
<bean id="adv_Java" class="com.durgasoft.beans.Course">
<property name="cid" value="C-111"/>
<property name="cname" value="Adv Java"/>
<property name="ccost" value="20000"/>
</bean>
<bean id="std" class="com.durgasoft.beans.Student" >
<constructor-arg name="sid" value="S-111"/>
<constructor-arg name="sname" value="Durga"/>
</bean>
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Student;
public class Test {
143
ClassPathXmlApplicationContext("applicationContext.xml");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3.Auto-Discovery[Stereo Types]
This mechanism will provide the autowiring beans objects with out using <bean>
configuration in configuration file.
To use this mechanism in Spring applications then we have to use the following
annotations provided by spring framework in the package
"org.springframework.stereotype"
Note: If we want to use these annotations in Spring applications then we must provide
the following tag in spring configuration file.
<context:component-scan base-package="---"/>
EX:
---
<context:component-scan base-package="com.durgasoft.service"/>
<context:component-scan base-package="com.durgasoft.dao"/>
<context:component-scan base-package="com.durgasoft.controller"/>
If we provide the above tag in spring configuration file then IOC Container will scan the
specified packages and recognize the classes which are annotated with @Component,
144
@Repository, @Service and @Controller then Container will create bean objects with
out checking beans configurations in configuration file.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
AccountDao.java
----------------
package com.durgasoft.dao;
import com.durgasoft.dto.Account;
AccountDaoImpl.java
--------------------
package com.durgasoft.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.durgasoft.dto.Account;
import oracle.jdbc.pool.OracleDataSource;
//@Repository("accDao")
145
@Component("accDao")
public class AccountDaoImpl implements AccountDao {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public String create(String accNo, String accName, String accType, int balance) {
try {
@Override
146
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public Account getAccount(String accNo) {
Account acc = null;
try {
Connection con = dataSource.getConnection();
PreparedStatement pst = con.prepareStatement("select * from
account where accNO = ?");
pst.setString(1, accNo);
ResultSet rs = pst.executeQuery();
boolean b = rs.next();
if(b == true) {
acc = new Account();
acc.setAccNo(rs.getString("ACCNO"));
acc.setAccName(rs.getString("ACCNAME"));
acc.setAccType(rs.getString("ACCTYPE"));
147
acc.setBalance(rs.getInt("BALANCE"));
}else {
Page
acc = null;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public String delete(String accNo) {
try {
Connection con = dataSource.getConnection();
PreparedStatement pst = con.prepareStatement("select * from
account where accNO = ?");
pst.setString(1, accNo);
ResultSet rs = pst.executeQuery();
148
boolean b = rs.next();
if(b == true) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
AccountService.java
--------------------
package com.durgasoft.service;
import com.durgasoft.dto.Account;
AccountServiceImpl.java
-----------------------
Page
package com.durgasoft.service;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.durgasoft.dao.AccountDao;
import com.durgasoft.dto.Account;
@Service("accService")
public class AccountServiceImpl implements AccountService {
@Autowired(required=true)
private AccountDao dao;
@Override
public String createAccount(String accNo, String accName, String accType, int
balance) {
@Override
public String searchAccount(String accNo) {
return dao.search(accNo);
}
@Override
public Account getAccount(String accNo) {
return dao.getAccount(accNo);
}
@Override
public String updateAccount(String accNo, String accName, String accType, int
balance) {
150
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public String deleteAcount(String accNo) {
return dao.delete(accNo);
}
Account.java
-------------
package com.durgasoft.dto;
}
public void setAccType(String accType) {
Page
this.accType = accType;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.durgasoft.service"/>
<context:component-scan base-package="com.durgasoft.dao"/>
<bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource">
<property name="URL" value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="user" value="system"/>
<property name="password" value="durga"/>
</bean>
</beans>
Test.java
152
package com.durgasoft.test;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.dao.AccountDao;
import com.durgasoft.dto.Account;
import com.durgasoft.service.AccountService;
while(true) {
System.out.println();
System.out.println("Account Operations Menu");
System.out.println("1.Create Account");
System.out.println("2.Search Account");
System.out.println("3.Update Account");
System.out.println("4.Delete Account");
System.out.println("5.Exit");
System.out.print("Your Option :");
int option = Integer.parseInt(br.readLine());
String status = "";
String accNo = "", accName = "", accType = "";
int balance = 0;
153
switch(option) {
case 1:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
if(status.equals("failure")) {
System.out.println("Account Updation Failure");
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}
}
}
AccountDao.java
156
----------------
package com.durgasoft.dao;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
AccountDaoImpl.java
package com.durgasoft.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.durgasoft.dto.Account;
import oracle.jdbc.pool.OracleDataSource;
//@Repository("accDao")
@Component("accDao")
public class AccountDaoImpl implements AccountDao {
String status = "";
@Autowired(required=true)
private OracleDataSource dataSource;
157
@Override
public String create(String accNo, String accName, String accType, int balance) {
Page
try {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public String search(String accNo) {
try {
Connection con = dataSource.getConnection();
PreparedStatement pst = con.prepareStatement("select * from
account where accNo = ?");
pst.setString(1, accNo);
158
ResultSet rs = pst.executeQuery();
boolean b = rs.next();
Page
if(b == true) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public Account getAccount(String accNo) {
Account acc = null;
try {
Connection con = dataSource.getConnection();
PreparedStatement pst = con.prepareStatement("select * from
account where accNO = ?");
pst.setString(1, accNo);
ResultSet rs = pst.executeQuery();
boolean b = rs.next();
if(b == true) {
acc = new Account();
acc.setAccNo(rs.getString("ACCNO"));
acc.setAccName(rs.getString("ACCNAME"));
acc.setAccType(rs.getString("ACCTYPE"));
acc.setBalance(rs.getInt("BALANCE"));
}else {
acc = null;
}
} catch (Exception e) {
e.printStackTrace();
159
}
return acc;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public String delete(String accNo) {
try {
Connection con = dataSource.getConnection();
PreparedStatement pst = con.prepareStatement("select * from
account where accNO = ?");
pst.setString(1, accNo);
ResultSet rs = pst.executeQuery();
boolean b = rs.next();
if(b == true) {
pst = con.prepareStatement("delete from account where accNo
= ?");
pst.setString(1, accNo);
pst.executeUpdate();
160
status = "success";
}else {
Page
status = "notexisted";
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
AccountService.java
package com.durgasoft.service;
import com.durgasoft.dto.Account;
AccountServoceImpl.java
package com.durgasoft.service;
import com.durgasoft.dto.Account;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
AccountServiceImpl.java
package com.durgasoft.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.durgasoft.dao.AccountDao;
import com.durgasoft.dto.Account;
@Service("accService")
public class AccountServiceImpl implements AccountService {
@Autowired(required=true)
private AccountDao dao;
@Override
public String createAccount(String accNo, String accName, String accType, int
balance) {
@Override
public String searchAccount(String accNo) {
return dao.search(accNo);
}
162
@Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
return dao.getAccount(accNo);
}
@Override
public String updateAccount(String accNo, String accName, String accType, int
balance) {
@Override
public String deleteAcount(String accNo) {
return dao.delete(accNo);
}
Account.java
package com.durgasoft.dto;
}
public String getAccName() {
Page
return accName;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
AccountConfig.java
package com.durgasoft.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.durgasoft.dao.AccountDao;
import com.durgasoft.dao.AccountDaoImpl;
import com.durgasoft.service.AccountService;
import com.durgasoft.service.AccountServiceImpl;
import oracle.jdbc.pool.OracleDataSource;
164
@Configuration
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Bean
public AccountService accService() {
AccountService accService = new AccountServiceImpl();
return accService;
}
@Bean
public AccountDao dao() {
AccountDao dao = new AccountDaoImpl();
return dao;
}
}
time to a bean object injection then explicit wiring overrides autowiring configurations.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Method Injection
In Spring applications, bydefault, all the objects are singleton objects provided by IOC
Container[ApplicationContext] . In Spring application , as part of dependency injection
both container object and contained object are having same scope then application may
not get any problem, if container object and contained objects are having different
scopes then application may get problem.
EX: In Spring applications, if we inject Course object in Student Object , where if
provide Singleton scope to Student object and Prototype scope to Course object then
For every request for Student object single Student Object is created , along with single
student object single Course object is created with out checking its scope "prototype"
which we provided in spring configuration file, it is voilating spring scopes rules and
regulations.
Student.java
-----
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
<beans>
<bean id="std" class="com.durgasoft.beans.Student" scope="singleton">
----
<property name="scourse" ref="scourse"/>
</bean>
<bean id="scourse" class="com.durgasoft.beans.Course" scope="prototype">
-----
</bean>
</beans>
Test.java
To overcome the above problem Spring has provided no of solutions, where one of the
solution is "Method Injection".
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In case of Look Method injection, we will declare an abstract class as a factory class and
an abstract method as a factory method then we will give an intemation to IOC
Container about to generate a sub class for the abstract class and an implementation
for the abstract method dynamically.
In this context, IOC Container will prepare dynamic sub classes for abstract factory
class and return that objects to the test application as per the requirement.
In Spring Framework, IOC Container will provide dynamic sub classes by using CGLIb
third party library which is managed by Spring framework internally.
To give an intimation to the IOC Container about the sub classes generation and
implementation for Factory method by providing configuration details in spring
configuration file.
Example:
Account.java
package com.durgasoft.beans;
CurrentAccount.java
168
package com.durgasoft.beans;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
SavingsAccount.java
package com.durgasoft.beans;
public class SavingsAccount implements Account {
public void create() {
System.out.println("Savings Account is created");
}
public void search() {
System.out.println("Savings Account is identified");
}
public void update() {
System.out.println("Savings Account is Updated");
}
public void delete() {
System.out.println("Savings Account is Deleted");
}
}
AccountFactory.java
169
package com.durgasoft.factory;
Page
import com.durgasoft.beans.Account;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
<beans>
<bean id="savingsAccount" class="com.durgasoft.beans.SavingsAccount" />
<bean id="currentAccount" class="com.durgasoft.beans.CurrentAccount" />
<bean id="savingsAccountFactory"
class="com.durgasoft.factory.AccountFactory">
<lookup-method name="getAccount" bean="savingsAccount"/>
</bean>
<bean id="currentAccountFactory" class="com.durgasoft.factory.AccountFactory">
<lookup-method name="getAccount" bean="currentAccount"/>
</bean>
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.CurrentAccount;
import com.durgasoft.beans.SavingsAccount;
import com.durgasoft.factory.AccountFactory;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new
ClassPathXmlApplicationContext("/com/durgasoft/cfgs/spring_beans_config.xml");
AccountFactory
savingsAccountFactory=(AccountFactory)context.getBean("savingsAccountFactory");
SavingsAccount
savings_Account=(SavingsAccount)savingsAccountFactory.getAccount();
170
savings_Account.create();
savings_Account.search();
Page
savings_Account.update();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
AccountFactory
currentAccountFactory=(AccountFactory)context.getBean("currentAccountFactory");
CurrentAccount
current_Account=(CurrentAccount)currentAccountFactory.getAccount();
current_Account.create();
current_Account.search();
current_Account.update();
current_Account.delete();
}
}
Method Replacement:
It is one type of method injection, where we will give an intimation to IOC Container
about to replace the existed method implementation with some other method
implementation.
To achieve Method Replacement, we have to declare an user defined bean class with a
method whose implementation we want to replace and we will provide new
implementation for that method by declaring a class and by implementing
"MethodReplacer" interface.
Example:
Course.java
package com.durgasoft.beans;
171
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
NewImpl.java
package com.durgasoft.beans;
import java.lang.reflect.Method;
import org.springframework.beans.factory.support.MethodReplacer;
public class NewImpl implements MethodReplacer {
public Object reimplement(Object arg0, Method arg1, Object[] arg2) throws Throwable
{
System.out.println("Course Details");
System.out.println("-----------------");
System.out.println("Course Id :C-222");
System.out.println("Course Name :.NET");
System.out.println("Course Cost :20000");
return null;
}
}
spring_beans_config.xml
<beans>
<bean id="newImpl" class="com.durgasoft.beans.NewImpl"/>
172
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Course;
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("/com/durgasoft/cfgs/spring_beans_config.xml");
Course crs=(Course)context.getBean("course");
crs.getCourseDetails();
}
}
173
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1.Client Side Data Validations: The process of checking whether data is valid or not at
client browser before submitting request to the Server is called as Client Side Data Data
Validations. To perform client side data validations we will use "Java Script" Functions.
2.Server Side Data Validations: The process of checking whether data is valid or not
at server after getting request from client and before using data in application logic is
called as Server side data validations. To perform Server side data validations we have
to use Java code explicitly.
Note: If we use web Frameworks like Struts, JSF , SPring WEB MVC module then all
these frameworks are able to provide their own validations services implicitly to
perform data validations.
In Spring Core Module, to perform validations over the data after storing data in Bean
objects Spring Framework has provided a predefined interface in the form of
"org.springframework.validation.Validator" .
To perform bean validations in Spring applications then we have to use the following
steps.
Declare validation messages in the form of key-value pairs, where keys must be
validation message code and value must be validation message.
174
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The main intention of Validator class is to define all data validation logic w.r.t the bean
properties.
Steps:
d)Declare Resource property and its setXXX() method inorder to repersent the name
and location of the properties file where all the validation messages are existed.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
package com.durgasoft.beans;
public class Employee {
private String eid;
private String ename;
private float esal;
private int eage;
private String eemail;
private String emobile;
messages.properties
error.eid.empty=Employee Id is required.
error.eid.invalid=Invalid Employee Id.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeValidator.java
package com.durgasoft.validations;
import com.durgasoft.beans.Employee;
import java.util.Properties;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@Override
public boolean supports(Class type) {
System.out.println("Hello");
return Employee.class.equals(type);
}
@Override
177
System.out.println("Hello...validate()");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}else{
if(!emp.getEmobile().startsWith("91-")){
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
<beans>
<bean id="emp" class="com.durgasoft.beans.Employee">
<property name="eid" value=""/>
<property name="ename" value=""/>
<property name="esal" value=""/>
<property name="eage" value=""/>
<property name="eemail" value=""/>
<property name="emobile" value=""/>
</bean>
<bean id="empValidator" class="com.durgasoft.validations.EmployeeValidator">
<property name="resource"
value="/com/durgasoft/resources/messages.properties"/>
</bean>
</beans>
Test.java0
package com.durgasoft.test;
import com.durgasoft.beans.Employee;
import com.durgasoft.validations.EmployeeValidator;
179
import java.util.HashMap;
import java.util.List;
Page
import java.util.Map;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
180
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Event Handling, the main intention of Listeners is to listen the events rised by the
GUI Components, handle that events and generating results back to the GUI
Applications.
Similarily, in spring applications, IOC Container is able to rise events when it was
started, refreshed, stopped and closed. In this context, to handle the generated events
Spring Framework has provided "Event Handling".
1.ContextRefreshedEvent
2.ContextStartedEvent
3.ContextStoppedEvent
4.ContextClosedEvent
5.RequestHandledEvent
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To Handle all the above Events, Spring Framework has provided a Listener in the form
of "org.springframework.context.ApplicationListener" interface and it is having the
following to execute when the respective event is rised.
Note: ApplicationListener is able to listen all the events bydefault, if we want to filter
the events then we have to provide the respective Event type as Generic parameter.
EX: ApplicationListener<ContextStartedEvent> is able to listen only
ContextStartedEvent .
In Spring applications, if we want to implement event handling then we have to use the
following steps.
Example:
ContextRefreshedListenerImpl.java
182
package com.durgasoft.listeners;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public void onApplicationEvent(ContextRefreshedEvent e) {
System.out.println("Application Context is Refreshed");
}
ContextStartedListenerImpl.java
package com.durgasoft.listeners;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;
@Override
public void onApplicationEvent(ContextStartedEvent e) {
System.out.println("Application Context Started....");
}
}
ContextStoppedListenerImpl.java
183
package com.durgasoft.listeners;
Page
import org.springframework.context.ApplicationListener;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public void onApplicationEvent(ContextStoppedEvent e) {
System.out.println("Application Context Stopped");
}
ContextClosedListenerImpl.java
package com.durgasoft.listeners;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
@Override
public void onApplicationEvent(ContextClosedEvent e) {
System.out.println("Application Context has Closed");
}
HelloBean.java
package com.durgasoft.beans;
184
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
<beans>
<bean id="helloBean" class="com.durgasoft.beans.HelloBean">
<property name="uname" value="Durga"/>
</bean>
<bean id="contextRefreshedEvent"
class="com.durgasoft.listeners.ContextRefreshedListenerImpl"/>
<bean id="contextStartedEvent"
class="com.durgasoft.listeners.ContextStartedListenerImpl"/>
<bean id="contextStoppedEvent"
class="com.durgasoft.listeners.ContextStoppedListenerImpl"/>
<bean id="contextClosedEvent"
class="com.durgasoft.listeners.ContextClosedListenerImpl"/>
</beans>
Test.java
package com.durgasoft.test;
import com.durgasoft.beans.HelloBean;
185
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
Page
import org.springframework.context.support.ClassPathXmlApplicationContext;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Custom Events are user defined events which are defined by the developers as per
their application requirements.
To manage custom Events in Spring applications we have to use the following steps.
defined class.
c)Declare public and Object parameterized Constructor and access super class Object
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The main intention of event publisher class is to publish the user defined event inorder
to handle.
Steps:
The main intention of User defined Event Handler class is to handle the user defined
Events.
Steps:
Note: By default, Listeners are able to handle all the Listeners, but, if we want to filter
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note:Spring4.2 version has provided very good annotations support for Event
Handling in the form of the following Annotations.
1)@EventListener({Event1.class,Event2.class...})
Where Event1.class, Event2.class,... are Event class types wich we want to process.
EX:@EventListener({ContextRefreshedEvent.class,ContextStoppedEvent.class})
2)@Async() : It will be used to prcess events asynchronously.
In the application, as per the requirement we are able to publish the events by using
publishEvent(--) method.
AccountEvent.java
package com.durgasoft.events;
import java.io.FileOutputStream;
import java.util.Date;
import org.springframework.context.ApplicationEvent;
} catch (Exception e) {
e.printStackTrace();
}
}
188
super(obj);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}
}
AccountEventPublisher.java
package com.durgasoft.events;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.events;
import org.springframework.context.ApplicationListener;
@Override
public void onApplicationEvent(AccountEvent e) {
e.generateLog();
}
Account.java
package com.durgasoft.beans;
import com.durgasoft.events.AccountEventPublisher;
}
public void updateAccount(){
Page
System.out.println("Account Updated");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
<beans>
<bean id="account" class="com.durgasoft.beans.Account">
<property name="publisher" ref="accountEventPublisher"/>
</bean>
<bean id="accountEventHandler"
class="com.durgasoft.events.AccountEventHandler"/>
<bean id="accountEventPublisher"
class="com.durgasoft.events.AccountEventPublisher"/>
</beans>
Test.java
package com.durgasoft.test;
import com.durgasoft.beans.Account;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args)throws Exception {
ConfigurableApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
Account account=(Account)context.getBean("account");
account.createAccount();
account.searchAccount();
account.updateAccount();
191
account.deleteAccount();
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To provide Internationalization services to the users, first, we have to devide all the
users into groups as per locality, for this, we have to use the following parameters.
3.System Varient[OS]: It will be represented in the form of three lower case letters.
EX: win, uni, lin,.....
In java applications, to represent a group of local users JAVA has provided a predefined
class in the form of "java.util.Locale".
EX:
1.Number Formations
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Number Formations:
Steps:
2.Date Formations:
It can be used to represent a Date w.r.t a particular Locale, for this, it will use
java.text.DateFormat class.
Steps:
3.Message Formations:
It can be used to represent messages w.r.t a particular Locale, for this, we have to use
properties files and java.util.ResourceBundle class.
Steps:
a)Create properties files with all the messages in the form of key-value pairs.
Note: properties files names must be provided in the followng format.
193
baseName_lang_country.properties
b)Create ResourceBundle object by using getBundle(--) Factory method.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
com/durgasoft/resources/abc_en_US.properties
---------------------------------------------
welcome = Welcome To en US Users.
com/durgasoft/resources/abc_it_IT.properties
---------------------------------------------
welcome = Welcome To it IT Users.
Test.java
package com.durgasoft;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
public class Test {
public static void main(String[] args)throws Exception {
Locale l = new Locale("it", "IT");
ResourceBundle resource_Bundle =
ResourceBundle.getBundle("com/durgasoft/resources/abc", l);
System.out.println(resource_Bundle.getString("welcome"));
}
194
}
To provide Message formations in Spring applications, Spring has provided a
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
For MessageSource interface Spring Framework has provided the following two
implementation classes.
org.springframework.context.support.ResourceBundleMessageSource
org.springframework.context.support.ReloadableResourceBundleMessageSource
Steps:
1.Declare properties files with the messages and with the following format for
properties files names.
baseName_lang_Country.properties.
2.Declare a Bean class with MessageSource type property and the respective setter
method and the required business methods.
Note: To get a message from MessageSource object we have to use the following
method.
public String getMessage(String key, Object[] place_holder_values, Locale l)
object.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example-1:
abc_en_US.properties
---------------------
welcome = Welcome To {0} and {1} User.
abc_fr_FR.properties
---------------------
welcome = Welcome To {0} and {1} Users.
I18NBean.java
--------------
package com.durgasoft.beans;
import java.util.Locale;
import org.springframework.context.MessageSource;
}
196
}
Page
applicationContext.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
<beans>
<bean id="i18nBean" class="com.durgasoft.beans.I18NBean">
<property name="messageSource" ref="resourceBundleMessageSource"/>
</bean>
<bean id="resourceBundleMessageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="com/durgasoft/resources/abc"/>
</bean>
</beans>
Test.java
package com.durgasoft.test;
import com.durgasoft.beans.I18NBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
<properties>
<entry key="message_Key"> Message_Value </entry>
Page
-----
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
abc_en_US.xml
--------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="welcome"> Welcome to en US User from XML </entry>
</properties>
abc_fr_FR.xml
---------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="welcome"> Welcome to fr France User from XML </entry>
</properties>
spring_beans_config.xml
------------------------
<beans>
<bean id="i18nBean" class="com.durgasoft.beans.I18NBean">
<property name="messageSource"
ref="reloadableResourceBundleMessageSource"/>
</bean>
<bean id="reloadableResourceBundleMessageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSourc
198
e">
<property name="basename" value="com/durgasoft/resources_xml/abc"/>
Page
</bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
I18NBean.java
--------------
package com.durgasoft.beans;
import java.util.Locale;
import org.springframework.context.MessageSource;
Test.java
package com.durgasoft.test;
import com.durgasoft.beans.I18NBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
I18NBean bean = (I18NBean)context.getBean("i18nBean");
199
bean.displayMessage();
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Java, we are able to get beans descriptions like bean properties information like their
names and the correspecding setXXX() and getXXX() methods information by using
"Beans Introspection".
Example:
200
package com.durgasoft.core;
public class Employee {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.core;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To get BeanInfo object we have to use the following method from BeanInfoFactory
interface.
Example:
Employee.java
package com.durgasoft.beans;
public class Employee {
private int eno;
private String ename;
private float esal;
private String eaddr;
return eno;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import com.durgasoft.beans.Employee;
203
import java.beans.BeanInfo;
import java.beans.PropertyDescriptor;
Page
import org.springframework.beans.BeanInfoFactory;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To set values to the Bean object through Bean Wrapper class we have to use the
following method from BeanWrapper class.
Note: If we want to set all the properties at a time to Bean object, first, we have to set
204
property names and their values in the form of Map object then set that Map object to
BeanWrapper object, for this, we have to use the following method.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To get property value explicitly from Bean object we have to use the following method
from BeanWrapper class.
To get Bean object explicitly through BenWrapper we have to use the following method
from BeNWrapper.
To copy the properties values from one Bean object to another Bean object we have to
use the following method from "org.springframework.beans.BeanUtils" class.
To Check whether the property is readable or writable then we have to use the
following methods from BeanWrapper class.
Example:
Employee.java
package com.durgasoft.beans;
public class Employee {
private int eno;
205
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
System.out.println("Employee Details");
System.out.println("-------------------");
Page
System.out.println("Employee Id :"+eno);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}
}
Test1.java
package com.durgasoft.test;
import com.durgasoft.beans.Employee;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
map.put("eaddr", "Hyd");
bw.setPropertyValues(map);
Page
System.out.println(emp);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
System.out.println("Employee Details");
System.out.println("--------------------------");
System.out.println("Employee No :"+bw.getPropertyValue("eno"));
System.out.println("Employee Name :"+bw.getPropertyValue("ename"));
System.out.println("Employee Salary :"+bw.getPropertyValue("esal"));
System.out.println("Employee Address :"+bw.getPropertyValue("eaddr"));
}
}
Test2.java
package com.durgasoft.test;
import com.durgasoft.beans.Employee;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
emp2.displayEmpDetails();
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Spring Applications, we will provide all values in spring configuration file as text
values , but, Spring framework has to store these text values into the bean objects as
the objects like Byte, Integer, String, Long,....., In this context, to convert data from
textual rep-resentation to the respective objects Spring framework will use a feature
"Property Editors".
To convert data from text form to Objects , Spring Framework has provided the
following Predefined Property Editors.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
8.LocaleEditor: Capable of resolving Strings to Locale objects and vice versa (the
String format is [country][variant], which is the same thing the toString() method of
Locale provides).
Spring Framework has provided an approach to provide custom Property Editors, for
this , we have to use the following steps.
Example:
210
EmployeeAddress.java
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
package com.durgasoft.beans;
public class Employee {
private String eid;
private String ename;
private float esal;
private EmployeeAddress eaddr;
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeAddressEditor.java
package com.durgasoft.beans;
import java.beans.PropertyEditorSupport;
@Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import com.durgasoft.beans.Employee;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
spring_beans_config.xml
214
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="com.durgasoft.beans.EmployeeAddress"
value="com.durgasoft.beans.EmployeeAddressEditor"/>
</map>
</property>
</bean>
</beans>
215
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In general, in all project lifecycle phases we will provide the required configuration
details manually, it may increase problems to the applications , in this context,
Spring3.x version has provided an automated solution inorder to provide the
corresponding configuration details wrt the lifecycle phases, for this, Spring framework
has provided "Profiling" feature.
1.Create a seperate spring configuration file for each and every phase of the project
lifecyle with the respective configuration details.
EX: spring-context-development.xml
spring-context-testing.xml
spring-context-production.xml
2.In all Spring Configuration files we must provide "profile" attribute in <beans> tag
with the respective lifecycle phyase name.
EX: spring-context-development.xml
------------------------------
<beans profile="development">
216
------
</beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
Example:
AccountBean.java
package com.durgasoft.beans;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext-development.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
</beans>
applicationContext-production.xml
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.durgasoft.beans.AccountBean;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
220
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
1.JSP EL: To evaluate the objects and their properties like request, session,
application,.... and their parameters and attribuites.
2.Struts2.x OGNL: To evaluate the objects and their properties like Value Stack,
CentralContext, request, application......
3.JBOSS EL: To evaluate Objects and their properties which are related to the JBOSS
implementations.
To prepare and Evaluate Expressions in SpEL, Spring has provided very good
Predefined Library in the form of "org.springframework.exprssion" package.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To prepare expression and to get Expression object we have to use the following
method from ExpressionParser .
To get expression result we have to use the following method from Expresion.
EX:
Page
package com.durgasoft.test;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
expr = parser.parseExpression("10*10");
int val2 = (Integer) expr.getValue();
System.out.println(val2);
expr = parser.parseExpression("'abc'+'def'");
String val3 = (String) expr.getValue();
System.out.println(val3);
}
}
CalculatorBean.java
package com.durgasoft.beans;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import com.durgasoft.beans.CalculatorBean;
expr2.setValue(context, "5");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
System.out.println("num1 :"+cal.getNum1());
System.out.println("num2 :"+cal.getNum2());
System.out.println("ADD :"+cal.add());
System.out.println("SUB :"+cal.sub());
System.out.println("MUL :"+cal.mul());
}
}
SpEL Features:
1.Expressions
2.Operators
3.Variables
4.Medthod Invocations
5.Collections
1.Expressions
1.Literal Expressions
---> It able to allow only literals inside the Expressions.
2.Regular Expressions
---> It able to check the specified String against the provided Regular Expressions, If the
provided String is as per the provided Regular Expression then it will return true value
otherwise it will return false value.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
package com.durgasoft.test;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class Test {
expr = parser.parseExpression("0xABCDEF*10+6");
System.out.println(expr.getValue());
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
i).Arithmetic Operators:
+, -, *, /, %,.....
ii).Logical Operators:
and or &&
or or ||
not or !
iii).Comparision Operators:
eq or ==
ne or !=
lt or <
le or <=
gt or >
ge or >=
iv).Ternary Operator:
v).Type Operator[T]:
Syntax:
227
T(Class_Name)
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Syntax:
var_Name?.methid_or_Var_Name()
Example:
package com.durgasoft.beans;
Test.java
package com.durgasoft.test;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
228
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
expr = parser.parseExpression("T(Thread).MIN_PRIORITY");
System.out.println(expr.getValue());
expr = parser.parseExpression("T(Integer).toString(10)");
System.out.println(expr.getValue());
3.Variables
#var_Name.
Example:
230
MyMath.java
Page
package com.durgasoft.beans;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import com.durgasoft.beans.MyMath;
public class Test {
public static void main(String[] args)throws Exception {
MyMath math = new MyMath();
StandardEvaluationContext context = new
StandardEvaluationContext(math);
context.setVariable("number1", 10);
context.setVariable("number2", 5);
ExpressionParser parser = new SpelExpressionParser();
231
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4.Medthod Invocations
In SpEL , we are able to declare methods and we are able to access that methods as per
the requirement.
If we want to declare an user defined method and if we want to access user defined
method through an expression then we have to use the following steps.
1.Create StandardEvaluationContext object.
2.Register Method with a name.
public void registerFunction(String meth_Name, Method m)
3.Prepare an Expression with method call and access it.
Example:
MyString.java
package com.durgasoft.beans;
public class MyString {
public static void reverseString(String str) {
StringBuffer sb = new StringBuffer(str);
System.out.println(sb.reverse());
}
}
Test.java
232
package com.durgasoft.test;
import java.lang.reflect.Method;
Page
import org.springframework.expression.Expression;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
5.Collections
In SpEL, we are able to declare Collections and we are able to access the content from
Collection objects by using the following Expression Syntax.
Collection_Ref_Var.?Condition_Expression
233
Example:
Page
City_State.java
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.beans;
City_State_Collection.java
package com.durgasoft.beans;
import java.util.ArrayList;
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.test;
import java.util.ArrayList;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import com.durgasoft.beans.City_State;
import com.durgasoft.beans.City_State_Collection;
}
235
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
{Spring JDBC
MODULE}
236
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
237
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
-->DAO [Data Access Object], it is a design pattern, it able to provide very good environment to
separate Data Access logic from Business Processing logic.
-->In enterprise Applications, to prepare Data Access Layer we will use DAO Design pattern.
Prepare a seperate DAO interface with the required DAO methods, which must represent CRUD
operations.
EX:
-----
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Service layer
StudentDao dao = StudentDao.getStudentDao();
5) We must not cache DAO references, because, Factory classes/ Factory methods are providing
single instances of DAO to the service layer, if DAO is required in multiple modules then it is
239
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
7) DAO is not threadsafe, we must not use DAOs in multi threadded environment.
8) In DAOs we can access close() method inorder to close the resources like connections,.... , so
here, before calling close() method we must ensure that whether the resources are going to be
released or not with our close() method call.
9) We have make sure that all the objects which are used by DAOs are following Java bean
conventions or not.
Resources:
1. htmls:
a)addform.html
b)searchform.html
c)deleteform.html
d)existed.html
e)notexisted.html
f)success.html
g)failure.html
h)layout.html
i)header.html
j)menu.html
k)welcome.html
l)footer.html
2.jsps
a)display.jsp
3.Servlets
a)ControllerServlet
4.Services:
a)StudentService
5.DAOs
a)StudentDao
6)DTOs
a)StudentTo
7)Factories
a)ConnectionFactory
240
b)StudentServiceFactory
c)StudentDaoFactory
Page
8)JARS:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Design Patterns:
a)DAO
b)MVC
c)DTO
d)Factory
Example:
layout.html
<frameset rows="20%,65%,15%">
<frame src="header.html"/>
<frameset cols="20%,80%">
<frame src="menu.html"/>
<frame src="welcome.html" name="body"/>
</frameset>
<frame src="footer.html"/>
</frameset>
header.html
</html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
menu.html
</html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
addform.html
</tr>
<tr>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
searchform.html
deleteform.html
244
"http://www.w3.org/TR/html4/loose.dtd">
<html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
display.jsp
<%@page import="com.durgasoft.to.StudentTo"%>
<%!
StudentTo sto;
%>
<%
sto = (StudentTo)request.getAttribute("sto");
%>
<html>
<body bgcolor="lightblue">
<center>
<br><br><br>
<table border = "1" bgcolor="white">
<tr>
<td>Student Id</td><td><%= sto.getSid() %></td>
</tr>
<tr>
245
<tr>
<td>Student Address</td><td><%= sto.getSaddr() %></td>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
</table>
</center>
</body>
</html>
existed.html
notexisted.html
<br><br><br>
<font color="red" size="6">
Page
<b>
Student Not Existed
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
success.html
failure.html
Failure
</b>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ControllerServlet.java
package com.durgasoft.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.durgasoft.factory.StudentServiceFactory;
import com.durgasoft.services.StudentService;
import com.durgasoft.to.StudentTo;
public class ControllerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String button_Label = request.getParameter("button");
String status = "";
RequestDispatcher rd = null;
if(button_Label.equals("ADD")){
StudentService service = StudentServiceFactory.getStudentService();
StudentTo sto = new StudentTo();
sto.setSid(request.getParameter("sid"));
sto.setSname(request.getParameter("sname"));
sto.setSaddr(request.getParameter("saddr"));
status = service.addStudent(sto);
if(status.equals("success")){
rd = request.getRequestDispatcher("./success.html");
rd.forward(request, response);
}
if(status.equals("failure")){
248
rd = request.getRequestDispatcher("./failure.html");
rd.forward(request, response);
Page
}
if(status.equals("existed")){
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
dispatcher = request.getRequestDispatcher("notexisted.html");
dispatcher.forward(request, response);
}
}
}
249
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.services;
import com.durgasoft.to.StudentTo;
StudentServiceImpl.java
package com.durgasoft.services;
import com.durgasoft.dao.StudentDao;
import com.durgasoft.factory.StudentDaoFactory;
import com.durgasoft.to.StudentTo;
@Override
public StudentTo searchStudent(String sid) {
StudentTo sto = null;
StudentDao dao = StudentDaoFactory.getStudentDao();
sto = dao.search(sid);
return sto;
}
@Override
public String deleteStudent(String sid) {
250
return status;
}
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentDao.java
package com.durgasoft.dao;
import com.durgasoft.to.StudentTo;
StudentDaoImpl.java
package com.durgasoft.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.durgasoft.factory.ConnectionFactrory;
import com.durgasoft.to.StudentTo;
pst.setString(2, sto.getSname());
pst.setString(3, sto.getSaddr());
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ResultSet rs = pst.executeQuery();
boolean b = rs.next();
Page
if(b == true) {
pst = con.prepareStatement("delete from student where sid = ?");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentTo.java
package com.durgasoft.to;
this.saddr = saddr;
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.factory;
import com.durgasoft.services.StudentService;
import com.durgasoft.services.StudentServiceImpl;
StudentDaoFactory.java
package com.durgasoft.factory;
import com.durgasoft.dao.StudentDao;
import com.durgasoft.dao.StudentDaoImpl;
ConnectionFactory.java
package com.durgasoft.factory;
import java.sql.Connection;
254
import java.sql.DriverManager;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}
public static Connection getConnection() {
return con;
}
}
To provide support for DAOs kind of implementations in Spring Applications, Spring has provided
a separate module called as ―Spring DAO‖.
Spring DAO modules has provided a set of predefined classes and interfaces in order to provide
DAO support in the form of ―org.springframework.dao‖ package.
255
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Q)In Enterprise Applications, to prepare Data Access Layer we have already Plain JDBC
tech. then what is the requirement to go for Spring JDBC Module?
Ans:
1.To prepare Data Access Layer in enterprise applications, if we use JDBC then we must take
explicit responsibility to prepare the steps load and register the driver, Establisg Connection,
creating Statement, executing SQl Queries and closing the resources like ResultSet, Statement
and Connection.
If we use Spring JDBC module to prepare Data Access Layer, we must take explicit responsibility
to write and execute SQL Queries only, not to take any responsibility to load and register driver,
connection establishment, creating Statement and closing the resources.
2.In case of Plain JDBC, almost all the exceptions are checked exceptions, we have to handle
them explicitly by providing some java code.
In case of Spring JDBC module, all the internal checked exceptions are converted into Unchecked
Exceptions which are defined by Spring DAO module , it is very simple to handle these unchecked
Exceptions.
In Spring JDBC Module, very good support is available for transactions, we may use Transaction
module also to provide transactions.
4.In Plain JDBC, to hold the results we are able to use only ResultSet object, which is not
implementing java.io.Serializable interface, which is not transferable in network.
In Spring JDBC, we are able to get results of SQL Queries in our required form like in the form of
RowSet, Collections, ..... which are implementing java.io.Serializable interface and which are
transferable in Network.
256
5.In plain JDBC, we are able to get Connections either by using DriverManager or by using
Datasource.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
6.In plain JDBC, to map records to Bean objects in the form of Collection Object we have to write
java code explicitly, no predefined support is provided by JDBC tech.
In case of Spring JDBC, to map Database records to Bean objects in the form of Collection Spring
JDBC has provided predefined support in the form of "RowMapper".
7.In Plain JDBC, no callback interfaces support is available to create and execute the sql queries
in PrfeparedStatement style.
In Spring JDBC, callback interfaces support is available to create and execute sql queries
in PreparedStatement style.
To prepare Data Access Layer in enterprise applications, Spring JDBC module has provided the
complete predefined library in the from of the following classes and interfaces in
"org.springframework.jdbc" and its sub packages.
JdbcTemplate
NamedParameterJdbcTemplate
SimpleJdbcTemplate
SimpleJdbcInsert and SimpleJdbcCall
SQL Mapping through SQLUpdate and SQLInsert
IN Spring configuration file we have to configure DataSource with the following properties.
driverClassName
url
257
username
password
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
JdbcTemplate class is providing basic environment to interact with Database like Loading Driver
class, Getting Connection between Java application and DB, Creating Statement ,
PreparedStatement and CallableStatement and closing the connection with the help of the
provided Datasource and JdbcTemplate class has provided the following methods to execute SQL
Queries.
1)For Non Select sql queries and DML SQL queries
public int update(String query)
2)For DDL Sql Queries
public void execute(String query)
3)For Select sql queries
public int queryForInt(String query)
public int queryForLong(String query)
public String queryForString(String query)
public Object queryForObject(String query)
public List query(String query)
public List queryForList(String query)
public Map queryForMap(String query)
public RowSet queryForRowSet(String query)
While performing retrival operations to convert data from ResultSet object[records] to Bean
objects Spring Framework has provided a predefined interface in the form of
"org.springframework.jdbc.core.RowMapper" which contains the following method .
Example
StudentDao.java
package com.durgasoft.dao;
import org.springframework.jdbc.core.JdbcTemplate;
import com.durgasoft.beans.Student;
public interface StudentDao {
258
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentDaoImpl.java
package com.durgasoft.dao;
import org.springframework.jdbc.core.JdbcTemplate;
import com.durgasoft.beans.Student;
@Override
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate ;
}
@Override
public String add(Student std) {
try {
jdbcTemplate.update("insert into student
values('"+std.getSid()+"','"+std.getSname()+"','"+std.getSaddr()+"')");
status = "success";
}catch(Exception e) {
status = "failure";
e.printStackTrace();
}
return status;
}
259
@Override
public Student search(String sid) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public String update(Student std) {
try {
jdbcTemplate.update("update student set
sname='"+std.getSname()+"',saddr='"+std.getSaddr()+"' where sid='"+std.getSid()+"'");
status="success";
jdbcTemplate.qu
}catch(Exception e) {
status="failure";
e.printStackTrace();
}
return status;
}
@Override
public String delete(String sid) {
try {
jdbcTemplate.update("delete from student where sid='"+sid+"'");
status="success";
} catch (Exception e) {
status="failure";
e.printStackTrace();
}
return status;
}
}
Student.java
package com.durgasoft.beans;
260
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentMapper.java
package com.durgasoft.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.durgasoft.beans.Student;
}
}
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Student;
import com.durgasoft.dao.StudentDao;
261
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
std.setSid("S-222");
std.setSname("Anil");
std.setSaddr("Hyd");
status = dao.add(std);
System.out.println("Student Insertion :"+status);
std.setSid("S-333");
std.setSname("Sekhar");
std.setSaddr("Hyd");
status = dao.add(std);
System.out.println("Student Insertion :"+status);
System.out.println();
//----Retriving Record-----
Student std1 = dao.search("S-111");
if(std1 == null) {
System.out.println("Student Search Status :NotExisted");
}else {
System.out.println("Student Details");
System.out.println("--------------------");
System.out.println("Student Id :"+std1.getSid());
System.out.println("Student Name :"+std1.getSname());
System.out.println("Student Address :"+std1.getSaddr());
}
System.out.println();
//----Updating a Record------
std.setSid("S-111");
std.setSname("XXX");
262
std.setSaddr("YYY");
status = dao.update(std);
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
//----Deleting a record-----
status = dao.delete("S-111");
System.out.println("Student Deletion :"+status);
}
}
In Spring JDBC Applications, we will use positional parameters[?] also in sql queries which we are
providing along with JdbcTemplate class provided query execution methods.
If we provide positional parameters in sql queries then JdbcTemplate class will use
"PreparedStatement" internally to execute sql query instead of Statement.
To provide values to the Positional parameters in SQL Queries we have to use Object[] with
values as parametyer to all JdbcTemplate class provided query execution methods.
Example:
StudentDao.java
package com.durgasoft.dao;
import org.springframework.jdbc.core.JdbcTemplate;
import com.durgasoft.beans.Student;
263
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentDaoImpl.java
package com.durgasoft.dao;
import org.springframework.jdbc.core.JdbcTemplate;
import com.durgasoft.beans.Student;
@Override
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate ;
}
@Override
public String add(Student std) {
try {
String query = "insert into student values(?,?,?)";
jdbcTemplate.update(query, new Object[] {std.getSid(), std.getSname(),
std.getSaddr()});
status = "success";
}catch(Exception e) {
status = "failure";
e.printStackTrace();
}
return status;
264
}
Page
@Override
public Student search(String sid) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public String update(Student std) {
try {
jdbcTemplate.update("update student set sname=?, saddr=? where
sid=?",new Object[] { std.getSname(), std.getSaddr(), std.getSid()});
status="success";
}catch(Exception e) {
status="failure";
e.printStackTrace();
}
return status;
}
@Override
public String delete(String sid) {
try {
jdbcTemplate.update("delete from student where sid=?", new Object[] {sid});
status="success";
} catch (Exception e) {
status="failure";
e.printStackTrace();
}
return status;
}
}
applicationContext.xml
265
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="durga"/>
</bean>
</beans>
StudentMapper.java
package com.durgasoft.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.durgasoft.beans.Student;
std.setSname(rs.getString("SNAME"));
std.setSaddr(rs.getString("SADDR"));
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}
}
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Student;
import com.durgasoft.dao.StudentDao;
std.setSid("S-222");
std.setSname("Anil");
std.setSaddr("Hyd");
status = dao.add(std);
System.out.println("Student Insertion :"+status);
std.setSid("S-333");
std.setSname("Sekhar");
std.setSaddr("Hyd");
status = dao.add(std);
267
//----Retriving Record-----
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
//----Updating a Record------
std.setSid("S-111");
std.setSname("XXX");
std.setSaddr("YYY");
status = dao.update(std);
System.out.println("Student Updation :"+status);
System.out.println();
//----Deleting a record-----
status = dao.delete("S-111");
System.out.println("Student Deletion :"+status);
}
NamedParameterJdbcTemplate
NamedParameterJdbcTemplate class is same as JdbcTemplate class , but,
NamedParameterJdbcTemplate class is able to define and run sql queries with Named
Parameters instead of positional parameters.
EX:
String query = "insert into student values(:sid, :sname, :saddr)";
Where :sid, :sname, :saddr are named parameters for which we have to provide values.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To provide values to the Named parameters Spring has provided the following two implementation
classes for SqlParameterSoure interface.
a)MapSqlParameterSource
b)BeanPropertySqlParameterSource
To provide values to the named parameters if we want to use MapSqlParameterSource then first
we have to create object for MapSqlParameterSource and we have to use the following method to
add values to the named parameters.
EX:
EX:
std.setSname("AAA");
std.setSaddr("Hyd");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: JdbcTemplate is allowing DataSource object injection through setter method, but,
NamedParameterJdbcTemplate class is allowing DataSource object injection through Constructor
Dependency Injection.
Example
CustomerDao.java
package com.durgasoft.dao;
import com.durgasoft.beans.Customer;
CustomerDaoImpl.java
package com.durgasoft.dao;
import java.util.HashMap;
import java.util.Map;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.durgasoft.beans.Customer;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public Customer search(String cid) {
String query = "select * from customer where cid=:cid";
return c;
}
@Override
public String update(Customer c) {
String query = "update customer set CNAME=:cname, CADDR=:caddr where
CID=:cid";
SqlParameterSource paramSource = new BeanPropertySqlParameterSource(c);
namedParameterJdbcTemplate.update(query, paramSource);
return "SUCCESS";
}
@Override
public String delete(String cid) {
String query = "delete from customer where cid=:cid";
271
return "SUCCESS";
}
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.beans;
CustomerMapper.java
package com.durgasoft.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
272
import com.durgasoft.beans.Customer;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}
}
applicationContext.xml
</beans>
Page
Test.java
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
import com.durgasoft.beans.Customer;
import com.durgasoft.dao.CustomerDao;
Customer c1 = dao.search("C-111");
System.out.println("Customer Details");
System.out.println("--------------------");
System.out.println("Customer Id :"+c1.getCid());
System.out.println("Customer Name :"+c1.getCname());
System.out.println("Customer Address :"+c1.getCaddr());
System.out.println();
Customer c2 = new Customer();
c2.setCid("C-111");
c2.setCname("BBB");
c2.setCaddr("Sec");
status = dao.update(c2);
System.out.println("Student Updation Status :"+status);
Customer c3 = dao.search("C-111");
System.out.println("Customer Updated Details");
System.out.println("--------------------");
System.out.println("Customer Id :"+c3.getCid());
System.out.println("Customer Name :"+c3.getCname());
System.out.println("Customer Address :"+c3.getCaddr());
274
System.out.println();
status = dao.delete("C-111");
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
SimpleJdbcTemplate class was provided in Spring2.5 version only and it was deprecated in the
later versions Spring3.x and Spring4.x , in Spring5.x version SimpleJdbcTemplate class was
removed.
If we want to use SimpleJdbcTemplate class we have to use Spring2.5 version jar files in Spring
applications.
To execute SQL queries , SimpleJdbcTemplate class has provided the following methods.
Example:
EmployeeDao.java
package com.durgasoft.dao;
import com.durgasoft.beans.Employee;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeDaoImpl.java
package com.durgasoft.dao;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import com.durgasoft.beans.Employee;
}
@Override
public String add(Employee emp) {
String query = "insert into emp1
values("+emp.getEno()+",'"+emp.getEname()+"',"+emp.getEsal()+",'"+emp.getEaddr()+"')";
simpleJdbcTemplate.getJdbcOperations().execute(query);
status = "SUCCESS";
return status;
}
@Override
public Employee search(int eno) {
String query = "select * from emp1 where eno=?";
Employee emp = simpleJdbcTemplate.queryForObject(query, new
EmployeeMapper(), eno);
return emp;
}
@Override
public String update(Employee emp) {
String query = "update emp1 set ename=?, esal =?, eaddr=? where eno=?";
simpleJdbcTemplate.update(query, emp.getEname(), emp.getEsal(),
emp.getEaddr(), emp.getEno());
276
status = "SUCCESS";
return status;
Page
}
@Override
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
return status;
}
}
Employee.java
package com.durgasoft.beans;
}
public void setEaddr(String eaddr) {
Page
this.eaddr = eaddr;
}
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import com.durgasoft.beans.Employee;
}
}
applicationContext.xml
</bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
System.out.println("--------------------");
System.out.println("Employee Number :"+emp1.getEno());
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Spring JDBC applications, if we want to get XXXTemplate classes with out declaring Template
properties and corresponding setXXX() methods we have to use DAO Support classes provided
Spring JDBC module.
There are three types of DAOSupport classes inorder to get Template object in DAO classes.
1.JdbcDaoSupport
2.NamedParameterJdbcDaoSupport
3.SimpleJdbcDaoSupport
Where JdbcDaoSupport class will provide JdbcTemplate reference in DAO classes by using the
following method.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
public String insert(int eno, String ename, float esal, String eaddr){
getJdbcTemplate().update("insert into emp1 values("+eno+",'"+ename+"',"+esal+",'"+eaddr+"')");
return "SUCCESS";
}
----
----
}
To perform Batch Updations in Spring JDBC we have to use the following method from
JdbcTemplate class.
Where setValues() method will be executed for each and every record to set values to the
positional parameters existed in PreparedStatement object by getting values from the provided
List.
Employee.java
package com.durgasoft.beans;
281
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeDao.java
package com.durgasoft.dao;
import java.util.List;
282
import com.durgasoft.beans.Employee;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeDaoImpl.java
package com.durgasoft.dao;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import com.durgasoft.beans.Employee;
}
@Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Jdbc.properties
jdbc.driverClassName = oracle.jdbc.OracleDriver
jdbc.url = jdbc:oracle:thin:@localhost:1521:xe
jdbc.username = system
jdbc.password = durga
applicationContext.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
284
<context:property-placeholder location="jdbc.properties"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
</beans>
Test.java
package com.durgasoft.test;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
e3.setEaddr("Hyd");
list.add(e3);
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}
}
To use SimpleJdbcCall in Spring Jdbc applications we have to use the following steps.
1)Create DAO interface and its implementation class.
2)IN DAO implementation class, we have to declare DataSource and JdbcTemplate and its
respective setter method .
3)In side setter method we have to create SimpleJdbcCall object.
SimpleJdbcCall jdbcCall = new SimpleJdbcCall();
jdbcCall.withProcedureName("proc_Name");
4)Configure DataSource and DAO implementation class in beans configuration file.
5)Access "execute" method by passing IN type parameters values in the form of
"SQLParameterSource".
public Map execute(Map m)
pubhlic Map execute(SqlParameterSource paramSource)
public Map execute(Object ... obj)
Employee.java
286
package com.durgasoft.beans;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeDao.java
package com.durgasoft.dao;
import java.util.Map;
287
import com.durgasoft.beans.Employee;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeDaoImpl.java
package com.durgasoft.dao;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.jdbc.core.namedparam.MapSqlParameterSourc
e;
import
org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import com.durgasoft.beans.Employee;
}
@Override
public void create(Employee emp) {
try {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql= "insert into emp1 values("+emp.getEno()+",'"+emp.getEname()+"',"+emp.getEsal()+"
,'"+emp.getEaddr()+"')";
jdbcTemplate.update(sql);
}catch(Exception e) {
e.printStackTrace();
288
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
// System.out.println(map);
return map.get("SAL");
}
}
applicationContext.xml
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-
beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-
context.xsd">
<bean id="empDao" class="com.durgasoft.dao.EmployeeDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id = "dataSource" class =
"org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "oracle.jdbc.OracleDriver"/>
<property name = "url" value = "jdbc:oracle:thin:@localhost:1521:xe"/>
<property name = "username" value = "system"/>
<property name = "password" value = "durga"/>
</bean>
</beans>
Test.java
289
package com.durgasoft.test;
Page
import org.springframework.context.ApplicationContext;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
System.out.println(emp3.getEno()+"---->"+salary3);
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to use CURSOR types in Stored Procedures inorder to retrive multiple Records data
then we have to use the following method on SimpleJdbcCall reference.
Example:
Employee.java
package com.durgasoft.beans;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeDao.java
package com.durgasoft.dao;
import java.util.Map;
}
292
EmployeeDaoImpl.java
Page
package com.durgasoft.dao;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
import javax.sql.DataSource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import com.durgasoft.beans.Employee;
//System.out.println(map);
return map;
}
}
applicationContext.xml
</bean>
<bean id = "dataSource"
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import java.util.ArrayList;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
System.out.println("Employee Details");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-----------------------------");
for(Employee e: list) {
System.out.println(e.getEno()+"\t"+e.getEname()+"\t"+e.getEsal()+"\t"+e.getEaddr());
}
}
294
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Spring JDBC Applications, to process BLOB and CLOB Data, Spring JDBC has provided the
following three interfaces mainly.
1.AbstractLobCreatingPreparedStatementCallback
--> It will be used to store Blob and Clob related data in Database.
protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException,
DataAccessException
2.AbstractLobStreamingResultSetExtractor
--> It will be used to retrive BLOB and CLOB data from database.
streamData(ResultSet rs)throws SQLException, IOException, DataAccessException
3.LobCreator
--> It contains the following methods to prepare Binary stream and character streams to send blob
and clob data to database.
setBlobAsBinaryStream()
setClobAsCharacterStream()
4.LobHolder
--> It contains the following methods to get Binary stream and character stream to get blob and
clob data.
getBlobAsBinaryStream()
getClobAsCharacterStream()
Example:
Employee.java
package com.durgasoft.beans;
import java.io.File;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeDao.java
package com.durgasoft.dao;
import com.durgasoft.beans.Employee;
EmployeeDaoImpl.java
Page
package com.durgasoft.dao;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback;
import org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.util.FileCopyUtils;
import com.durgasoft.beans.Employee;
AbstractLobCreatingPreparedStatementCallback(lobHolder) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@Override
public Employee readEmployee() {
Employee emp = new Employee();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}
});
return emp;
}
applicationContext.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="lobHolder" class="org.springframework.jdbc.support.lob.DefaultLobHandler">
</bean>
<context:property-placeholder location="jdbc.properties"/>
</beans>
299
jdbc.properties
Page
jdbc.driverClassName = oracle.jdbc.OracleDriver
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import java.io.File;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
System.out.println("Employee Resume
:"+emp2.getEmp_Resume().getAbsolutePath());
Page
}
}
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To overcome the above problem we have to use Connection Pooling in applications.In Connection
pooling we will create a set of Connection object in the form of a pool at the application startup
time and we will reuse that COnnection objects while executing applications , when database
operations are completed then we will send back that connection objects to Pool object with out
destroying that connection objects.
In SPring JDBC applications there are three approaches to provide connection pooling.
If we want to use default Connection Pooling mechanism in SPring JDBC application then we
have to configure org.springframework.jdbc.datasource.DriverManagerDataSource in beans
configuration file with the following properties .
1.driverClassName
2.url
3.username
4.password
---
---
EX:
301
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Spring JDBC applications we are able to use the following third party connection pooling
mechanisms
1.Apache DBCP
2.C3P0
3.Proxool
1.Apache DBCP:
1.driverClassName
2.url
3.username
4.password
5.initialSize:It will take Initial pool size.
6.maxTotal: It will allow the specified no of max connections.
---
---
EX:
---
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="root" />
<property name="password" value="root" />
<property name="initialSize" value="20" />
<property name="maxTotal" value="30" />
</bean>
Note: To use this mechanism in Spring JDBC Applications then we have to add the following two
jar files to Library.
302
1.commons-dbcp2-2.2.0.jar
2.commons-pool2-2.5.0.jar
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1.driverClass
2.jdbcUrl
3.user
4.password
5.minPoolSize:It will take Initial pool size.
6.maxPoolSize: It will allow the specified no of max connections.
7.maxStatements: Max statements it allows.
8.testConnectionOnCheckOut:true/false for Checking Connection before use.
---
---
EX:
Note: To use this mechanism in Spring JDBC Applications then we have to add the following two
jar files to Library.
1.c3p0-0.9.5.2.jar
2.mchange-commons-java-0.2.11.jar
3.Proxool:
1.driver
Page
2.driverUrl
3.user
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: To use this mechanism in Spring JDBC Applications then we have to add the following two
jar files to Library.
1.proxool-0.9.1.jar
2.proxool-cglib.jar
Example:
Employee.java
package com.durgasoft.beans;
}
public void setEname(String ename) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeDao.java
package com.durgasoft.dao;
import com.durgasoft.beans.Employee;
EmployeeDaoImpl.java
package com.durgasoft.dao;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import com.durgasoft.beans.Employee;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}
}
applicationContext.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
public class Test {
emp.setEno(111);
emp.setEname("Nag");
Page
emp.setEsal(5000);
emp.setEaddr("Hyd");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
}
}
JNDI is existed inside the application Servers to provide any resource with Global Scope, that is,
JNDI will share any resource like "DataSource" to all the applications which are running in the
present application server.
In general, almost all the Application Servers are having their own Connection Pooling
mechanisms, if we want to use Application Servers provided Connection pooling mechanisms we
have to use the following steps.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Database Name: xe
Host Name: localhost
Page
Port : 1521
Database User Name: system
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To use Weblogic Server provided Connection Pooling mechanism in Spring JDBC Application
then we have to use the following jars along with the regular jars.
1)weblogic.jar
2)spring-jdbc-4.0.4.RELEASE.jar
3)spring-tx-4.0.4.RELEASE.jar
To use Weblogic Server provided Connection Pooling mechanism in Spring JDBC Application
then we have to provide the following DataSource configuration in beans configuration file.\
Example:
Employee.java
package com.durgasoft.beans;
310
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeDao.java
package com.durgasoft.dao;
import com.durgasoft.beans.Employee;
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
package com.durgasoft.dao;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import com.durgasoft.beans.Employee;
}
}
applicationContext.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.remoting.rmi.JndiRmiProxyFactoryBean;
import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
{SPRING AOP}
314
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
315
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Aspect Orientation:
EX:
If we use the above style of implementation then we are able to get the following problems.
1. It is very difficult to modify the services logic, it required to modify in all business method.
2. It will not provide Sharability
3. It will not provide Code Reusability.
4. It will provide tightly coupled design.
316
applied on Object Oriented Programming in order to get loosely coupled design and in order to
improve sharability and Reusability.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Aspect
2. Advice
3. Join point
4. Pointcut
5. Target
6. Proxy
7. Weaving
8. Introduction
1. Aspect:
An Aspect is the concern or a service which we want to implement in the application such as
logging, transactional , Security etc.
2. Advice:
An Advice is the actual implementation of the aspect. Aspect is a concept and Advice is the
concrete implementation of the concept.
3. Join point:
A JoinPoint is a point in the execution of the program where an aspect can be applied. It could be
before/after executing the method, before throwing an exception, before/after modifying an
instance variable etc.
4. Pointcut:
PointCuts tell on which join points the aspect will be applied. An advice is associated with a point
cut expression and is applied to a join point which matches the point cut expression.
5.Target:
6.Proxy:
318
Proxy is the object which is created by the framework after applying the advice on the target
Page
object.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
7. Weaving:
Weaving is the process of applying the aspect on the target object to product the proxy object.
Weaving can be done at compile time, class loading time or runtime. Spring AOP supports
weaving at runtime.
8. Introduction:
An Introduction allows adding new methods or attributes to existing classes. The new method and
instance variable can be introduced to existing classes without having to change them, giving
them new state and behavior.
319
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Advice is the implementation of Aspect. An Advice provides the code for implementation of the
service or Aspect. As an example consider logging service, logging is an Aspect and Advice
denotes the implementation of Log4j.
In general, all the advices code will not be included in business methods at compile time, these
services will be included at runtime.
1. Before Advice:
Before advice contains service/Aspect implementation , it will be executed before executing the
respective business method.
To represent Before Advice, Spring Framework has provided a predefined interface in the form of
"org.springframework.aop.MethodBeforeAdvice".
If we want to use Before Advice in Spring applications , first, we have to declare an user defined
class, it must implement org.springframework.aop.MethodBeforeAdvice interface and we must
provide implementation for the following method provided by MethodBeforeAdvice interface.
Note: The services which are implemented in before() method are executed at before executing
business logic.
320
Example:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
It is same as Before Advice, But this advice contains services which are applied after completion
of our business method logic
To create an after returning advice in spring, we have to declare an user defined class, it must
implement org.springframework.aop.AfterReturningAdvice and we must implement the following
method.
Where first parameter is representning return value in the form of Object type.
Where second parameter is able to represent business method parameters in the form of
Object[].
Where third parameter is representing Target Object.
EX:
Note: In Schema Based implementation, After Advice and After-Returning Advice are same, but,
in Annotation approach both are different.
This advice will be executed after throwing an exception from the business method.
To represent After-Throwing Advice, Spring Framework has provided a predefined interface in the
form of "org.springframework.aop.ThrowsAdvice".
If we want to use After Throwing Advice in Spring applications , first, we have to declare an user
321
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
5. Around Advice
Around Advice will be executed before and after executing the business method.
Around Advice is combination of both Before and After Advice.
Around Advice is not given by spring framework and it is from Open Source implementation
called AOP alliance.
Around Advice can be used by any framework which supports AOP.
To represent Around Advice, Spring AOP Aliance has provided a predefined interface in the form
of org.aopalliance.intercept.MethodInterceptor.
MethodINterceptor has provided the following method inorder to provide services before and after
execution of the business method.
In Around Advice, we will implement Before and After Advice in invoke() method, in invoke()
method will provide before advice logic before calling proceed() method and we will provide After
322
Note: Around Advice can access the return value of business method and it can modify the value
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
PointCut
PointCut defines at what Joinpoints Advices has to be applied, instead of defining advices at all
join points.
If we want to use PointCuts in AOP based applications then we have to configure that pointcuts in
Spring configuration File.
To configure Pointcuts in configuration file then we have to use the following two types of
PointCuts.
1. Static Pointcut
2. Dynamic Pointcut
1. Static Pointcut:
Static pointcuts define advice that is always executed. Static pointcuts are based on method and
target class, and cannot take into account the method's arguments. Static pointcuts are sufficient -
and best - for most usages. It's possible for Spring to evaluate a static pointcut only once, when a
method is first invoked: after that, there is no need to evaluate the pointcut again with each
323
method invocation.
Page
To represent Pointcuts , Spring framework has provided a predefined interface in the form of
"org.springframework.aop.PointCut".
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2. Dynamic Pointcut:
Dynamic pointcuts determine if advice should be executed by examining the runtime method
arguments.
Dynamic pointcuts are costlier to evaluate than static pointcuts. They take into account method
arguments, as well as static information. This means that they must be evaluated with every
method invocation; the result cannot be cached, as arguments will vary.
To represent Dynamic Pointcut Spring has provided the following predefined class.
1. ControlFlowPointcut
2. DynamicMethodMatcherPointcut
If we want to use Pointcuts in Spring applications then we have to configure Pointcut and Advisor
in apring configuration file.
In spring applications, we will use "DefaultPointCutAdvosor" inorder to suggest the advices to the
Pointcuts.
7. </property>
8. </bean>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.beans;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eemail;
8. private String emobile;
9.
10. public int getEno() {
11. return eno;
12. }
325
15. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeService.java
1. package com.durgasoft.bo;
2.
3. import com.durgasoft.beans.Employee;
4.
5. public interface EmployeeService {
6. public void displayEmployee(Employee emp);
7. public void getEmployeeDetails(Employee emp);
8. }
326
EmployeeServiceImpl.java
Page
1. package com.durgasoft.bo;
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeValidator.java
1. package com.durgasoft.advice;
2.
3. import java.lang.reflect.Method;
4.
5. import org.springframework.aop.MethodBeforeAdvice;
6.
7.
8. import com.durgasoft.beans.Employee;
9.
327
12. @Override
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ApplicationContext.java
15. </bean>
16.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.springframework.aop.support.DefaultPointcutAdvisor;
329
4. import org.springframework.aop.support.NameMatchMethodPointcut;
5. import org.springframework.context.ApplicationContext;
Page
6. import org.springframework.context.support.ClassPathXmlApplicationContext;
7.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Student.java
1. package com.durgasoft.beans;
2.
3. public class Student {
4. private String sname;
5. private String squal;
6. private String semail;
7. private String smobile;
8.
9. public String getSname() {
10. return sname;
11. }
12. public void setSname(String sname) {
13. this.sname = sname;
14. }
15. public String getSqual() {
16. return squal;
17. }
330
20. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
InstituteService.java
1. package com.durgasoft.bo;
2.
3. import com.durgasoft.beans.Student;
4.
5. public interface InstituteService {
6. public void enquiry(Student std, String course_Name);
7. public void registration(Student std, String course_name);
8. }
InstituteServiceImpl.java
1. package com.durgasoft.bo;
2.
3. import com.durgasoft.beans.Student;
4.
5. public class InstituteServiceImpl implements InstituteService {
6.
7. @Override
8. public void enquiry(Student std, String course_Name) {
9. System.out.println("Student Enquiry Details");
10. System.out.println("-----------------------------");
331
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ThanqAdvice.java
1. package com.durgasoft.advice;
2.
3. import java.lang.reflect.Method;
4.
5. import org.springframework.aop.AfterReturningAdvice;
6.
7. import com.durgasoft.beans.Student;
8.
9. public class ThanqAdvice implements AfterReturningAdvice {
10.
11. @Override
12. public void afterReturning(Object return_Val, Method method, Object[] params, Object t
arget) throws Throwable {
13. Student std = (Student)params[0];
14. String course_Name = (String)params[1];
15. System.out.println("ThanQ "+std.getSname()+" for your course "+method.getName()+"
on "+course_Name);
16. System.out.println("Durgasoft Team will contact with you for the Course Schedule");
17. }
18. }
ApplicationContext.java
2. <beans xmlns="http://www.springframework.org/schema/beans"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
Page
4. xmlns:aop="http://www.springframework.org/schema/aop"
5. xsi:schemaLocation="
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5.
6. import com.durgasoft.beans.Student;
7. import com.durgasoft.bo.InstituteService;
333
8.
9. public class Test {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Movie.java
1. package com.durgasoft.beans;
2.
3. public class Movie {
4. private String movie_Name;
5. private String show_Time;
6. private int price;
7.
8. public String getMovie_Name() {
9. return movie_Name;
10. }
11. public void setMovie_Name(String movie_Name) {
12. this.movie_Name = movie_Name;
13. }
14. public String getShow_Time() {
15. return show_Time;
16. }
17. public void setShow_Time(String show_Time) {
18. this.show_Time = show_Time;
19. }
20. public int getPrice() {
21. return price;
22. }
23. public void setPrice(int price) {
334
26.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
MovieService.java
1. package com.durgasoft.bo;
2.
3. import com.durgasoft.beans.Movie;
4.
5. public interface MovieService {
6. public void playMovie(Movie movie)throws Exception;
7. }
MovieServiceImpl.java
1. package com.durgasoft.bo;
2.
3. import com.durgasoft.beans.Movie;
4.
5. public class MovieServiceImpl implements MovieService {
6.
7. @Override
8. public void playMovie(Movie movie)throws Exception {
9. System.out.println("Movie Details");
10. System.out.println("----------------");
11. System.out.println("Movie Name :"+movie.getMovie_Name());
12. System.out.println("Movie Time :"+movie.getShow_Time());
13. System.out.println("Price :"+movie.getPrice());
14. throw new RuntimeException("Power Failure Occurred");
15. }
16.
17. }
MoneyReturnAdvice.java
1. package com.durgasoft.advice;
2.
3.
4. import java.lang.reflect.Method;
335
5.
6. import org.springframework.aop.ThrowsAdvice;
Page
7.
8.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ApplicationContext.java
27. </list>
28. </property>
Page
29. </bean>
30. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.test;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5.
6. import com.durgasoft.beans.Movie;
7. import com.durgasoft.bo.MovieService;
8.
9. public class Test {
10.
11. public static void main(String[] args) {
12. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
xt.xml");
13. Movie movie = (Movie)context.getBean("movieBean");
14.
15. MovieService movie_Service = (MovieService) context.getBean("proxy");
16. try {
17. movie_Service.playMovie(movie);
18. } catch (Exception e) {
19.
20. }
21.
22. }
23.
24. }
Account.java
1. package com.durgasoft.beans;
2.
3. public class Account {
4. private String accNo;
5. private String accName;
6. private String accType;
7. private int balance;
337
8.
9. public String getAccNo() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Cheque.java
1. package com.durgasoft.beans;
2.
3. public class Cheque {
4. private String cheque_No;
5. private int amount;
6.
7. public String getCheque_No() {
8. return cheque_No;
9. }
10. public void setCheque_No(String cheque_No) {
11. this.cheque_No = cheque_No;
12. }
338
15. }
16. public void setAmount(int amount) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
TransactionService.java
1. package com.durgasoft.bo;
2.
3. import com.durgasoft.beans.Account;
4. import com.durgasoft.beans.Cheque;
5.
6. public interface TransactionService {
7. public void debit(Account acc, Cheque cheque );
8. }
TransactionServiceImpl.java
1. package com.durgasoft.bo;
2.
3. import com.durgasoft.beans.Account;
4. import com.durgasoft.beans.Cheque;
5.
6. public class TransactionServiceImpl implements TransactionService {
7.
8. @Override
9. public void debit(Account acc, Cheque cheque) {
10. int initial_Amount = acc.getBalance();
11. int debit_Amount = cheque.getAmount();
12. int total_Amount = initial_Amount - debit_Amount;
13. acc.setBalance(total_Amount);
14. System.out.println("*******Transaction Success*******************");
15. System.out.println("*******Amount is debited from Account********");
16. }
17. }
ChequeClearenceAdvice.java
1. package com.durgasoft.advice;
2.
339
3. import org.aopalliance.intercept.MethodInterceptor;
4. import org.aopalliance.intercept.MethodInvocation;
Page
5.
6.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.java
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5.
6. import com.durgasoft.beans.Account;
7. import com.durgasoft.beans.Cheque;
8. import com.durgasoft.bo.TransactionService;
9.
10. public class Test {
11.
12. public static void main(String[] args) {
13. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
xt.xml");
14. Account account = (Account) context.getBean("accBean");
15. Cheque cheque = (Cheque) context.getBean("chequeBean");
16. TransactionService tx_Service = (TransactionService) context.getBean("proxy");
341
19.
20. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Declarative approach
2. @AspectJ annotation style approach
1. Declarative approach:
IN declarative approach, we will use Aspectj Namespace tags inorder to declare aspects, advices,
Pointcuts,......
In declarative configuration approach, all the aspect declarations are placed under the
<aop:config/> tag.
applicationContext.xml
Note:The aop:config will contain all aspect configurations and all specific method-related
configurations, such as around, pointcut, and so on.
342
1. Declaring Aspects:
To declare aspects by using AspectJ namespace tags we have to use the following tags.
Page
<aop:config>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
2. Declaring Pointcuts:
A pointcut helps in determining the join points to be executed with different advices.
To declare pointcuts we have to use the following tags in configuration file.
<aop:config>
<aop:aspect id="----" ref="----">
<aop:pointcut id="----" expression="------"/>
...
</aop:aspect>
</aop:config>
Where "id" attribute in <aop:pointcut> tag will take identity to the Pointcut.
Where "expression" attribute in <aop:pointcut> will take AspectJ expression to define
343
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
1. <aop:config>
2. <aop:aspect id="loggingAspect" ref="loggingAspectBean">
3.
4. <aop:pointcut id="loggingOperation" expression="execution(* com.durgasoft.service
.EmployeeService.*(..))" />
5.
6. </aop:aspect>
7. </aop:config>
8.
9. <bean id="loggingAspectBean" class="com.durgasoft.aspect.EmployeeCRUDLoggingAspe
ct" />
1. execution (* com.durgasoft.service.EmployeeService.*(..))
The above Expression matches all of the methods declared in the EmployeeService
interface
The above expression matches methods with any modifier (public, protected, and private)
and any return type.
The two dots in the argument list match any number of arguments.
2.execution(* EmployeeService.*(..))
The above Expression matches all methods of EmployeeService interface which are
existed in the present package with any type of access modifier and with any return type.
3.execution(public * EmployeeService.*(..))
The above Expression matches all public methods of EmployeService interface with any
return type.
4.execution(public Employee EmployeeService.*(..))
The above Expression matches all public methods of EmployeeService interface with
Employee return type.
return type and with Employee as First parameter and Integer type parameter as second.
Declaring Advices:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
All the above advices tags contains "method" and "pointcut-ref" attributes, where "method" atribute
will take advice method and "pointcut-ref" attribute will take Pointcut reference whic we declared in
Configuration file.
EX:
1. <beans xmlns="http://www.springframework.org/schema/beans"
2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3. xmlns:aop="http://www.springframework.org/schema/aop"
4. xsi:schemaLocation="http://www.springframework.org/schema/beans
5. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
6. http://www.springframework.org/schema/aop/
7. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
8.
9. <aop:config>
10.
11. <!-- Spring AOP Pointcut definitions -->
12. <aop:pointcut id="loggingOperation"
13. expression="execution(* com.durgasoft.service.EmployeeService.*(..))" />
14.
15. <!-- Spring AOP aspect -->
16. <aop:aspect id="loggingAspect" ref="loggingAspectBean">
17.
18. <!-- Spring AOP advises -->
19. <aop:before pointcut-ref="loggingOperation" method="logBefore" />
20. <aop:after pointcut-ref="loggingOperation" method="logAfter" />
21.
22. </aop:aspect>
23.
345
24.
25. </aop:config>
Page
26.
27. <!-- Spring AOP aspect instances -->
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.beans;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
8.
9. public int getEno() {
10. return eno;
11. }
12. public void setEno(int eno) {
13. this.eno = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. this.ename = ename;
346
20. }
21. public float getEsal() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeService.java
1. package com.durgasoft.service;
2.
3. import com.durgasoft.beans.Employee;
4.
5. public interface EmployeeService {
6. public String createEmployee(Employee emp)throws Exception;
7. public Employee searchEmployee(int eno);
8. public String updateEmployee(Employee emp);
9. public String deleteEmployee(Employee emp);
10. }
EmployeeServiceImpl.java
1. package com.durgasoft.service;
2.
3. import com.durgasoft.beans.Employee;
4.
5. public class EmployeeServiceImpl implements EmployeeService {
6.
7. @Override
8. public String createEmployee(Employee emp){
9. System.out.println("Employee "+emp.getEno()+" Inserted Successfully from createEm
ployee()");
347
10.
11. return "Success";
Page
12. }
13.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
LoggingAspectBean.java
1. package com.durgasoft.aspects;
2.
3. import org.aspectj.lang.JoinPoint;
4. import org.aspectj.lang.ProceedingJoinPoint;
5. import org.aspectj.lang.annotation.After;
6. import org.aspectj.lang.annotation.AfterReturning;
7. import org.aspectj.lang.annotation.AfterThrowing;
8. import org.aspectj.lang.annotation.Around;
9. import org.aspectj.lang.annotation.Aspect;
10. import org.aspectj.lang.annotation.Before;
11. public class LoggingAspectBean {
12. public void before(JoinPoint jp) {
13. System.out.println("Before "+jp.getSignature().getName()+" method execution");
14. }
15. public void after(JoinPoint jp) {
348
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5.
6. import com.durgasoft.beans.Employee;
7. import com.durgasoft.service.EmployeeService;
8.
9. public class Test {
10. public static void main(String[] args) {
11. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
xt.xml");
12. EmployeeService empService = (EmployeeService)context.getBean("empService");
13. Employee emp = (Employee) context.getBean("empBean");
14. String message = "";
15. try {
16. message = empService.createEmployee(emp);
17. } catch (Exception e) {
350
18.
19. }
Page
20. System.out.println(message);
21. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
Show.java
1. package com.durgasoft.beans;
2.
3. public class Show {
4. private String name;
5. private String time;
6. private int price;
7.
8. public String getName() {
9. return name;
10. }
11. public void setName(String name) {
12. this.name = name;
13. }
14. public String getTime() {
15. return time;
16. }
17. public void setTime(String time) {
18. this.time = time;
19. }
20. public int getPrice() {
21. return price;
22. }
23. public void setPrice(int price) {
24. this.price = price;
25. }
26. }
ShowService.java
1. package com.durgasoft.service;
2.
3. import com.durgasoft.beans.Show;
4.
351
7. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ShowAspect.java
1. package com.durgasoft.aspect;
2.
3. import org.aspectj.lang.ProceedingJoinPoint;
4.
5. public class ShowAspect {
6. public void before() {
7. System.out.println("Get Tickets for the Show");
8. }
9. public void around(ProceedingJoinPoint jp) {
10. System.out.println("Show is Ready To start, Take Chairs and Keep mobiles in Silent m
ode");
11. try {
12. jp.proceed();
13. } catch (Throwable e) {
14. e.printStackTrace();
15. }
352
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
rvice.runShow(com.durgasoft.beans.Show))" id="showPointcut"/>
25.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5.
6. import com.durgasoft.beans.Show;
7. import com.durgasoft.service.ShowService;
8.
9. public class Test {
10.
11. public static void main(String[] args) {
12. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
xt.xml");
13. Show show = (Show) context.getBean("showBean");
14. ShowService showService = (ShowService) context.getBean("showService");
15. try {
16. showService.runShow(show);
17. } catch (RuntimeException e) {
18. //System.out.println(e.getMessage());
19. }
20. }
21. }
Business method.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: To activate all the above annotations in Spring applications we have to use <aop:aspectj-
autoproxy/> tag in spring configuration file.
Example:
Account.java
1. package com.durgasoft.beans;
2.
3. public class Account {
4. private String accNo;
5. private String accName;
6. private String accType;
7. private int balance;
8.
9. public String getAccNo() {
10. return accNo;
11. }
12. public void setAccNo(String accNo) {
13. this.accNo = accNo;
14. }
15. public String getAccName() {
16. return accName;
17. }
18. public void setAccName(String accName) {
19. this.accName = accName;
20. }
21. public String getAccType() {
22. return accType;
23. }
355
26. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
TransactionService.java
1. package com.durgasoft.service;
2.
3. import com.durgasoft.beans.Account;
4. import com.durgasoft.exceptions.InsufficientFundsException;
5.
6. public interface TransactionService {
7. public String withdraw(Account acc, int wd_Amt)throws InsufficientFundsException;
8. }
TransactionServiceImpl.java
1. package com.durgasoft.service;
2.
3. import org.springframework.stereotype.Component;
4.
5. import com.durgasoft.beans.Account;
6. import com.durgasoft.exceptions.InsufficientFundsException;
7.
8. @Component("transaction")
9. public class TransactionServiceImpl implements TransactionService {
10.
11. @Override
12. public String withdraw(Account acc, int wd_Amt) throws InsufficientFundsException {
13. String status = "";
14. if(acc.getBalance() > wd_Amt) {
15. int total_Bal = acc.getBalance() - wd_Amt;
16. acc.setBalance(total_Bal);
356
19. }else {
20. status = "FAILURE";
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
InsufficientFundsException.java
1. package com.durgasoft.exceptions;
2.
3. public class InsufficientFundsException extends Exception {
4. public InsufficientFundsException(String desc) {
5. super(desc);
6. }
7. }
TransactionAspect.java
1. package com.durgasoft.aspect;
2.
3. import org.aspectj.lang.JoinPoint;
4. import org.aspectj.lang.ProceedingJoinPoint;
5. import org.aspectj.lang.annotation.After;
6. import org.aspectj.lang.annotation.AfterReturning;
7. import org.aspectj.lang.annotation.AfterThrowing;
8. import org.aspectj.lang.annotation.Around;
9. import org.aspectj.lang.annotation.Aspect;
10. import org.aspectj.lang.annotation.Before;
11. import org.springframework.stereotype.Component;
12.
13. import com.durgasoft.beans.Account;
14. import com.durgasoft.exceptions.InsufficientFundsException;
15. @Component("aspect")
16. @Aspect
17. public class TransactionAspect {
18. @Before("execution(* com.durgasoft.service.TransactionService.*(..))")
19. public void before(JoinPoint jp) {
20. Object[] args = jp.getArgs();
21. Account acc = (Account) args[0];
357
24.
25. @After("execution(* com.durgasoft.service.TransactionService.*(..))")
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
33. returning="result")
34. public void afterReturning(JoinPoint jp, String result) {
35. System.out.println("After Returning Advice: Transaction Status :"+result);
36. }
37.
38. @Around("execution(* com.durgasoft.service.TransactionService.*(..))")
39. public void around(ProceedingJoinPoint jp) {
40. System.out.println("Around Advice : Before "+jp.getSignature().getName()+" Method E
xecution");
41. String status = "";
42. try {
43. status = (String)jp.proceed();
44. } catch (Throwable e) {
45. e.printStackTrace();
46. }
47. System.out.println("Around Advice : After "+jp.getSignature().getName()+" Method Ex
ecution");
48. System.out.println("Around Advice : Transaction Status :"+status);
49. }
50.
51. //@AfterThrowing(pointcut="execution(* com.durgasoft.service.TransactionService.*(..))",
52. //throwing="exception")
53. public void afterThrowing(JoinPoint jp, InsufficientFundsException exception) {
54. System.out.println("After Throwing Advice : "+exception.getClass().getName()+" In Tra
nsaction :"+exception.getMessage());
55. }
56. }
applicationContext.xml
358
3. <beans xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
Page
1. package com.durgasoft.test;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
360
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
{SPRING ORM}
361
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
362
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In general, Object Oriented Data Model and Relational data model are having the following
mismatches.
1. Granualarity Mismatch
2. Sub types mismatch
3. Associations Mismatch
4. Identity Mismatch
To improve Data persistency in Enterprise applications we have to resolve the above specified
mismtahces between Data models, for this, we have to use "ORM" implementations.
To implement ORM in Enterprise applications we have to use the following ORM implementations.
1. EJBs-Entity Beans
2. JPA
3. Hibernate
4. IBatis
5. JDO
If we want to use Hibernate in enterprise applications then we have to use the following sateps.
1) Persistence Class or Object.
2) Prepare Mapping File.
3) Prepare Hibernate Configuration File
4) Prepare Hibernate Client Application
Example:
363
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To remove the above boilerplate code, SPRING Framework has provided ORM Module.
Spring has provided the complete ORM module in the form of "org.springframework.orm"
package.
To abstract the above boilerplate code Spring-ORM module has provided a predefined class in
the fomr of "org.springframework.orm.hibernate4.HibernateTemplate" w.r.t Hibernate4 version
1) Create Java Project with both Spring[including ORM] and Hibernate Libraries.
2) Create Bean/POJO class.
3) Prepare Hibernate Mapping File
364
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Prepare JAVA project in Eclipse IDE and add the following JAR files to Buildpath in the form of the
following Libraries.
Spring4_Lib:
spring-aop-4.0.4.RELEASE.jar
spring-beans-4.0.4.RELEASE.jar
spring-context-4.0.4.RELEASE.jar
spring-context-support-4.0.4.RELEASE.jar
spring-core-4.0.4.RELEASE.jar
spring-expression-4.0.4.RELEASE.jar
spring-jdbc-4.0.4.RELEASE.jar
commons-io-2.6.jar
commons-logging-1.2.jar
spring-tx-4.0.4.RELEASE.jar
spring-aspects-4.0.4.RELEASE.jar
spring-orm-4.0.4.RELEASE.jar
Hibernate4_Lib:
ojdbc6.jar
antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.11.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
hibernate-entitymanager-4.3.11.Final.jar
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Student.hbm.xml
EX:
The main intention of DAO implementation class is to implement all DAO methods. In DAO
implementation class every DAO method must be declared with @Transactional annotation
inorder to activate Spring Transaction Service.
Note: If we use @Transactional annotation then it is not required to create Transaction object
explicitly and iit is not required to perform commit and rollback operations explicitly.
In DAO implementation class we must declare HibernateTemplate property and its respective
setXXX() method inorder to inject HibernateTemplate object.
Example:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
45. @Transactional
46. public Employee getStudent(int sid) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
34. <tx:annotation-driven/>
35. <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTra
Page
nsactionManager">
36. <property name="sessionFactory" ref="sessionFactory"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The main intention of Client Application is to get Dao object and to access Dao object.
Example:
22. System.out.println(status);
23. or
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.pojo;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
8.
9. public int getEno() {
10. return eno;
11. }
12. public void setEno(int eno) {
13. this.eno = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. this.ename = ename;
20. }
21. public float getEsal() {
22. return esal;
23. }
24. public void setEsal(float esal) {
25. this.esal = esal;
26. }
27. public String getEaddr() {
28. return eaddr;
29. }
30. public void setEaddr(String eaddr) {
31. this.eaddr = eaddr;
32. }
371
33.
34. public String toString() {
35. return "["+eno+","+ename+","+esal+","+eaddr+"]";
Page
36. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeDao.java
1. package com.durgasoft.dao;
2.
3. import com.durgasoft.pojo.Employee;
4.
5. public interface EmployeeDao {
6. public String insert(Employee e);
7. public String update(Employee e);
8. public String delete(Employee e);
9. public Employee getEmployee(int eno);
10. }
EmployeeDaoImpl.java
1. package com.durgasoft.dao;
2. import org.hibernate.FlushMode;
3. import org.hibernate.Transaction;
4. import org.springframework.orm.hibernate4.HibernateTemplate;
5. import org.springframework.transaction.annotation.Transactional;
6.
7. import com.durgasoft.pojo.Employee;
8.
9. public class EmployeeDaoImpl implements EmployeeDao {
10. String status = "";
11. private HibernateTemplate hibernateTemplate;
12. public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
13. this.hibernateTemplate = hibernateTemplate;
14.
15. }
16.
17. @Override
18. @Transactional
19. public String insert(Employee e) {
20. try {
21. hibernateTemplate.save(e);
372
24. ex.printStackTrace();
25. status = "Insertion Failure";
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
65. }
66. return emp;
Page
67. }
68. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
actoryBean">
22. <property name="dataSource" ref="dataSource"/>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5. import org.springframework.orm.hibernate4.HibernateTemplate;
6.
7. import com.durgasoft.dao.EmployeeDao;
8. import com.durgasoft.pojo.Employee;
9.
10. public class Test {
375
11.
12. public static void main(String[] args)throws Exception {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
376
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Introduction:
JPA is a an API , it can be used to perform database operations in enterprise applications
with ORM implementation tools.
JPA was provided by J2EE along with EJB3.0 version as a persistence mechanism.
If we want to prepare JPA applications with "Hibernate" JPA provider then we have to use the
following steps.
1. Create Java project in Eclipse with JPA library which includes all Hibernate JARs.
2. Create Entity class under src folder.
3. Create mapping File or Use JPA annotations in POJO class.
4. Create JPA configuration File[persistence.xml]
5. Create Test Application.
1. Create Java project in Eclipse with JPA library which includes all Hibernate JARs.
This step is same as Java project creation and it will include JPA provider Library that is Hibernate
jars.
Student.java
1. package com.durgasoft.entity;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
It is same as Hibernate mapping file, it will provide mapping between Object Oriented Data model
elements like class, Id property, normal properties with the relational data model elements like
Table name, Primary Key Columns, normal columns,....
EX:
Student.xml
1. <hibernate-mapping>
2. <class name="com.durgasoft.entity.Student" table="student">
3. <id name="sid" column="SID"/>
4. <property name="sname" column="SNAME"/>
5. <property name="saddr" column="SADDR"/>
6. </class>
7. </hibernate-mapping>
JPA configuration File is same as Hibernate COnfiguration File, it include all JPA configuration
details which are required to interact with database .
IN general, we will provide the following configuration details in JPA configuration file.
1. Jdbc Parameters like Driver class name, Driver URL, Database user name, Database
password.
2. Dialect configurations
3. Mapping File or Annotated classes configuration
4. Cache Mechanisms configurations
5. Transactions configurations
Ex persistence.xml:
Page
1. <persistence>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: EntityTranmsaction is required for only non select operations only, not for select operations.
To perform Persistence operations we have to use the following methods from EntityManager
object.
Note: To perform Updations , first we have to get Entity object from Database table by using find()
method then we have to use set New data to Entity Object then perform commit operation.
380
EX:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
Test.java
1. package com.durgasoft.pojo;
2. public class Employee {
3. private int eno;
4. private String ename;
5. private float esal;
6. private String eaddr;
381
9. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.xml
src/META-INF/persistence.xml
382
2. <persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import javax.persistence.EntityManager;
4. import javax.persistence.EntityManagerFactory;
5. import javax.persistence.EntityTransaction;
6. import javax.persistence.Persistence;
7.
8. import com.durgasoft.pojo.Employee;
9.
10. public class Test {
11.
12. public static void main(String[] args)throws Exception {
13. EntityManagerFactory factory = Persistence.createEntityManagerFactory("emp");
14. EntityManager entManager = factory.createEntityManager();
15. Employee emp = new Employee();
16. emp.setEno(111);
17. emp.setEname("AAA");
383
18. emp.setEsal(5000);
19. emp.setEaddr("Hyd");
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <persistence>
2. <persistence-unit name="std">
3. <class>com.durgasoft.entity.Student</class>
4. ------
5. </persistence-unit>
6. </persistence>
Example:
Employee.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="emp2")
10. public class Employee {
384
11. @Id
12. @Column(name="ENO")
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
src/META-INF/persistence.xml
ersistence/persistence_2_0.xsd"
4. version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
Page
5. <persistence-unit name="emp">
6. <class>com.durgasoft.pojo.Employee</class>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import javax.persistence.EntityManager;
4. import javax.persistence.EntityManagerFactory;
5. import javax.persistence.EntityTransaction;
6. import javax.persistence.Persistence;
7.
8. import com.durgasoft.pojo.Employee;
9.
10. public class Test {
11.
12. public static void main(String[] args)throws Exception {
13. EntityManagerFactory factory = Persistence.createEntityManagerFactory("emp");
14. EntityManager entManager = factory.createEntityManager();
15. Employee emp = new Employee();
16. emp.setEno(111);
17. emp.setEname("AAA");
18. emp.setEsal(5000);
19. emp.setEaddr("Hyd");
20. EntityTransaction tx = entManager.getTransaction();
21. tx.begin();
22. entManager.persist(emp);
386
23. tx.commit();
24. System.out.println("Employee Inserted Succssfully");
Page
25. }
26. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to use JPA with EclipseLink implementation then we have to use the following steps.
1. Create JPA project.
2. Create Entity Class with Annotations
3. Create JPA configuration File
4. Create Test Application
With these steps JPA project will be created in projects Explorer part..
Create package "com.durgasoft.entity" under src folder and create Entity class.
Employee.java
1. package com.durgasoft.entity;
2. import java.io.Serializable;
3. import java.lang.String;
4. import javax.persistence.*;
387
5. @Entity
6. @Table(name="emp1")
7. public class Employee implements Serializable {
Page
8.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
48.
49. public void setEaddr(String eaddr) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Open persistence.xml file which is existed under"src\META-INF" folder and provide the following
details.
persistence.xml
1. package com.durgasoft.test;
2.
3. import javax.persistence.EntityManager;
4. import javax.persistence.EntityManagerFactory;
5. import javax.persistence.EntityTransaction;
6. import javax.persistence.Persistence;
7.
8. import com.durgasoft.entity.Employee;
389
9.
10. public class Test {
Page
11.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
53. }
54. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Create Java Project with both Spring Library and Hibernate Library.
2. Create Dao interface
3. Create Dao implementation classs.
4. Create POJO / Entity class.
5. Create Hibernate Mapping File.
6. Create Spring Configuration File.
7. Create Test Application.
1. Create Java Project with both Spring Library and Hibernate Library.
Spring Library:
commons-logging-1.2.jar
spring-aop-4.3.9.RELEASE.jar
spring-beans-4.3.9.RELEASE.jar
spring-context-4.3.9.RELEASE.jar
spring-context-support-4.3.9.RELEASE.jar
spring-core-4.3.9.RELEASE.jar
spring-expression-4.3.9.RELEASE.jar
spring-jdbc-4.3.9.RELEASE.jar
spring-orm-4.3.9.RELEASE.jar
spring-tx-4.3.9.RELEASE.jar
Hibernate Library:
hibernate3.jar
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
slf4j-api-1.6.1.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
ojdbc6.jar
EmployeeDao.java
Page
1. package com.durgasoft.dao;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.dao;
2.
3. import javax.persistence.EntityManager;
4. import javax.persistence.PersistenceContext;
5.
6. import org.springframework.stereotype.Repository;
7. import org.springframework.transaction.annotation.Transactional;
8.
9. import com.durgasoft.entity.Employee;
10.
11. @Repository
12. public class EmployeeDaoImpl implements EmployeeDao {
13.
14. String status = "";
15.
16. @PersistenceContext
17. private EntityManager entityManager;
18.
19. @Transactional
20. @Override
21. public String insertEmployee(Employee emp) {
22. entityManager.persist(emp);
23. status = "SUCCESS";
24. return status;
25. }
26.
27. @Override
392
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.entity;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
393
8.
9. public int getEno() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
41. </property>
42. </bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.test;
Page
2.
3. import org.springframework.context.ApplicationContext;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
44. }
45. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.pojo;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
8.
9. public int getEno() {
10. return eno;
11. }
12. public void setEno(int eno) {
13. this.eno = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. this.ename = ename;
20. }
21. public float getEsal() {
22. return esal;
23. }
24. public void setEsal(float esal) {
25. this.esal = esal;
26. }
27. public String getEaddr() {
28. return eaddr;
29. }
30. public void setEaddr(String eaddr) {
31. this.eaddr = eaddr;
32. }
33.
34. public String toString() {
35. return "["+eno+","+ename+","+esal+","+eaddr+"]";
398
36. }
37.
Page
38. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.dao;
2.
3. import com.durgasoft.entity.Employee;
4.
5. public interface EmployeeDao {
6. public String insertEmployee(Employee emp);
7. public Employee findEmployee(int eno);
8. public String updateEmployee(Employee emp);
9. public String removeEmployee(int eno);
10. }
EmployeeDaoImpl.java
1. package com.durgasoft.dao;
2.
3. import javax.persistence.EntityManager;
4. import javax.persistence.PersistenceContext;
5.
6. import org.springframework.stereotype.Repository;
7. import org.springframework.transaction.annotation.Transactional;
8.
9. import com.durgasoft.entity.Employee;
10.
11. @Repository
12. public class EmployeeDaoImpl implements EmployeeDao {
13.
14. String status = "";
15.
16. @PersistenceContext
17. private EntityManager entityManager;
18.
19. @Transactional
20. @Override
21. public String insertEmployee(Employee emp) {
22. entityManager.persist(emp);
23. status = "SUCCESS";
24. return status;
399
25. }
26.
Page
27. @Override
28. public Employee findEmployee(int eno) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
11. </class>
12. </hibernate-mapping>
Page
applicationContext.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
40. </props>
41. </property>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5. import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
6.
7. import com.durgasoft.dao.EmployeeDao;
8. import com.durgasoft.entity.Employee;
9.
10. public class Test {
11.
12. public static void main(String[] args) {
13. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
xt.xml");
14. EmployeeDao empDao = (EmployeeDao) context.getBean("empDao");
15. /*
16. Employee emp = new Employee();
17. emp.setEno(111);
18. emp.setEname("AAA");
19. emp.setEsal(5000);
20. emp.setEaddr("Hyd");
21. String status = empDao.insertEmployee(emp);
22. System.out.println(status);
23. */
24. /*
25. Employee emp = empDao.findEmployee(111);
26. System.out.println("Employee Details");
27. System.out.println("----------------------");
28. System.out.println("Employee Number :"+emp.getEno());
402
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
403
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
{SPRING
TraNSACTIONS}
404
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
405
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Transaction Management:
Transaction is an unit of work performed by Front End applications on Back End System.
1. Atomicity: This property will make the Transaction either in SUCCESS state or in FAILURE
state.
In Database related applications, if we perform all operations then the Transaction is available in
SUCCESS State, if we perform none of the operations then the Transaction is available in
FAILURE state.
2.Consistency:In database applications, Before the Transaction and After the Transaction
Database state must be in stable.
3. Isolation: If we run more than one Transaction on a single Data item then that Transactions are
called as "Concurret Transactions". In Transactions Concurrency , one transaction execution must
not give effect to another Transaction, this rule is called as "Isolation" property.
4. Durability: After committing the Transaction, if any failures are coming like Power failure, OS
failure,... after getting the System if we open the transaction then the modifications which we
performed during the transaction must be preserved.
406
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Transaction tx = null;
1. try{
2. -----
3. tx = session.beginTransaction();
4. ----
5. -----
6. tx.commit();
7. }catch(Exception e){
8. tx.rollback();
9. }
If we execute more than one transaction on a single data item then that transactions are called as
Concurrent Transactions.
In Transactions concurrency we are able to get the following data consistency problems while
executing more than one transaction at a time.
407
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Transactions concurrency, if one transaction perform updations over the data with out commit
operation , mean while, other transactions perform updations with commit operation then the first
transaction updations are lost, this data consistency problem is called as Lost Update problem.
408
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
409
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
1. <hibernate-configuration>
2. <session-factory>
3. ----
4. <property name="hibernate.connection.isolation>
5. SERIALIZABLE
6. </property>
7. -----
8. </session-factory>
9. </hibernate-configuration>
Local transactions are specific to a single transactional resource like a JDBC connection
be implemented
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Global transaction management is required in a distributed computing environment where all the
resources are distributed across multiple systems
A distributed or a global transaction is executed across multiple systems, and its execution
requires coordination between the global transaction management system and all the local data
managers of all the involved systems.
EX: txTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Spring Framewrk has provided very good suport for Propagation Behaviour in the form of the
following constants from "org.springframework.transaction .TransactionDefinition".
1. PROPAGATION_REQUIRED
2. PROPAGATION_REQUIRES_NEW
3. PROPAGATION_SUPPORTS
4. PROPAGATION_NOT_SUPPORTED
5. PROPAGATION_MANDATORY
6. PROPAGATION_NEVER
7. PROPAGATION_NESTED
1. PROPAGATION_REQUIRED:
If a method1 is running in a transaction and invokes method2 then method2 will be executed in
the same transaction. If method1 is not associated with any Transaction then Container will create
new Transaction to execute Method2.
2. PROPAGATION_REQUIRES_NEW:
If a method1 is running in a transaction and invokes method2 then container will suspend the
current Transaction temporarily and creates new Transaction for method2. After executing
method2 transaction then method1 transaction will continue.If Method1 is not associated with any
transaction then container will start a new transaction before starts new method.
3. PROPAGATION_MANDATORY:
If a method1 is running in a transaction and invokes method2 then method2 will be executed in
the same transaction. If method1 is not associated with any Transaction then Container will raise
an exception like "TransactionThrowsException".
4. PROPAGATION_SUPPORTS:
If a method1 is running in a transaction and invokes method2 then method2 will be executed in
the same transaction. If method1 is not associated with any Transaction then Container does not
start new Transaction before running method2.
5 .PROPAGATION_NOT_SUPPORTED:
If a method1 is running in a transaction and invokes method2 then Container Suspends the
Mehod1 transaction before invoking Method2. When Method2 has completed , container resumes
412
Method1 transaction. If Mehod1 is not associated with Tramsaction then Container does not start
new Tansaction before executing Method2.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If a method1 is running in a transaction and invokes method2 then Container throws an Exception
like RemoteException. I mthod1 is not associated with any transaction then Container will not start
new Transaction for Method2.
7. PROPAGATION_NESTED:
Indicates that the method should be run with in a nested transaction if an existed transaction is in
progress.
To set the above Propagation Behaviout to TransactionTemplate then we have to use the
following method.
413
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Programmetic Approach:
In Programatic Approach of transactions we have to declare the transaction and we have to
perform transactions commit or rollback operations explicitly by using JAVA code.
In Programetic approach if we want to provide transactions then we have to use the following
predefined Library.
1.Transaction Manager:
Spring Framework has provided Transaction manager in the form of a predefined interfaces
1. org.springframework.jdbc.datasource.DataSourceTransactionManager
2. org.springframework.transaction.PlatformTransactionManager
3. org.springframework.orm.hibernate4.HibernateTransactionManager
4. org.springframework.transaction.jta.JtaTransactionManager
------
------
In Spring Transaction based applicatins , We must configure either of the above
TransactionManager in configuration file and we must inject TransactionManager in DAO
implementation class.
2. TransactionDefinition:
1. ISOLATION_READ_UNCOMMITTED
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. TransactionStatus:
TransactionDao.java
1. package com.durgasoft.dao;
2. public interface TransactionDao {
3. public String transferFunds(String fromAccount, String toAccount, int transfer_Amt);
4. }
TransactionDaoImpl.java
415
1. package com.durgasoft.dao;
2. import org.springframework.jdbc.core.JdbcTemplate;
3. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
Page
4. import org.springframework.transaction.TransactionDefinition;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
42.
43. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
Test.java
Page
1. package com.durgasoft.test;
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Declarative Approach:
In Declarative approach, we will seperate Transaction Service code and Business Logic in Spring
applications , so that, we are able to get loosly coupled design in Spring applications.
To manage Transactions in declarative approach, Spring Transaction module has provided the
following AOP implemented tags.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Syntax:
2. <tx:attributes>
It will take Transactional methods inorder to apply Isolation levels and Propagation
behaviours,...... by using <tx:method> tag.
Syntax:
<tx:attributes>
-----
<tx:attributes>
3. <tx:method>
It will define Transactional method and its propagation Behaviours, Isolation levels, Timeout
statuses,....
Syntax:
With the above tags, we must define Transaction Advice and it must be configured with a
particular Pointcut expression by using <aop:advisor> tag.
EX:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
TransactionDao.java
1. package com.durgasoft.dao;
2. public interface TransactionDao {
3. public String transferFunds(String fromAccount, String toAccount, int transfer_Amt);
4. }
TransactionDaoImpl.java
1. package com.durgasoft.dao;
2. import org.springframework.jdbc.core.JdbcTemplate;
3. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
4. import org.springframework.transaction.TransactionDefinition;
5. import org.springframework.transaction.TransactionStatus;
6. import org.springframework.transaction.support.DefaultTransactionDefinition;
7.
8.
420
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ApplicationContext.xml
20. </bean>
21. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2. import org.springframework.context.ApplicationContext;
3. import org.springframework.context.support.ClassPathXmlApplicationContext;
4.
5. import com.durgasoft.dao.TransactionDao;
6.
7. public class Test {
8.
9. public static void main(String[] args) {
10. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
xt.xml");
11. TransactionDao tx_Dao = (TransactionDao)context.getBean("transactionDao");
12. String status = tx_Dao.transferFunds("abc123", "xyz123", 100);
13. System.out.println(status);
422
14. }
15. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
This approach is very simple to use for transactions in Spriong applications. In this approach, we
will use @Transactional annotation just before the transactional methods in DAO implementation
classes, but, to use this annotation we must activate @Transactional annotation in Spring
configuration file vy using the following tag.
<tx:annotation-driven transaction-manager="transactionManager"/>
TransactionDao.java
1. package com.durgasoft.dao;
2. public interface TransactionDao {
3. public String transferFunds(String fromAccount, String toAccount, int transfer_Amt);
4. }
TransactionDaoImpl.java
1. package com.durgasoft.dao;
2. import org.springframework.jdbc.core.JdbcTemplate;
3. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
4. import org.springframework.transaction.TransactionDefinition;
5. import org.springframework.transaction.TransactionStatus;
6. import org.springframework.transaction.annotation.Transactional;
7. import org.springframework.transaction.support.DefaultTransactionDefinition;
8.
9.
10. public class TransactionDaoImpl implements TransactionDao {
11.
12. private JdbcTemplate jdbcTemplate;
13. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
14. this.jdbcTemplate = jdbcTemplate;
15. }
16.
17. @Transactional
18. @Override
423
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ApplicationContext.xml
23. </bean>
24. <bean id="transactionDao" class="com.durgasoft.dao.TransactionDaoImpl">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5.
6. import com.durgasoft.dao.TransactionDao;
7.
8. public class Test {
9.
10. public static void main(String[] args) {
11. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
xt.xml");
12. TransactionDao tx_Dao = (TransactionDao)context.getBean("transactionDao");
13. String status = tx_Dao.transferFunds("abc123", "xyz123", 100);
14. System.out.println(status);
15. }
16. }
425
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
{SPRING WEB
MODULE}
426
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
427
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Q)To prepare web applications we have already Struts1 Framework then what is the
requirement to use Spring Web MVC Module?
Ans:
1. Struts is Web Framework, it able to provide very good environment to prepare and execute
web applications.
2. Struts framework is mainly MVC based frame work, it able to use only MVC and its
corelated design pattern.
In Spring framework, only Web Module is able to use MVC Design Pattern.
4. Struts framework is able to provide tightly coupled design for its applications.
5. Struts is not providing clear seperatin between Controller layer, Beans Model and View
part.
Spring Framework is able to provide clear seperation between controller layer, Model and
View part.
6. Struts is more API dependent, it is very difficult to perform debugging and Testing.
Spring is less API dependent, it is very simple perform debugging and testing.
428
7. Struts is not providing very good environment to integrate other technology applications like
JDBC, Hibernate, EJBs,....
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
8. Struts is able to use only HTML, JSP ,... basic view related tech to prepare View part.
Spring is able to provide very good environment to use view related tech like HTML,
JSP, velocity, Freemarker,.....
11. Struts is said to be invasive. In Struts we used to extend Action Classes and ActionForm
classes.It forces the programmer that, the programmer class must extend from the base
class provided by Struts API.
12. Struts framework is able to provide very good Tag library to prepare view part.
Spring framework is not providing good tag library to prepare view part.
13. Spring is providing very good Transaction management and Messaging support for its
applications.
Struts is not providing support for Transaction Management and Messaging Support.
Q)To prepare MVC Based Web Applications we have already JSF[Java Server Faces] then
what is the requirement to use Spring Web MVC Framework?
Ans:
1. JSF is web framework, it able to provide environment to prepare web applications only.
429
environment to prepare any type of application like Standalone applications, web applications,
Distributed applications,.....
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Spring Framework is not Component based Framework, it will use Beans to manage
Form data.
Spring is not View Layered Framework, it will focus on all layers of tghe Enterprise
Applications.
6. JSF is not having Middleware Services support like Transactions, Messaging, ....
7. JSF is not having any integration environment to integrate other technologies applications
like JDBC, EJBs, RMI,....
across contexts, such as from web controllers to business objects and validators.
3. Spring Framework is allowing Command and Form objects to reuse Business code instead
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. View
2. web.xml
3. DispatcherServlet
4. HandlerMapping
5. Controller Component
6. Command Class
7. View Resolver
8. Spring Configuration File
3. HandlerMapping will return the name and location of the Controller class.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1.View :
Ans:
Spring Framework is able to allow all the advanced view tech ,but, at basic level, We will use JSP
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml is deployment descriptor, it will provide metadata about the web application which is
required by the container inorder to identify the server side components and inorder to execute
server side components.
In Spring web MVC applicatins , web.xml file requirement is to configure Font Controller that is
DispatcherServlet inorder to activate FrontController by Web containers.
EX: <servlet-name>dispatcherServlet</servlet-name>
Where DispatcherServlet class must be configured with its fully qualified name inorder to activate
FrontController.
Page
EX: <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: The default name and location of Spring configuration file is under WEB-INF folder with the
name "Servlet_Logical_Name-servlet.xml", but, if we want to change this name and location then
we must use "contextConfigLocation" initialization parameter in DispatcherServlet configuration.
EX:
1. <init-param>
2. <param-name>contextConfigLocation</param-name>
3. <param-value>/WEB-INF/configd/myconfig.xml</param-value>
4. </init-param>
EX: <load-on-startup>1</load-on-startup>
Where URL pattern definition is required for each and every Servlet in web applications.
IN general, in web applications, we will define URL patterns for the Servlets in the following three
approaches.
1. Exact Match Method
2. Directory Match Method
3. Extension Match Method
From the above Url pattern definitions, DispatcherServlet required to use either Directory Match
method[/*] or Extension Match Method[*.do] inorder to trap all the requests from Clients to
DispatcherServlet.
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>dispatcherServlet</servlet-name>
4. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
5. <load-on-startup>1</load-on-startup>
6. </servlet>
434
7. <servlet-mapping>
8. <servlet-name>dispatcherServlet</servlet-name>
Page
9. <url-pattern>*.do</url-pattern> or
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. DispatcherServlet:
The main intention of the Front Controller in web applications is ,
1. Getting request from clients
2. Identifying the respective Model component or Business component which includes
business logic.
3. Executing Business Logic which is existed in Business component.
4. Identifying the respective View part inorder to generate response.
5. Forwarding request to view part inorder to generate dynamic response.
In Spring web mvc module , DispatcherServlet is acting as the Front Controller provided by Spring
Framework in the form of "org.springframework.web.servlet.DispatcherServlet".
Spring Framework has provided DispatcherServlet with the following Structer.
Where HttpServletBean is the first Spring-aware class in the hierarchy. It injects the bean‘s
properties using the servlet init-param values received from the web.xml or
435
from WebApplicationInitializer.
Where FrameworkServlet integrates the Servlet functionality with a web application context,
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where DispatcherServlet will perform the following actions in Spring web MVC applications
inorde to process the requests.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
5. When request is coming to the container then Web Container will take URL pattern value from
request format and container is trying to compare the URL pattern of the DispatcherServlet which
we configured in web.xml file, where if the url pattern is matched with DispatcherServlet URL
pattern then container will forward request to DispatcherServlet.
6. When request is coming to the DispatcherServlet then DispatcherServlet will perform the
following actions
Note: Interceptors are like Filters in servlets, which are used to perform pre-processing and
437
object to access Handler by using handle() method, where HandlerAdapter will execute all
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
After executing all the interceptors, HandlerAdpter will access business logic which is
included in Handler or Controller component.
By the execution of Business login in Handler class, Handler will return ModelAndView
object to HandlerAdapter by executing all the interceptors in reverse inorder to provide
post-processing activities by executing postHandle() method, where HandlerAdapter will
send the received ModelAndView object to DispatcherServlet.
Note: Where ModelAndView object contains View objct and Model object, where View
object contains view name inorder to identify view part and Model object contains no of
Objects to provide data to the View part.
When View is identified in web application then DispatcherServlet will execute the
corresponsing view page by getting data from Model part a and DispatcherServlet will
prepare Response for the client.
a) Protocol will prepare response format contains Header part and Body part, where
Header part is able to manage response headers data like response size, type of
response,….. and Body part is able to manage the actual dynamic response.
b) Protocol will carry response format to client, where client browser will display the
generated response.
c) When response is generated at client browser , protocol will destroy the
connection which is established between client and Server.
d) When we shutdown the server or when we undeploy the web application then
container will perform DispatcherServlet deinstantiation, with this, all the Spring
Framework objects like HandlerMapping, HandlerAdapter, viewResolver,….. are
destroyed.
4. HandlerMapping:
The main intention of HandlerMapping is to map incoming request to the Handler class that can
handle requests.
438
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
i. BeanNameUrlHandlerMapping
ii. SimpleUrlHandlerMapping
iii. ControllerClassNameHandlerMapping
iv. CommonsPathMapHandlerMapping
Note: IN Spring web MVC applications, if we want to use the HandlerMapping classes then we
must configure them in Spring configuration File.
i. BeanNameUrlHandlerMapping
It is default HandlerMapping in Spring applications, it will be used by Spring framework when no
HandlerMapping is configured in Spring configuration file.
This HandlerMapping map URLs to beans with names that start with a slash ("/"), similar to how
Struts maps URLs to action names.
Spring Framework has provided this Handler mapping like
“org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping”.
EX:
1. <beans>
2. -----
3. <bean name=‖/welcome.htm‖ class=‖com.durgasoft.controller.WelcomeController‖/>
4. <bean name=‖/hello.htm‖ class=‖com.durgasoft.controller.HelloController‖/>
5. <bean name=‖handlerMapping‖ class=‖org.springframework.web.servlet.handler.Bean
NameUrlHandlerMapping‖/>
6. ------
7. </beans>
ii. SimpleUrlHandlerMapping
439
This HandlerMapping is able to map Handler or Controller classes by matching URL path with the
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
1. <beans>
2. ------
3. <bean name=‖addEmp‖ class=‖com.durgasoft.controller.AddEmployeeController‖/>
4. <bean name=‖searchEmp‖ class=‖com.durgasoft.controller.SearchEmployeeController‖/
>
5. <bean name=‖deleteEmp‖ class=‖com.durgasoft.controller.DeleteEmployeeController‖/>
iii. ControllerClassNameHandlerMapping
This HandlerMapping follows a simple convention for generating URL path mappings from the
class names of registered Controller beans as well as @Controller annotated beans.
For simple Controller implementations (those that handle a single request type), the convention is
to take the short name of the Class, remove the 'Controller' suffix if it exists and return the
440
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <beans>
2. ------
3. <bean id=‖welcome‖ class=‖com.durgasoft.controller.WelcomeController‖/>
4. <bean name=‖hello‖ class=‖com.durgasoft.controller.HelloController‖/>
5. <bean name=‖handlerMapping‖ class=―org.springframework.web.servlet.mvc.support.C
ontrollerClassNameHandlerMapping‖/>
6.
7.
8. </beans>
iv. CommonsPathMapHandlerMapping
The org.springframework.web.servlet.handler.CommonsPathMapHandlerMapping is one of the
implementation of HandlerMapping interface.
To use this HandlerMapping the controller class must have a class level metadata of the form
@org.springframework.web.servlet.handler.commonsattribures.PathMap("/mypath.spring").
We can configure multiple path maps for a single controller.
EX:
1. @org.springframework.web.servlet.handler.commonsattribures.PathMap(
2. "/mypath.spring")
3.
4. public class FirstController implements Controller {
5.
441
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
5. Controller Component:
The main intention of Controller in Spring web MVC is to manage application logic or to have
controller logic to manage Service layer provided business methods access.
To prepare Controller classes in Spring web MVC applications Spring framework has provided the
following predefined Library.
Ex:
3. ------------
4. return new ModelAndView(―success‖);
5. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
6. Command Class:
The main intention of Command class is to store form data which is submitted by the client when
we use FormCommandControllers. It is like ActionForm component in Struts framework.
EX:
7. View Resolver:
In Spring MVC, view resolvers enable you to render models in a browser without tying you to a
specific view technology like JSP, Velocity, XML…etc.
There are two interfaces that are important to the way Spring handles views
are ViewResolverand View. The ViewResolver provides a mapping between view names and
actual views. The View interface addresses the preparation of the request and hands the request
over to one of the view technologies.
the request file name or Accept header. This class delegates view resolution to other view
resolvers that are configured. The class uses the MediaType from the request to determine
Page
a view. The class first determines the MediaType, then asks each ViewResolver to return a
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
IN spring Web MVC applications we have to configure view Resolver in Spring configuration file
with the name ―viewResolver‖ id name.
EX:
The main intention of Spring configuration file in Spring Web MVC application is to provide the
configuration details like,
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <beans>
2. -----
3. <bean name=‖/welcome.htm‖ class=‖com.durgasoft.controller.WelcomeController‖/>
4. <bean name=‖/hello.htm‖ class=‖com.durgasoft.controller.HelloController‖/>
5. <bean name=‖handlerMapping‖ class=‖org.springframework.web.servlet.handler.Bean
NameUrlHandlerMapping‖/>
6. <bean id=‖viewResolver‖ class=‖org.springframework.web.servlet.view.InternalResourceVi
ewResolver‖>
7. <property name=‖prefix‖ value=‖WEB-INF‖/>
8. <property name=‖suffix‖ value=‖.jsp‖/>
9. </bean>
10. -------
11. </beans>
445
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
app1
|---index.jsp
|---src
| |-----com.durgasoft.controllers.WishController.java
|---WEB-INF
|-----web.xml
|-----ds-servlet.xml
|-----wish.jsp
|-----classes
|----com.durgasoft.controllers.WishController.class
446
wish.jsp
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
WishController.java
1. package com.durgasoft.controllers;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5. import org.springframework.web.servlet.ModelAndView;
6. import org.springframework.web.servlet.mvc.Controller;
7.
8. public class WishController implements Controller {
9.
10. @Override
11. public ModelAndView handleRequest(HttpServletRequest request, HttpServletRespons
e response) throws Exception {
12. ModelAndView mav = new ModelAndView("wish","message", "Welcome to Spring WE
B MVC World");
13. return mav;
14. }
15.
16. }
ds-servlet.xml
2. <beans xmlns="http://www.springframework.org/schema/beans"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
Page
4. xmlns:p="http://www.springframework.org/schema/p"
5. xmlns:context="http://www.springframework.org/schema/context"
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
19. <url-pattern>*.ds</url-pattern>
20. </servlet-mapping>
Page
21. </web-app>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hello.jsp
welcome.jsp
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HelloController.java
1. package com.durgasoft.controllers;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.web.servlet.ModelAndView;
7. import org.springframework.web.servlet.mvc.Controller;
8.
9. public class HelloController implements Controller {
10.
11. @Override
12. public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse ar
g1) throws Exception {
13. ModelAndView mav = new ModelAndView("hello");
14. return mav;
15. }
16.
17. }
WelcomeController.java
1. package com.durgasoft.controllers;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
450
5.
6. import org.springframework.web.servlet.ModelAndView;
Page
7. import org.springframework.web.servlet.mvc.Controller;
8.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
web.xml
451
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Application-3
index.jsp
4. <html>
5. <head>
Page
6. <meta charset="ISO-8859-1">
7. <title>Insert title here</title>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
helloform.html
wish.jsp
5. <html>
6. <head>
Page
7. <meta charset="ISO-8859-1">
8. <title>Insert title here</title>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HelloPageController.java
1. package com.durgasoft.controllers;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.web.servlet.ModelAndView;
7.
8. import org.springframework.web.servlet.mvc.Controller;
9.
10.
11. public class HelloPageController implements Controller {
12.
13. @Override
14. public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse ar
g1) throws Exception {
15.
16. ModelAndView mav = new ModelAndView("helloform");
17. return mav;
18. }
19.
20. }
WishController.java
1. package com.durgasoft.controllers;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
454
6. import org.springframework.web.servlet.ModelAndView;
7. import org.springframework.web.servlet.mvc.Controller;
Page
8.
9. public class WishController implements Controller {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
26. <load-on-startup>1</load-on-startup>
27. </servlet>
28. <servlet-mapping>
Page
29. <servlet-name>ds</servlet-name>
30. <url-pattern>/</url-pattern>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
Application-4:
index.jsp
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Success.jsp
9. <body>
10. <h2>Durga Software Solutions</h2>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
failure.jsp
LoginPageController.java
1. package com.durgasoft.controllers;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.web.servlet.ModelAndView;
7. import org.springframework.web.servlet.mvc.Controller;
8.
9. public class LoginPageController implements Controller {
10.
11. @Override
12. public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse ar
g1) throws Exception {
458
13.
14.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.controllers;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.web.servlet.ModelAndView;
7. import org.springframework.web.servlet.mvc.Controller;
8.
9. public class LoginController implements Controller {
10.
11. @Override
12. public ModelAndView handleRequest(HttpServletRequest request, HttpServletRespons
e response) throws Exception {
13. String uname = request.getParameter("uname");
14. String upwd = request.getParameter("upwd");
15. ModelAndView mav = null;
16. if(uname.equals("durga") && upwd.equals("durga")) {
17. mav = new ModelAndView("success");
18. }else {
19. mav = new ModelAndView("failure");
20. }
21. return mav;
22. }
23. }
ds-servlet.xml
11.
12. <bean name="/loginpage" class="com.durgasoft.controllers.LoginPageController"/>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Spring Framework has provided annotations support right from its Spring 2.5 version. By using
Anotations in SPring Web MVC applications we are able to reduce the following configurations in
spring configuation file.
Spring Web MVC Frame work has provided the following Annotations mainly.
1. @Controller
2. @RequestMapping
3. @RequestParam
4. @SessionAttributes
1. @Controller:
Before Spring 2.5, all controller classes must be configured in spring configuration file, But, from
Spring2.5 version, We are able to declare all controller classes with @Controller annotation to tell
the Spring container that this class is a controller.in this context, to give an intemation to the
Spring Container about the Controller classes and their locations we have to add the following tag
in spring configuration file.
The above declaration(context:component-scan) tells the Spring container to auto scan the entire
package to identify the controller components.
EX:
@Controller
public class LoginController {
-----
}
2. @RequestMapping
461
@RequestMapping annotation is used for defining the request urls based on the context root and
HTTP request methods like GET , POST, HEAD,... for the request.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@RequestMapping(value="/---" , method=---)
Where value member will take Request URL with / prefix.
Where method member will take the constants like GET, POST, HEAD,... from RequestMethod
enum.
EX:
@Controller
public class LoginController {
@RequestMapping(value="/login", method=RequestMethod.POST)
public ModelAndView checkLogin(HttpServletRequest request, HttpServletResponse
response){
------
return new ModelAndView("success");
}
}
Note: It is not mandatory to return ModelAndView object from controller method, where we can
return String also but the parameter to Controller Method must be ModelMap, it will take model
attributes which we want to submit to View JSP page.
EX:
@Controller
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
3.@RequestParam:
@RequestParam annotation will be used in the methods to bind the method parameters to the
request parameters. If the request is submitted by the browser, request parameters are passed
462
through the URL query parameters. That can be easily mapped to the methods by annotating the
method parameters with @RequestParam.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@RequestParam("paramName")
EX:
@Controller
public class LoginController {
@RequestMapping(value="/login", method=RequestMethod.POST)
public ModelAndView checkLogin(@RequestParameter("uname") String uname,
@RequestParameer("upwd") String upwd){
------
return new ModelAndView("success");
}
}
4.@SessionAttributes:
@SessionAttributes is used to define a variable name inorder to keep its Key-Value pair in
Session Scope and inorder to use that in multiple pages in the same web application.
Syntax:
@SessionAttributes("Param_Name")
EX:
@Controller
@SessionAttributes("status")
public class LoginController {
@RequestMapping(value="/login", method=RequestMethod.POST)
public ModelAndView checkLogin(@RequestParameter("uname") String uname,
@RequestParameer("upwd") String upwd, ModelMap map){
------
map.addAttribute("status", "Login SUCCESS");
return new ModelAndView("success");
}
}
status.jsp
463
1. <h1>
Page
2. <%
3. String status = session.getAttribute("status");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example-5:
index.jsp
loginform.jsp
17. </tr>
18. <tr>
Page
19. <td>Password</td>
20. <td><input type="password" name="upwd"/></td>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
status.jsp
LoginController.java
1. package com.durgasoft.controllers;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.ui.ModelMap;
7. import org.springframework.web.bind.annotation.RequestMapping;
8. import org.springframework.web.bind.annotation.RequestParam;
465
9. import org.springframework.web.bind.annotation.SessionAttributes;
10. import org.springframework.web.servlet.ModelAndView;
Page
11.
12.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.java
16. </bean>
17. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
467
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
index.jsp
1. <html>
2. <body>
3. <jsp:forward page="hellopage"/>
4. </body>
5. </html>
helloform.jsp
21. </table>
22. </form>
23. </body>
Page
24. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HelloController.java
1. package com.durgasoft.controllers;
2.
3. import org.springframework.stereotype.Controller;
4. import org.springframework.ui.ModelMap;
5. import org.springframework.web.bind.annotation.RequestMapping;
6. import org.springframework.web.bind.annotation.RequestParam;
7.
8. @Controller
9. public class HelloController {
10. @RequestMapping("/hellopage")
11. public String helloPage() {
12.
13. return "helloform";
14. }
15.
16. @RequestMapping("/wish")
469
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
16. </web-app>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
36. </dependency>
37.
Page
38.
39. <dependency>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
472
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To prepare Controller classes, Spring framework has provided a set of predefined classes in
"org.springframework.web.servlet.mvc" package an which are implemented by Controller
interface.
AbstractController:
This Controller Classe will be used to prepare Controller classes where no form data submission
in request, but, it will dispay dynamic content through web pages.
AbstractController class is able to have the following method to have Business logic or the code to
access business components.
-----
Note: In all the cases, no form submission is going on, but, dynamic content will be included in
Page
response.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
wish.jsp
WishController.java
1. package com.durgasoft.controller;
2.
3.
4. import java.time.LocalTime;
5.
474
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
Page
8.
9. import org.springframework.web.servlet.ModelAndView;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
17. </bean>
18. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
476
index.jsp
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
home.jsp
contactUs.jsp
8. </head>
9. <body>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
aboutUs.jsp
HomeController.java
1. package com.durgasoft.controller;
2.
478
3.
4. import javax.servlet.http.HttpServletRequest;
Page
5. import javax.servlet.http.HttpServletResponse;
6.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
24. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Internal Flow:
handleRequestInternal() method will be executed, it will return "viewName" property value as
ModelAndView object , that is, logical name of the View, where ViewResolver will resolve the View
Page and generate the respective webpage as response.
EX:
public class ParameterizableViewController extends Abstractcontroller{
public ModelAndView handleRequestInternal(HttpServletRequest request,
HttpservletResponse response)throws Exception{
return new ModelAndView(getViewName());
}
}
MultiActionController:
In general, in Spring WEB MVC applications, we will for each and every form or an URI we will
prepare a separate Controller class depending on our requirement.
In the above approach, if we want to provide a particular Entity related actions like save, update,
search and delete then we have to prepare seperate Controller classes like SaveController,
UpdateController, SearchController, DeleteController... it will increase no of controller classes
480
unnecessarily.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The main intention of MultiActionController class is to group related actions into a single controller
class.
If we want to use MultiAction controller class in Spring WEB MVC applications then we have to
declare an user defined class as sub class to "MultiActionController" and we have to define action
methods with the same incoming URI names.
Ex:
19.
20. In the above context, if we submit "http://lh:1010/app/save" then save() method in StudentA
Page
ction class will be executed, similarily, search(), update(), delete(),.. methods will be execut
ed as per the URI values from clients like search, update, delete...
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
index.jsp
home.jsp
6. <meta charset="ISO-8859-1">
7. <title>Insert title here</title>
Page
8. </head>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
addform.jsp
29. <tr>
30. <td><input type="submit" value="ADD"/></td>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
searchform.jsp
updateform.jsp
484
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
student_edit_form.jsp
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
deleteform.jsp
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
student.jsp
28. </table>
29. <h3>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
status.jsp
HomeController.java
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.web.servlet.ModelAndView;
7. import org.springframework.web.servlet.mvc.AbstractController;
8.
9. public class HomeController extends AbstractController {
10.
11. @Override
488
13.
14. return new ModelAndView("home");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentAction.java
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.web.servlet.ModelAndView;
7. import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
8.
9. import com.durgasoft.dao.StudentDao;
10. import com.durgasoft.dto.StudentTo;
11.
12. public class StudentAction extends MultiActionController {
13. StudentDao studentDao;
14. String status = "";
15. String message = "";
16.
17. public void setStudentDao(StudentDao studentDao) {
18. this.studentDao = studentDao;
19. }
20.
21. public ModelAndView add(HttpServletRequest request, HttpServletResponse response)
throws Exception{
22. StudentTo sto = new StudentTo();
23. sto.setSid(request.getParameter("sid"));
24. sto.setSname(request.getParameter("sname"));
25. sto.setSaddr(request.getParameter("saddr"));
26. status = studentDao.add(sto);
27. if(status.equals("success")) {
28.
29. message = "Student Added Successfully";
30. }
31. if(status.equals("failure")) {
32. message = "Student Insertion Failure";
33. }
489
34. if(status.equals("existed")) {
35. message = "Student Existed Already";
Page
36. }
37. return new ModelAndView("status", "message", message);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
74. }else {
75. mav = new ModelAndView("status", "message", "Student Updation Failure");
Page
76. }
77. return mav;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentDao.java
1. package com.durgasoft.dao;
2.
3. import com.durgasoft.dto.StudentTo;
4.
5. public interface StudentDao {
6. public String add(StudentTo sto);
7. public StudentTo search(String sid);
8. public String update(StudentTo sto);
9. public String delete(String sid);
10. }
11.
12. StudentDaoImpl.java
13. --------------------
14. package com.durgasoft.dao;
15.
16. import java.util.List;
17.
491
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
60. std_Entity.setSname(resultSet.getString("SNAME"));
61. std_Entity.setSaddr(resultSet.getString("SADDR"));
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
104. }
105.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentTo.java
1. package com.durgasoft.dto;
2.
3. public class StudentTo {
4. private String sid;
5. private String sname;
6. private String saddr;
7.
8. public String getSid() {
9. return sid;
10. }
11. public void setSid(String sid) {
12. this.sid = sid;
13. }
14. public String getSname() {
15. return sname;
16. }
17. public void setSname(String sname) {
18. this.sname = sname;
19. }
20. public String getSaddr() {
21. return saddr;
22. }
23. public void setSaddr(String saddr) {
24. this.saddr = saddr;
25. }
26.
27.
28. }
ds-servlet.xml
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:p="http://www.springframework.org/schema/p"
Page
5. xmlns:context="http://www.springframework.org/schema/context"
6. xsi:schemaLocation="
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
43.
44. <bean name="/*" class="com.durgasoft.controller.StudentAction">
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
26.
27.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To run the above application we need the following jar files in web application lib folder.
o commons-logging-1.2.jar
o ojdbc6.jar
o spring-aop-4.3.9.RELEASE.jar
o spring-aspects-4.3.9.RELEASE.jar
497
o spring-beans-4.3.9.RELEASE.jar
o spring-context-4.3.9.RELEASE.jar
o spring-context-support-4.3.9.RELEASE.jar
Page
o spring-core-4.3.9.RELEASE.jar
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. Command Controllers:
Command Class:
Command Class is a normal Java Bean class, it can be instantiate by Spring WEB MVC
framework inorder to store form data which is submitted by the respective Client along with
request.
6. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to use Command classes in Spring WEB MVC Applications then we have to use
Command Controller Classes.
Spring has provided the following Command Controller classes to use Command classes.
1. BaseCommandController
2. AbstractCommandController
3. AbstractFormController
4. SimpleFormController
5. AbstractWizardFormController
1. BaseCommandController:
It is a base class for all Command Controller classes which are wishing to populate request
parameters data in Command class objects.
2. AbstractCommandController:
This controller class will populate form data in Command class objects automatically by creating
Command class object for each and every request.
In general, we will use Controller class when we have form submission from client and when we
dont want to perform Data Validations at Server side.
499
If we want to use this CommandController class then we have to declare an user defined class
and it must be extended from "AbstractCommandController" abstract class and we must override
Page
handle(--) method.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
index.jsp
loginform.jsp
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html>
Page
4. <html>
5. <head>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
status.jsp
16. </body>
17. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.validation.BindException;
7. import org.springframework.web.servlet.ModelAndView;
8. import org.springframework.web.servlet.mvc.AbstractCommandController;
9.
10.
11. import com.durgasoft.command.User;
12.
13. public class LoginController extends AbstractCommandController{
14. @Override
15. protected ModelAndView handle(HttpServletRequest request, HttpServletResponse res
ponse, Object command, BindException exception)
16. throws Exception {
17. User user = (User)command;
18. String uname = user.getUname();
19. String upwd = user.getUpwd();
20. ModelAndView mav = null;
21. if(uname.equals("durga") && upwd.equals("durga")) {
22. mav = new ModelAndView("status", "message", "User Login Success");
23. }else {
24. mav = new ModelAndView("status", "message", "User Login Failure");
25. }
26. return mav;
27. }
28. }
User.java
1. package com.durgasoft.command;
2.
3. import java.io.Serializable;
4.
5. public class User implements Serializable{
502
8.
9. public String getUname() {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
3. AbstractFormController
Where processFormSubmission() method will handle the request , It will include the
application logic which we want to execute after submmitting form, It will be executed when
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
This controller class will populate form data in Command class objects automatically eithet by
creating Command class object for each and every request or it will reuse the command class
object from session scope if we set "sessionForm" property value true.
In general, we will use Controller class when we have form submission from client and when we
dont want to perform Data Validations at Server side.
If we want to use this CommandController class then we have to declare an user defined class
and it must be extended from "AbstractCommandController" abstract class and we must override
processFormSubmission(--) method and showForm() method.
Note: In User defined Controller class , we have to provide 0-arg constructor, where we have to
set command class by using the following method.
public void setCommandClass(Class class)
or
We have to set the following properties in Controller bean configurations in spring configuration
file.
1. sessionForm --> true
2. commandName --> any name
3. commandClass --> Fully qualified name of the command class.
Note: AbstractFormController class is deprecated in Spring3.x version, to use this Controller class
we have to use either Spring2.5 version atleast Spring3.x version.
Example:
index.jsp
12. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
37. </body>
38. </html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Student.java
507
1. package com.durgasoft.command;
2.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentController.java
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.validation.BindException;
7. import org.springframework.web.servlet.ModelAndView;
508
8. import org.springframework.web.servlet.mvc.AbstractFormController;
9.
Page
10.
11. import com.durgasoft.command.Student;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
In SPring WEB MVC based applications, to prepare Presentation or View part we are able to use
basic View technologies like HTML, JSP, JSTL , Velocity , Free Marker,......
In Spring WEB MVC based applications, to prepare User Forms Spring WEB MVC framework has
given a seperate tag library.
510
To use Spring WEB MVC web applications if we want to use Spring provided tag library then we
have to use keep spring-webmvc.jar in web application lib folder and we have to use the following
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Spring has provided the following set of form tags to prepare User forms.
1.<form:form>
It is same as html <form> tag, it will gather/group all other Html components to take data from
users inorder to submit data to Server side application.
Syntax:
registrationform.jsp
User.java
ds-servlet.xml
<beans>
-----
511
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2. <form:input>
This tag is same as HTML <input type=‖text‖/> tag, it will create textfield in user form , it is an input
GUI component, it will take a line text data from Users.
Syntax:
Where "path" attribute will take reference name to the text field and it must be same as a
property in Command class having setter and getter method.
Where "size" attribute will take textfield size.
Where "value" attribute will take a default message to display while preparing text field.
3. <form:password>
It will generate password field in user form, it is same as "<input type="password"/>" tag, it will
512
Syntax:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where "path" atribute will take reference name to the password field, it must be same as
the property defined in the respective Command class having setter and getter methods.
Where "value" atrribute will take default password value to display while creating password
field.
Where "showPassword" property will take either true/false value to show or not to show
password data in password field while providing password data.
EX:
<form:form ----->
User Password<form:password name="upwd" showPassword="false"/>
</form:form>
In Command class:
public class User{
private String upwd;
----
public void setUpwd(String upwd){
this.upwd = upwd;
}
public String getUpwd(){
return upwd;
}
---
}
Note: "showPassword" attribute is not working in Applications as part of my testing, but, Spring
Framework has provided "showPassword" attribute in documentation.
4. <form:checkbox>
It will provide checkbox in user form, it is same as Html <input type="checkbox"> tag and it will
submit a boolean value to the Server side application on the basis of the selection. If we select
checkbox then it will send "true" value , if we are not selecting checkbox then it will send false
value to server side application.
Syntax:
513
Where "path" attribute will take reference name to the checkbox, it must be same as the
Page
boolean property existed in Command class having setXXX() and isXXX() method.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
<form:form ---->
R U Married?<form:checkbox path="Married"/>
</form:form>
In Command Class:
public class User{
private boolean married;
----
public void setMarried(boolean married){
this.married = married;
}
public boolean isMarried(){
return married;
}
}
EX:
In Command Class:
public class User{
private String maritalStatus;
----
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
public String getMaritalStatus() {
if(maritalStatus == null || maritalStatus.equals("")) {
maritalStatus="Not Married";
}
return maritalStatus;
514
}
----
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Syntax:
Where "path" attribute will take reference value of all checkboxes , it must have a property
of String[] in the respective command class having setXXX() and getXXX() methods.
Where "items" attribute will take an expression including a property from Command class
providing checkbox labels and values or a Property data which is generated by overriding
referenceData() method in controller class.
EX:
In Controller class:
public class RegistrationController extends SimpleFormController{
@Override
protected Map referenceData(HttpServletRequest request) throws Exception {
Map<String, Object> map = new HashMap<>();
List<String> qual_List = new ArrayList<>();
qual_List.add("BSC");
qual_List.add("BTech");
qual_List.add("MCA");
qual_List.add("MTech");
qual_List.add("PHD");
map.put("qual_List", qual_List);
return map;
}
@Override
protected ModelAndView onSubmit(Object command) throws Exception {
User user = (User)command;
515
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
6. <form:radiobutton>
Syntax:
Where "path" attribute will take a reference name , it must be same as the property in
Command class having setXXX() method and getXXX() method.
Where "value" attribute will take radio button value inorder to send to Server side
application.
EX:
}
---
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Syntax:
Where "path" attribute will take reference name to the radio buttons which same as the
property name in command class inorder to store the seleted radio button value.
Where "items" attribute will take the property name of the List or String[] which contains all
the names of the Radio Buttons which is generated from referencedData() method from the
respective controller class.
EX:
In Command class:
public class User{
private String uworkLocation;
----
public void setUworkLocation(String uworkLocation){
this.uworkLocation = uworkLocation;
}
public String getUworkLocation(){
return uworkLocation;
}
}
In Controller class:
uworkLocation.add("Mumbai");
map.put("uworkLocation", uworkLocation);
Page
return map;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
8. <form:select>
<form:select> tag can be used to create select box, it is same as html <select> tag, it will display
list of items to select either multiple or single depending on our option.
Syntax:
Where "path" attribute will take reference value to the Select box , it must be same as the
respecitve property name in command class inorder to store the selected values.
Where "multiple" attribute will take either "true" or "false" value inorder make "multiple"
selections or "single" selection in the select box.
Where "items" attribute will take a property name of Map type contains the Item values and
itemLabels which is generated from referenceddata() method of the contoller class.
Note: If we want to provide items to the select box individually , not as a Map from controller class
then we have to use <form:option> tag as chaild tag to <form:select> tag.
Syntax:
Note: If we want to get all the Item Values and Item Labels from referencesData() method in
Controller class then we have to use <form:options> tag.
Syntax:
Where "items" attribute will take a property representing Map object contains item values and item
Labels from referencedData() method in Controiller class.
518
EX:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Command Class:
public class User{
private String[] uskillSet;
----
public void setUskillSet(String[] uskillSet){
this.uskillSet = uskillSet;
}
public String[] getUskillSet(){
return uskeillSet;
}
}
EX:
In Command Class:
public class User{
private String[] uhobbies;
----
public void setUhobbies(String[] uhobbies){
this.uhobbies = uhobbies;
}
public String[] getUhobbies(){
return uhobbies;
}
}
In Controller class:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
map.put(―uhobbies‖, uhobbies);
return map;
}
EX:
IN Command Class:
public class User{
private String uprofession;
----
public void setUprofession(String uprofession){
this.uprofession = profession;
}
public String getUprofession(){
return uprofession;
}
}
9. <form:textarea>
It will provide text area to take multiple lines of data from Users, it is same as <textarea> tag in
Html.
Syntax:
<form:textarea path="--"/>
Where "path" attribute will take reference name to the textarea which is same as a property in
Command class.
EX:
<form:textarea path="uaddr"/>
520
In Command class:
public class User{
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
10. <form:hidden>
It will prepare Hidden field in user forms, it is same as <input type="hidden"/> in Html.
Syntax:
EX:
In Command Class:
public class Student{
private String sid;
public void setSid(String sid){
this.sid = sid;
}
public String getSid(){
return sid;
}
}
4. SimpleFormController:
This controller class is able to support the Command classes inorder to store form data in
Command class objects when we submit user forms.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to use this controller class then we have to declare an user defined class and it must be
extended from SimpleFormController class and we must implement either of the following
methods.
onSubmit(--) method will take the application logic which we want to execute by submitting form
from client.
If we want to use this Controller class, we must provide the the following properties in Controller
class configuration.
1. formView: it will take form name to get User form.
2. commandName: it will take logical name to the command class.
3. commandClass: It will take fully qualified name of the command class.
4. sessionForm: to keep Command Object in session scope inorder to reuse command
object.
index.jsp
9. <body>
10. <jsp:forward page="reg"></jsp:forward>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
registrationform.jsp
35. </tr>
36. <tr>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
78. </tr>
79. <tr>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
status.jsp
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
75. </h3>
76.
Page
77. </body>
78. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.command;
2.
3. import java.io.Serializable;
4.
5. public class User implements Serializable{
6. private String uname;
7. private String upwd;
8. private boolean maritalStatus1;
9. private String maritalStatus2;
10. private String[] uqual;
11. private String ugender;
12. private String uworkLocation;
13. private String uskillSet;
14. private String[] uhobbies;
15. private String uprofession;
16. private String uaddr;
17.
18.
19. public String getUname() {
20. return uname;
21. }
22. public void setUname(String uname) {
23. this.uname = uname;
24. }
25. public String getUpwd() {
26. return upwd;
27. }
28. public void setUpwd(String upwd) {
29. this.upwd = upwd;
30. }
31.
32. public void setMaritalStatus1(boolean maritalStatus1) {
33. this.maritalStatus1 = maritalStatus1;
34. }
35. public boolean isMaritalStatus1() {
36. return maritalStatus1;
37. }
527
38.
39. public void setMaritalStatus2(String maritalStatus2) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
83.
84. public void setUprofession(String uprofession) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
RegistrationController.java
1. package com.durgasoft.controller;
2.
3. import java.util.ArrayList;
4. import java.util.HashMap;
5. import java.util.List;
6. import java.util.Map;
7.
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10.
11. import org.springframework.validation.BindException;
12. import org.springframework.web.servlet.ModelAndView;
13. import org.springframework.web.servlet.mvc.SimpleFormController;
14.
15. import com.durgasoft.command.User;
16.
17. public class RegistrationController extends SimpleFormController{
18.
19. @Override
20. protected Map referenceData(HttpServletRequest request) throws Exception {
21. Map<String, Object> map = new HashMap<>();
22.
23. List<String> qual_List = new ArrayList<>();
529
24. qual_List.add("BSC");
25. qual_List.add("BTech");
Page
26. qual_List.add("MCA");
27. qual_List.add("MTech");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
6. xsi:schemaLocation="
7. http://www.springframework.org/schema/beans
Page
8. http://www.springframework.org/schema/beans/spring-beans.xsd
9. http://www.springframework.org/schema/context
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
10. <welcome-file>default.jsp</welcome-file>
11. </welcome-file-list>
Page
12. <servlet>
13. <servlet-name>ds</servlet-name>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
5. AbstractWizardFormController:
In general, In web applications , it is required to display more than one page in order to complete a
given task.
IN general, in Web applications, we will use multiple pages to enter user details like general
details, qualification details, communication details,....in User registration process, to achieve this
we have to use "Wizard".
To support for the Wizards in web applications, Spring Web MVC has provided a predefined
controller in the form of "org.springframework.web.servlet.mvc.AbstractWizardFormController".
AbstractWizardFormController allows us to carry the same command object through an entire flow
of Web pages in Wizard.
If we want to use AbstractWizardController class in Spring web MVC applications then we have to
use the following steps.
1. Prepare multiple web pages with the buttons where names of the buttons must be
a) _finish: Finish the wizard form.
b) _cancel: Cancel the wizard form.
c) _targetx: Move to the target page, where x is the zero-based page index.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
index.jsp
welcomepage.jsp
4. <html>
5. <head>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
form1.jsp
28. </td>
29. </tr>
Page
30. </table>
31. </center>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
form2.jsp
33. </form:form>
34. </body>
Page
35. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
userdetails.jsp
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
43. </body>
44. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.validation.BindException;
7. import org.springframework.web.servlet.ModelAndView;
8. import org.springframework.web.servlet.mvc.AbstractWizardFormController;
9.
10. import com.durgasoft.command.User;
11.
12. public class UserController extends AbstractWizardFormController {
13.
14. @Override
15. protected ModelAndView processFinish(HttpServletRequest request, HttpServletRespon
se response, Object command,
16. BindException exception) throws Exception {
17. User user = (User)command;
18. return new ModelAndView("userdetails", "user", user);
19. }
20.
21. @Override
22. protected ModelAndView processCancel(HttpServletRequest request, HttpServletRespo
nse response, Object command,
23. BindException errors) throws Exception {
24. // TODO Auto-generated method stub
25. return new ModelAndView("welcomepage");
26. }
27.
28.
29. }
User.java
1. package com.durgasoft.command;
2.
3. public class User {
538
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
47.
48.
Page
49. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
540
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
541
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we check whether data is valid or not at client browser after entering data in user forms and
before submitting form to Server then it is called as Client Side Data Validations.
To perform Client Side data Validations we will use Java Script functions.
To perform Server side data validation we will use JAVA code at server side.
Spring is providing Server side Data validations in the following two ways.
1. By Using Spring provided Error class.
2. By Using Java provided validation annotations
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2. Provide Properties file under src or in a package under properties file with validation
messages in the form of key-value pairs.
3. Configure Validator class and Properties file with "messageSource" property under
org.springframework.context.support.ResourceBundleMessageSource
Example:
index.jsp
registrationform.jsp
10. .error{
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
50. </tr>
51. <tr>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
registrationdetails.jsp
31. <tr>
32. <td>User Mobile No</td>
Page
33. <td>${user.umobile}</td>
34. </tr>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
User.java
1. package com.durgasoft.command;
2.
3. public class User {
4. private String uname;
5. private String upwd;
6. private int uage;
7. private String uemail;
8. private String umobile;
9.
10. public String getUname() {
11. return uname;
12. }
13. public void setUname(String uname) {
14. this.uname = uname;
15. }
16. public String getUpwd() {
17. return upwd;
18. }
19. public void setUpwd(String upwd) {
20. this.upwd = upwd;
21. }
22. public int getUage() {
23. return uage;
24. }
25. public void setUage(int uage) {
26. this.uage = uage;
27. }
28. public String getUemail() {
29. return uemail;
30. }
31. public void setUemail(String uemail) {
32. this.uemail = uemail;
546
33. }
34. public String getUmobile() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
UserController.java
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.validation.BindException;
7. import org.springframework.web.servlet.ModelAndView;
8. import org.springframework.web.servlet.mvc.SimpleFormController;
9.
10. import com.durgasoft.command.User;
11.
12. public class UserController extends SimpleFormController {
13. @Override
14. protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse r
esponse, Object command,
15. BindException errors) throws Exception {
16. User user = (User)command;
17. return new ModelAndView("registrationdetails", "user", user);
18. }
19. }
UserValidator.java
1. package com.durgasoft.validator;
2.
3. import org.springframework.validation.Errors;
4. import org.springframework.validation.ValidationUtils;
5. import org.springframework.validation.Validator;
6.
7. import com.durgasoft.command.User;
547
8.
9. public class UserValidator implements Validator {
Page
10.
11. @Override
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
validation_Messages.properties
uname.required = User Name is Required.
upwd.required = User Password is required.
uage.required = User Age is Required.
uemail.required = User Email Id Required.
548
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
web.xml
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Hibernate has provided its validation API which contains Java provided Validation API and some
extra validation rules.
1. @NotEmpty
It will be applied to the bean variables or getter methods.
It will check whether data is existed in the respecxtive bean property or not.
If the data is not existed in the bean property then it will raise validation error.
It is applicable for only String type propertirs.
2. @NotNull
It will be applied to the bean variables or getter methods.
It will check whether data/value is existed in the respective bean property or not.
If the data is not existed in the bean property then it will raise validation error.
550
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: If we dont want to use @Size annotation then we will use @Min and @Max annotation
4. @Range
It will be applied to the bean variables or getter methods.
It is applied for the numeric data type properties.
It will check the value as per the specified range.
It will take two parameters min and max
5. @Pattern
It will be applied either for property or for getter method directly.
It will check whether the property data is as per the provided reg exp.
It will take a parameter like "regexp", it will take pattern.
6. @Email
It will be applied either for property or for getter method directly.
It will check whether the value of a property is email id or not.
It will not require any parameter.
7. @DateTimeFormat
It will be applied either for property or for getter method directly.
It will be applied for Date type properties.
It will check whether the date value in a property is as per the specified format or not.
It will take a parameter like "pattern" to represent Date type patterns.
It will be applied for the properties in bean of Date type.
8. @Past
It will be applied either for property or for getter method directly.
It will check whether the date is past date or not.
It will be applied for the properties in bean of Date type.
Steps:
1. Use all the validation related annotations in Bean classes.
2. Declare properties file under src and provide validation messages.
3. Enable Annotations in Spring application through Spring configuration file.
4. Display Validation messages inside the pages.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
validation_Messages.properties
To define validation messages in properties file then we have to use the following format.
Annotation_Name.Model_name.Prop_Name = Validation Message
EX:
To enable Annotations in Spring applications we have to use the following tags in ds-servlet.xml
<context:component-scan base-package="com.durgasoft"/>
<mvc:annotation-driven>
To declare controller class and to define request mapping for the COntroller class we have to use
the following annotations:
@Controller
@RequestMapping
To use the above annotations in Spring web applications we have to use the following JARs in
web application lib folder.
1) All Spring web MVC JARs
2) clasmate-varsion.jar
3) hibernate-validator-5.x/4.x.final.jar
4) jboss-logging-version.jar
5) validation-api-version.jar
Example:
552
index.jsp
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
registrationform.jsp
25. <table>
26. <tr>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
registrationdetails.jsp
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
User.java
Page
1. package com.durgasoft.command;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
41.
42. public String getUname() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
UserController.java
557
1. package com.durgasoft.controller;
2.
Page
3.
4. import javax.validation.Valid;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
validation_Messages.properties
typeMismatch = {0} is in invalid format
NotEmpty.user.uname = User Name is Required.
NotEmpty.user.upwd = User Password is Required.
Size.user.upwd = User Password must be minimum {2} characters and maximum {1}
characters.
558
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example on Data Validations through Java Validation API provided Annotations by using
properties file provided validation Messages:
index.jsp
4. <html>
5. <head>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
reg_form.jsp
30. <tr>
31. <td>User Password</td>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
registrationdetails.jsp
9. <body>
10. <h2 style="color: red;" align="center">Durga Software Solutions</h2>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
User.java
1. package com.durgasoft.command;
2.
3. import java.util.Date;
4.
5. import javax.validation.constraints.NotNull;
563
6. import javax.validation.constraints.Past;
7. import javax.validation.constraints.Pattern;
Page
8. import javax.validation.constraints.Size;
9.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
48. }
49. public void setUpwd(String upwd) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
UserController.java
1. package com.durgasoft.controller;
2.
3. import javax.validation.Valid;
4.
5. import org.springframework.stereotype.Controller;
6. import org.springframework.ui.Model;
7. import org.springframework.validation.BindingResult;
565
8. import org.springframework.web.bind.annotation.RequestMapping;
9. import org.springframework.web.bind.annotation.RequestMethod;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
error_Messages.properties
typeMismatch = {0} is in invalid format
ds-servlet.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Spring Web MVC has provided a set of predefined HandlerMappings in the package like
"org.springframework.web.servlet.handler".
Spring Web MVC has provided the following predefined HandlerMapping classes.
1. BeanNameUrlHandlerMapping
2. SimpleUrlHandlerMapping
3. ControllerClassNameHandlerMapping
4. DefaultAnnotationHandlerMapping
1. BeanNameUrlHandlerMapping:
It is the default HandlerMapping in Spring web MVC applications if we use XML
configurations, it is not required to configure in Spring configuration file.
BeanNameUrlHandlerMapping is able to identify the Controller classes by mapping the
incoming request URI with the Bean identity["id" attribute value] or Bean logical name[
"name" attribute value] which we defined in Spring configuration file.
EX:
ds-servlet.xml
<beans>
-----
<bean name="handlerMapping"
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/welcome" class="com.durgasoft.controller.WelcomeController"/>
------
</beans>
If we submit request with the URI "welcome" then BeannameUrlHandlerMapping is able to map
"welcome" with "name" attribute value in <bean> tag , if it is matched then
BeanNameUrlHandlerMapping will confirm the respective Controller class is
"com.durgasoft.controller.WelcomeController" and send its details to DispatcherServlet.
EX: http://localhost:1010/app/welcome
568
Example:
index.jsp
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
helloform.jsp
24. </form>
25. </body>
Page
26. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HelloFormController.java
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6.
7. import org.springframework.web.servlet.ModelAndView;
8. import org.springframework.web.servlet.mvc.Controller;
9.
10. public class HelloFormController implements Controller {
11.
12. @Override
13. public ModelAndView handleRequest(HttpServletRequest request, HttpServletRespons
e response) throws Exception {
14. return new ModelAndView("helloform");
15. }
16. }
WishController.java
570
1. package com.durgasoft.controller;
Page
2.
3. import javax.servlet.http.HttpServletRequest;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
20. </bean>
21. </beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2. SimpleUrlHandlerMapping:
d) SimpleUrlHandlerMapping will identify the controller class on the basis of logical name
which we get from the matched property.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <beans>
2. -----
3. <bean name="wishController" class="com.durgasoft.controller.WishController"/>
4. <bean name="welcomeController" class="com.durgasoft.controller.WelcomeController"/>
From the above example, if we submit request with the URI "wish" then SimpleUrlHandlerMapping
will map this URI with properties names configured in Spring configuration file and it will identify
"wishController" as value and it will identify the respective controller class like
"com.durgasoft.controllers.WishController" from Spring configuration file.
EX:
Example:
index.jsp
9. <body>
10. <jsp:forward page="hello"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
helloform.jsp
wish.jsp
4. <html>
5. <head>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HelloFormController.java
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6.
7. import org.springframework.web.servlet.ModelAndView;
8.
9. import org.springframework.web.servlet.mvc.Controller;
10.
11. public class HelloFormController implements Controller {
12.
13. @Override
14. public ModelAndView handleRequest(HttpServletRequest request, HttpServletRespons
e response) throws Exception {
15. return new ModelAndView("helloform");
16. }
17. }
WishController.java
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.web.servlet.ModelAndView;
7. import org.springframework.web.servlet.mvc.Controller;
8.
575
11. @Override
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
28. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. ControllerClassHandlerMapping
org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping is able to
map the incoming request URI with the Controller class by following the below convention.
a) It will take request URI value and removes extension if any extension.
b) It will make the first letter as Upper Case letter in the Request URI value.
c) It will append Controller to the modified Request URI value.
d) It will search for the respective controller class with the above convention and sends that
Controller class details to DispatcherServlet.
If we submit a request with the URI value "wish" then ControllerClassNameHandlerMapping will
577
search for the Controller class with the name "WishController", in this context, "name" attribute
must not be provided in the Controller class configuration
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
<beans ...>
<bean name="handlerMapping"
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean class="com.durgasoft.controller.HelloController" />
<bean class="com.durgasoft.controller.WelcomeController" />
</beans>
In the above example, if we submit request with the Request URI "wish" then WishContrlller class
will be mapped.
If we submit request with the URI "welcome" then WelcomeController class will be mapped.
EX:
If we want to map the request URI with the Contrlller class names in case insensitive manner then
we have to use "caseSensitive" property with the value "true".
EX:
<beans ...>
<bean name="handlerMapping"
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="caseSensitive" value="true"/>
<bean class="com.durgasoft.controller.HelloController" />
<bean class="com.durgasoft.controller.WelcomeController" />
</beans>
EX:
EXAMPLE:
578
index.jsp
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
helloform.jsp
25. </body>
26. </html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HelloFormController.java
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6.
7. import org.springframework.web.servlet.ModelAndView;
8.
9. import org.springframework.web.servlet.mvc.Controller;
10. public class HelloFormController implements Controller {
11.
12. @Override
13. public ModelAndView handleRequest(HttpServletRequest request, HttpServletRespons
e response) throws Exception {
14.
15. return new ModelAndView("helloform");
16. }
17. }
580
WishController.java
Page
1. package com.durgasoft.controller;
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
19. <props>
20. <prop key="/hello">helloFormController</prop>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
21. </web-app>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
It will map incoming request URI with the name provided along with the @RequestMapping
annotation which we provided above of the controller class or Controller class method.
EX:
index.jsp
helloform.jsp
13. <center>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
wish.jsp
WishController.java
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
584
6. import org.springframework.stereotype.Controller;
7. import org.springframework.web.bind.annotation.RequestMapping;
Page
8. import org.springframework.web.bind.annotation.RequestMethod;
9. import org.springframework.web.servlet.ModelAndView;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
22. </property>
23. </bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
19. <url-pattern>/</url-pattern>
20. </servlet-mapping>
Page
21. </web-app>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
28. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In web applications, we are able to provide single filter for multiple Servlets and JSPs and we are
able to provide multiple filters for Single Servlet or JSP.
In the above representation, when we submit request to the container for a particular Servlet then
container will perform the following actions.
1. Container will check whether any Filter or Filters are associated with the respective
Servlet or not.
2. If any Filter or Filters are associated with the Servlet then container will execute all the
Filters in one by one fashion in an order which we configured in web.xml file.
3. If the present request is satisfying Filter constraints then Container will forward request to
the next filter or to the Servlet if no filter is existed in next.
4. If the present request is not satisfying the Filter constraints then Filter will send response to
the client through all the previous filters.
5. If all the Filters are executed then Container will execute the respective Servlet, after
execution of the Servlet Container will send the generated response to the client
through all the Filters in reverse order.
Similarly in Spring Web MVC applications, if we want to provide Pre-Processing and Post-
Processing services to any controller or all the controllers components then we have to use
Interceptors.
If we provide Interceptors in Spring WEB MVC applications then they will be executed before
executing the controller, after executing the controller and then after sending response to client.
If we provide Interceptors in Spring WEB MVC applications then they will be executed before
executing the controller, after executing the controller and before sending response to client and
then after sending response to client.
If we want to use Interceptors in Spring WEB MVC applications then we have to use the following
two steps.
1. Prepare Interceptor class
2. Configure Interceptor class in Spring configuration File.
To prepare Interceptor class we have to declare an user defined class and either implement
org.springframework.web.servlet.HandlerInterceptor interface or extend
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If more than one Interceptor is provided for a controller component then all the Interceptors are
589
If we provide Multiple Interceptors in Spring WEDB MVC application then preHandle() methods
will be executed as per the Interceptors configuration order which we configured in Spring
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To configure Interceptor class in Spring configuration file , we have to use the following
approaches.
<beans>
-----
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="maintenanceInterceptor" />
<ref bean="executeTimeInterceptor" />
</list>
</property>
</bean>
----
</beans>
<beans>
----
<interceptors>
<interceptor>
<mapping path="/home" />
<beans:bean
class="com.durgasoft.interceptors.RequestProcessingTimeInterceptor"></beans:bean>
</interceptor>
</interceptors>
------
590
</beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
<beans>
-----
<mvc:interceptors>
<bean class="com.javapapers.spring.mvc.interceptor.GreetingInterceptor" />
<mvc:interceptor>
<mvc:mapping path="/AnimalList" />
<bean class="com.durgasoft.interceptor.AnimalInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
-----
</beans>
Example:
index.jsp
helloform.jsp
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
wish.jsp
18. </body>
19. </html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.stereotype.Controller;
7. import org.springframework.web.bind.annotation.RequestMapping;
8. import org.springframework.web.bind.annotation.RequestMethod;
9. import org.springframework.web.servlet.ModelAndView;
10.
11.
12. @Controller
13. @RequestMapping("/wish")
14. public class WishController {
15. @RequestMapping(method=RequestMethod.GET)
16. public String getForm() {
17. return "helloform";
18. }
19.
20. @RequestMapping(method=RequestMethod.POST)
21. public ModelAndView wish(HttpServletRequest request, HttpServletResponse response)
{
22. String uname = request.getParameter("uname");
23. return new ModelAndView("wish", "uname", uname);
24. }
25. }
ProcessingTimeInterceptor.java
1. package com.durgasoft.interceptor;
2. import javax.servlet.http.HttpServletRequest;
3. import javax.servlet.http.HttpServletResponse;
4.
5. import org.springframework.web.servlet.HandlerInterceptor;
6. import org.springframework.web.servlet.ModelAndView;
7.
8. public class ProcessingTimeInterceptor implements HandlerInterceptor {
593
9.
10. @Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
10. http://www.springframework.org/schema/context/spring-context.xsd">
11. <context:annotation-config/>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
18. <servlet-name>ds</servlet-name>
19. <url-pattern>/</url-pattern>
Page
20. </servlet-mapping>
21. </web-app>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Spring MVC, the main intention of view resolvers are to enable us to render models in a
browser without tying you to a specific view technology like JSP, Velocity, XML…etc.
1. ViewResolver: It will provide mapping between View names and the actual views.
2. View: It will take care of preparing Request and handsover to the respective View
Technology.
In Spring WEB MVC applications, ViewResolver takes logical name provided by Controller class
through DispatcherServlet and return View object point to the actual View page, in this context,
DispatcherServlet will access render() method on View object to render the control to view
resource.
Spring Web MVC has provided the following ViewResolvers to handle View in Spring WEB MVC
applications.
1. AbstractCachingViewResolver
2. XmlViewResolver
3. ResourceBundleViewResolver
4. UrlBasedViewResolver
5. InternalResourceViewResolver
6. VelocityViewResolver/FreeMarkerViewResolver
From the above list of View Resolovers , mainly we are able to use the following ViewResolvers in
Spring WEB MVC Applications
1. UrlBasedViewResolver
2. InternalResourceViewResolver
3. XmlViewResolver
4. ResourceBundleViewResolver
1. UrlBasedViewResolver:
This ViewResolver will take view logical name from Controller through DispatcherServlet and
596
searches for the view resources whose name is same as logical view name.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
<beans>
<bean name="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Note: If we want to use JstlView class as value to the property "viewClass" then we must provide
the following jar files in web application "lib" folder.
1 .taglibs-standard-impl-1.2.5.jar
2. taglibs-standard-spec-1.2.5.jar
Example:
index.jsp
12. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
wish.jsp
9. <body>
10. <h2 style="color: Red;" align="center">Durga Software Solutions</h2>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HelloController.java
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.stereotype.Controller;
7. import org.springframework.web.bind.annotation.RequestMapping;
8. import org.springframework.web.bind.annotation.RequestMethod;
9.
10. import org.springframework.web.servlet.ModelAndView;
11.
12.
13. @Controller
14. @RequestMapping("/hello")
15. public class HelloController {
16. @RequestMapping(method=RequestMethod.GET)
17. public String showForm() {
18. return "helloform";
19. }
20.
21. @RequestMapping(method=RequestMethod.POST)
22. public ModelAndView wish(HttpServletRequest request, HttpServletResponse response
){
23. String uname = request.getParameter("uname");
24. return new ModelAndView("wish", "uname", uname);
25. }
26. }
ds-servlet.xml
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:p="http://www.springframework.org/schema/p"
Page
5. xmlns:context="http://www.springframework.org/schema/context"
6. xsi:schemaLocation="
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
19. <servlet-name>ds</servlet-name>
20. <url-pattern>/</url-pattern>
Page
21. </servlet-mapping>
22. </web-app>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
This ViewResolver will take JstlView as default view, if we want to use Jsp pages as view pages
with out Jstl tags then we have to use "InternalResourceView" class as "viewClass".
To configure this ViewResolver in Spring Configuration File we have to use the following XML
tags.
EX:
<beans>
----
<bean name="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
-----
</beans>
3. XmlViewResolver:
XmlViewResolver is used to resolve the view names using view beans defined in xml file.
If we want to use this ViewResolver in Spring WEB MVC applications then we have to prepare an
XML file with all View Pages configuration by using <bean> tags. In Views XML configuration file
we have to configure "JstlView" class as bean with the logical name which is returned by the
Controller class, in side JstlView class configuration we have to provide a property "url" with the
name and location of the respective View page.
WEB-INF/views.xml
601
2. <beans xmlns="http://www.springframework.org/schema/beans"
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
After providing View configuration XML file then we must configure View Configuration file in
Spring Configuration File.
To provide View Configuration File configuration in Spring Configuration file we have to use
"location" property with the View configuration XMl file location in "XmlViewResolver"
configuration.
EX:
ds-servlet.xml
<beans>
----
<bean name="viewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location" value="/WEB-INF/views.xml"/>
-----
</beans>
Example:
index.jsp
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
helloform.jsp
wish.jsp
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HelloController.java
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.stereotype.Controller;
7. import org.springframework.web.bind.annotation.RequestMapping;
8. import org.springframework.web.bind.annotation.RequestMethod;
9.
10. import org.springframework.web.servlet.ModelAndView;
11.
12.
13. @Controller
14. @RequestMapping("/hello")
15. public class HelloController {
16. @RequestMapping(method=RequestMethod.GET)
17. public String showForm() {
18. return "helloform";
19. }
20.
21. @RequestMapping(method=RequestMethod.POST)
22. public ModelAndView wish(HttpServletRequest request, HttpServletResponse response
){
604
25. }
26. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
18. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4. ResourceBundleViewResolver:
If we want to use this ViewResolver in Spring WEB MVC applications then we have to prepare a
properties file under "src" folder with all View Pages configuration by using key-value pairs.
In Views properties file we have to configure "JstlView" class as value with the logical name which
is returned by the Controller class in the formate like
logical_Name.(class) = org.springframework.web.servlet.view.JstlView
606
In Views properties file, we have to provide a key "url" with the name and location of the
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX: src/views.properties
helloform.(class)=org.springframework.web.servlet.view.JstlView
helloform.url=/WEB-INF/pages/helloform.jsp
After preparing views properties file, we have to configure views properties file in Spring
configuration file under "ResourceBundleViewResolver" with the "basename" property.
EX:
<beans>
----
<bean name="viewResolver"
class=" org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views"/>
</bean>
----
</beans>
Example:
index.jsp
helloform.jsp
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
wish.jsp
13. </body>
14. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.controller;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.springframework.stereotype.Controller;
7. import org.springframework.web.bind.annotation.RequestMapping;
8. import org.springframework.web.bind.annotation.RequestMethod;
9.
10. import org.springframework.web.servlet.ModelAndView;
11.
12. @Controller
13. @RequestMapping("/hello")
14. public class HelloController {
15. @RequestMapping(method=RequestMethod.GET)
16. public String showForm() {
17.
18. return "helloform";
19. }
20. @RequestMapping(method=RequestMethod.POST)
21. public ModelAndView wish(HttpServletRequest request, HttpServletResponse response
){
22. String uname = request.getParameter("uname");
23. return new ModelAndView("wish", "uname", uname);
24. }
25. }
views.properties
helloform.(class)=org.springframework.web.servlet.view.JstlView
helloform.url=/WEB-INF/pages/helloform.jsp
wish.(class)=org.springframework.web.servlet.view.JstlView
wish.url=/WEB-INF/pages/wish.jsp
ds-servlet.xml
4. xmlns:p="http://www.springframework.org/schema/p"
5. xmlns:context="http://www.springframework.org/schema/context"
Page
6. xsi:schemaLocation="
7. http://www.springframework.org/schema/beans
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To perform File Upload operation in SPring WEB MVC applications, Spring WEB MVC framework
has provided some predefined library in the form of
"org.springframework.web.multipart.commons.CommonsMultipartResolver"
If we want to perform Upload operation in Spring WEB MVC applications then we have to use the
following steps.
EX:
uploadform.jsp
EX:UploadController.java:
@Controller
public class UploadController {
-----
@RequestMapping(value="/upload", method=RequestMethod.POST)
public ModelAndView uploadFiles(@RequestParam MultipartFile file) {
611
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
} catch (Exception e) {
status = "FAILURE";
e.printStackTrace();
}
return new ModelAndView("status", "status", status);
}
}
EX: ds-servlet.xml
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
Note: For File Upload operation, Spring Framework is using Commons File Upload library
internally, so that, we must provide the following JAR files in web application lib folder along with
all Spring JARs.
commons-fileupload-1.4.jar
commons-io-2.6.jar
Example:
index.jsp
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
uploadform.jsp
status.jsp
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html>
Page
4. <html>
5. <head>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
UploadController.java
1. package com.durgasoft.controller;
2.
3. import java.io.FileOutputStream;
4.
5. import org.springframework.stereotype.Controller;
6. import org.springframework.web.bind.annotation.RequestMapping;
7. import org.springframework.web.bind.annotation.RequestMethod;
8. import org.springframework.web.bind.annotation.RequestParam;
9. import org.springframework.web.multipart.MultipartFile;
10. import org.springframework.web.servlet.ModelAndView;
11.
12. @Controller
13. public class UploadController {
14. @RequestMapping(value="/upload", method=RequestMethod.GET)
15. public String showUploadForm() {
16. return "uploadform";
17. }
18.
19. @RequestMapping(value="/upload", method=RequestMethod.POST)
20. public ModelAndView uploadFiles(@RequestParam MultipartFile[] file) {
21. String status = "";
22.
23. try {
24. for(MultipartFile multipartFile: file) {
25. String file_Name = multipartFile.getOriginalFilename();
26. FileOutputStream fos = new FileOutputStream("E:/uploads/"+file_Name);
27. byte[] bt = multipartFile.getBytes();
28. fos.write(bt);
29. status = "SUCCESS";
614
30. }
31.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
16.
17. <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
18. <property name = "prefix" value = "/WEB-INF//" />
19. <property name = "suffix" value = ".jsp" />
20. </bean>
21.
22. </beans>
web.xml
3. <display-name>exception_handling_web</display-name>
4. <welcome-file-list>
Page
5. <welcome-file>index.html</welcome-file>
6. <welcome-file>index.htm</welcome-file>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
616
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to perform Download operation in Spring WEB MVC Application then we have to use
the following steps.
1. Prepare a File with "Download" button and with the downloadable resource.
EX:
downloadpage.jsp
IN Controller class and in action method we have to use the following steps.
a) Set Content Type as "APPLICATION/OCTET-STREAM".
response.setContentType("APPLICATION/OCTET-STREM);
b) Set "content-disposition" response header to response object.
response.setHeader("Content-Disposition", "attachment;filename=\""+fileName+"\"");
c) Create File and FileInputStream object with the downloadable resource.
File file = new File("E:\\images\\Java_Python.jpg");
FileInputStream fis = new FileInputStream(file);
d) Create OutputStream from response object.
OutputStream os = response.getOutputStream()
e) Get bit by bit from FileInputStream and write bit by bit to OutputStream
int val = fis.read();
while(val != -1) {
os.write(val);
val = fis.read();
}
Example:
617
index.jsp
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
downloadpage.jsp
DownloadController.java
Page
1. package com.durgasoft.controller;
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
18. <servlet-name>ds</servlet-name>
19. <url-pattern>/</url-pattern>
Page
20. </servlet-mapping>
21. </web-app>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Java is providing very good Internationalization support in Java applications due to UNICODE
representations and the predefined library like java.util.Locale and some of the predefined classes
from java.text package.
To provide Internationalization in Spring WEB MVC applications , Spring has provided very good
environment with the following two beans.
1. SessionLocaleResolver
2. LocaleChangeInterceptor
1. SessionLocaleResolver:
SessionLocaleResolver resolves locales by inspecting a predefined attribute in a user‘s session. If
the session attribute doesn‘t exist, this locale resolver determines the default locale from the
accept-language HTTP header.
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
2. LocaleChangeInterceptor:
LocaleChangeInterceptor interceptor detects if a special parameter is present in the current HTTP
request. The parameter name can be customized with the paramName property of this
interceptor. If such a parameter is present in the current request, this interceptor changes the
user‘s locale according to the parameter value.
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
621
</bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Prepare properties file for each and every local to which we want to support.
In Internationalization , we have to prepare a seperate properties file with the locale respective
messages in the form of Key-Value pairs, where keys must be in English and the values must be
in the respective language letters in the form of UNOCODE.
EX:
messages_en.properties
To get messages from properties files we have to use the following tag from Spring tag library with
the URI "http://www.springframework.org/tags".
<spring:message code="--"/>
Where code attribute will take key of the message defined in properties file.
registrationform.jsp
9. <td><spring:message code="uname"/></td>
10. <td><form:input path="uname"/></td>
Page
11. </tr>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
1. <beans>
623
erAdapter" />
4.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
messages_en.properties
title1 = Durga Software Solutions
title2 = User Registration Form
uname = User Name
upwd = User Password
uemail = User Email Id
umobile = User Mobile No
messages_it.properties
624
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
registrationform.jsp
6. <html>
7. <head>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
registrationdetails.jsp
2. pageEncoding="ISO-8859-1"%>
3. <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
I18NController.java
627
1. package com.durgasoft.controller;
2.
Page
3. import org.springframework.stereotype.Controller;
4. import org.springframework.web.bind.annotation.RequestMapping;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
User.java
1. package com.durgasoft.command;
2.
3. public class User {
4. private String uname;
5. private String upwd;
6. private String uemail;
7. private String umobile;
8.
9. public String getUname() {
10. return uname;
11. }
12. public void setUname(String uname) {
13. this.uname = uname;
14. }
15. public String getUpwd() {
16. return upwd;
17. }
18. public void setUpwd(String upwd) {
19. this.upwd = upwd;
20. }
628
23. }
24. public void setUemail(String uemail) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds-servlet.xml
25.
26. <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandle
Page
rMapping">
27. <property name="interceptors">
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
22. </web-app>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To manage all the web pages in standard manner we have to use templates.
In general, we will use the following templates to prepare web pages in web applications.
631
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To manage all the web pages in the above provided templates and to manage flow of execution
between all the web pages we have to use a Apache provided Tiles framework.
632
Apache Software Foundations has provided the complete Tiles Framework in the form of the
following JAR files.
Page
tiles-api-2.2.2.jar
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to use Tiles Framework in our web applications then we have to provide the above Jar
files in web application lib folder.
The web frameworks like Struts, JSF, Xwork2 .... are using already Tiles Framework to prepare
web applications.
Spring web MVC framework is also providing in built support for Tiles Framework Integration
inorder to prepare web applications.
If we want to use Tiles Framework in Spring web MVC applications then we have to use the
following steps.
To prepare Template pages we have to use the following Tiles tag library which is available with
the URI "http://tiles.apache.org/tags-tiles".
<tiles:insertAttribute name="--"/>
633
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
header.jsp
1. <html>
2. <body>
3. <h1 style="color: white;">DURGA SOFTWARE SOLUTIONS</h1>
634
4. </body>
5. </html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <html>
2. <body>
3. <br>
4. <h3>
5. <a href="add">Add Student</a><br><br>
6. <a href="search">Search Student</a><br><br>
7. <a href="delete">Delete Student</a>
8. </h3>
9. </body>
10. </html>
In Tiles based web applications, we have to define all tiles definitions in an xml file by using the
following xml tags.
In Tiles definitions file, we are able to extend one definition to another definition by using "extends"
attribute inorder to reuse tiles configurations and we are able to override one tile configuration to
Page
another tiles configuration just like normal inheritance and method overridding.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
org\apache\tiles\resources\tiles-config_2_1.dtd
EX:
tiles-defs.xml
pages names.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentController.java
1. @Controller
2. public class StudentController {
3.
4. @RequestMapping(value="/welcome", method=RequestMethod.GET)
5. public String welcome() {
6. return "welcomeDef";
7. }
8.
9. @RequestMapping(value="/add", method=RequestMethod.GET)
10. public ModelAndView addStudent() {
11. return new ModelAndView("addDef", "student", new Student());
12. }
13.
14. @RequestMapping(value="/search", method=RequestMethod.GET)
15. public ModelAndView searchStudent() {
16. return new ModelAndView("searchDef", "student", new Student());
17. }
18.
19. @RequestMapping(value="/delete", method=RequestMethod.GET)
20. public ModelAndView deleteStudent() {
21. return new ModelAndView("deleteDef", "student", new Student());
22. }
23.
24. @RequestMapping(value="/add", method=RequestMethod.POST)
25. public ModelAndView add(Student student) {
26. String status = studentService.addStudent(student);
27. return new ModelAndView("statusDef", "status", status);
28. }
29.
30. @RequestMapping(value="/search", method=RequestMethod.POST)
31. public ModelAndView search(Student student) {
32. Student std = studentService.searchStudent(student.getSid());
33. if(std == null) {
34. return new ModelAndView("statusDef", "status", "Student Not Existed");
35. }else {
637
38. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
ds-servlet.xml
1. <beans>
2. -----
3. <bean id="viewResolver"
4. class="org.springframework.web.servlet.view.UrlBasedViewResolver">
5. <property name="viewClass">
6. <value>
7. org.springframework.web.servlet.view.tiles2.TilesView
8. </value>
9. </property>
10. </bean>
11.
12. <bean id="tilesConfigurer"
13. class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
14. <property name="definitions">
15. <list>
16. <value>/WEB-INF/tiles-defs.xml</value>
17. </list>
18. </property>
19. </bean>
20. ------
638
21. </beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
index.jsp
layout.jsp
21. </td>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
header.jsp
menu.jsp
8. </head>
9. <body>
Page
10. <br>
11. <h3>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
welcome.jsp
footer.jsp
9. <body>
10. <h3 style="color: white" align="center">
Page
11. Durgasoft India Pvt Ltd., 202, HMDA, Mitrivanam, Ameerpet, Hyd-38
12. </h3>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
addstudent.jsp
34. </html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
deletestudent.jsp
9. </head>
10. <body><br><br>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
studentdetails.jsp
21. <tr>
22. <td>Student Address</td>
Page
23. <td>${student.saddr}</td>
24. </tr>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
status.jsp
StudentController.java
1. package com.durgasoft.controller;
2.
3. import org.springframework.beans.factory.annotation.Autowired;
4. import org.springframework.stereotype.Controller;
5. import org.springframework.web.bind.annotation.RequestMapping;
6. import org.springframework.web.bind.annotation.RequestMethod;
7. import org.springframework.web.servlet.ModelAndView;
8.
9. import com.durgasoft.beans.Student;
10. import com.durgasoft.service.StudentService;
11.
12. @Controller
13. public class StudentController {
14.
15. @Autowired
645
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentService.java
Page
1. package com.durgasoft.service;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentServiceImpl.java
1. package com.durgasoft.service;
2.
3. import org.springframework.beans.factory.annotation.Autowired;
4. import org.springframework.stereotype.Service;
5. import org.springframework.transaction.annotation.Transactional;
6.
7. import com.durgasoft.beans.Student;
8. import com.durgasoft.dao.StudentDao;
9. import com.durgasoft.entity.StudentEntity;
10.
11.
12. @Service("studentService")
13. public class StudentServiceImpl implements StudentService {
14.
15. @Autowired
16. private StudentDao studentDao;
17.
18. @Transactional
19. @Override
20. public String addStudent(Student std) {
21. StudentEntity stdEntity = new StudentEntity();
22. stdEntity.setSid(std.getSid());
23. stdEntity.setSname(std.getSname());
24. stdEntity.setSaddr(std.getSaddr());
25.
26. String status = studentDao.add(stdEntity);
27. return status;
28. }
647
29.
30. @Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentDao.java
1. package com.durgasoft.dao;
2.
3. import com.durgasoft.entity.StudentEntity;
4.
5. public interface StudentDao {
6. public String add(StudentEntity stdEntity);
7. public StudentEntity search(String sid);
8. public String delete(String sid);
9. }
StudentDaoImpl.java
1. package com.durgasoft.dao;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.springframework.beans.factory.annotation.Autowired;
648
6. import org.springframework.orm.hibernate4.HibernateTemplate;
7. import org.springframework.stereotype.Repository;
Page
8. import org.springframework.transaction.annotation.Propagation;
9. import org.springframework.transaction.annotation.Transactional;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
48. try {
49. stdEntity = (StudentEntity) hibernateTemplate.get(StudentEntity.class, sid);
Page
50.
51. } catch (Exception e) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Student.java
1. package com.durgasoft.beans;
2.
3. public class Student {
4. private String sid;
5. private String sname;
6. private String saddr;
7.
8. public String getSid() {
9. return sid;
10. }
11. public void setSid(String sid) {
12. this.sid = sid;
13. }
650
16. }
17. public void setSname(String sname) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentEntity.java
1. package com.durgasoft.entity;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="student")
10. public class StudentEntity {
11. @Id
12. @Column(name="SID")
13. private String sid;
14. @Column(name="SNAME")
15. private String sname;
16. @Column(name="SADDR")
17. private String saddr;
18.
19. public String getSid() {
20. return sid;
21. }
22. public void setSid(String sid) {
23. this.sid = sid;
24. }
25. public String getSname() {
651
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
tiles-defs.xml
28. </tiles-definitions>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
38. </bean>
39.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_4_0.xsd" id="WebApp_ID" version="4.0">
Page
3. <display-name>tilesapp</display-name>
4. <welcome-file-list>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To run this application we have to use the following JARs in web application lib folder.
Spring JARS:
spring-aop-4.3.9.RELEASE.jar
spring-aspects-4.3.9.RELEASE.jar
spring-beans-4.3.9.RELEASE.jar
spring-context-4.3.9.RELEASE.jar
spring-context-support-4.3.9.RELEASE.jar
spring-core-4.3.9.RELEASE.jar
spring-expression-4.3.9.RELEASE.jar
spring-jdbc-4.3.9.RELEASE.jar
655
spring-orm-4.3.9.RELEASE.jar
spring-tx-4.3.9.RELEASE.jar
Page
spring-web-4.3.9.RELEASE.jar
spring-webmvc-4.3.9.RELEASE.jar
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Jstl Jars
taglibs-standard-impl-1.2.5.jar
taglibs-standard-spec-1.2.5.jar
Hibernate Jars:
antlr-2.7.7.jar
commons-logging-1.2.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.11.Final.jar
hibernate-entitymanager-4.3.11.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
ojdbc6.jar
hibernate-core-4.3.11.Final.jar
hibernate-entitymanager-4.3.11.Final.jar
Page
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-1.1.0.Final.jar
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Spring_Struts Integration:
Struts Overview:
implementation
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Ans:
Web Frameworks will provide very good environment to prepare and execute web applications
only.
EX: Struts, JSF.
Application Frameworks will provide very good environment to prepare and execute any type of
JAVA/J2EE Applications including Standalone Applications, Web applications, Distributed
Applications,
EX: Spring
If we want to prepare Struts applications in Struts1.x version then we have to use the following
components
1. View
2. Deployment Descriptor
3. Controller [ActionServlet]
4. Action class
5. Action Form
6. Struts Configuration File
658
1. View:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
This type view part is able to provide only information to the user, which includes status of the
server side actions like Success, failure, ... and display a particular database table data,.....
EXAMPLE: success.html
This type of view part is able to provide a form to collect data from users and to submit data to the
server side applications.
In Struts applications, to prepare Presentation part we are able to use plain HTML tags, but, which
are not suggestible. In Struts applications it is suggestible to use Struts provided tag library.
EX: loginform.html
1. <html>
2. <body>
3. <form method="POSt" action="login.*">
4. <table>
5. <tr>
6. <td>User Name</td>
7. <td><input type="text" name="uname"/></td>
8. </tr>
9. <tr>
10. <td>Password</td>
11. <td><input type="password" name="upwd"/></td>
12. </tr>
13. <tr>
14. <td><ipnut type="submit" value="Login"/></td>
15. </tr>
16. </table></form></body></html>
659
The above login form with Struts provided html tag library
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2. Deployment Descriptor:
Deployment descriptor is web.xml file, it will provide description about our web application which is
required by the container in order to perform server side actions.
In general, in web applications, web.xml file will provide the following configuration details.
1. <web-app>
660
2. <servlet>
3. <servlet-name>actionServlet</servlet-name>
Page
4. <servlet-class>org.apache.struts.action.ActionServlet
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. Controller [ActionServlet]
Note: In Struts applications, ActionServlet is performing all the above actions by using
"RequestProcessor" internally.
In Struts based web applications, the main intention of ActionForm or FormBean component is to
manage a particular form data at Server side inorder to perform Server side data validations, to
transfer data from Controller layer to model layer or Vie layer,.....
To prepare Form Bean components in Struts applications we have to use the following rules and
regulations.
org.apache.struts.action.ActionForm .
2. Form Bean class must be public, it must not be abstract and final.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EXAMPLE:
LoginActionForm.java
In Struts based web applications, the main intention of Action class is to manage application logic
which we want to execute by getting request from client.
In Struts based web applications, to prepare Action class we have to use the following steps.
class.
2. Action class must be public class and it must not be abstract class.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note:In execute() method we must return ActionForward object with a particular Forward key
inorder to identify target view page, for this, we have to use the following method from
ActionMapping.
EX: LoginAction.java
struts-config.xml
In Struts based web applications, the main intention of struts configuration file is to provide
mappings between user forms amd the respective ActionForm classes and Action classes
,...... which are required by the ActionServlet inorder to perform Server side actions.
In Struts based web applications, the default name and location of configuration file is
"struts-config.xml" and "WEB-INF" location, but, it is possible to change this default name
and location but we must give that new name and location to the Struts Framework.
In Struts based web applications, configuration file is able to provide the following
configurations.
663
1. Datasource configurations.
2. Global Forwards configurations.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To prepare basic Struts based web applications we need to provide ActionForm class
configuration and action class configuration in struts connfiguration file.
Where <struts-config> is a root tag, it will include struts application configuration details.
Where <form-beans> tag is able to include no of form beans configurations.
Where <form-bean> tag is able to provide single form bean class configuration.
Where "name" attribute in <form-bean> tag is able to provide logical name to Form Bean
component.
Where "type" attribute in <form-bean> tag will take fully qualified name of the respective
form bean class.
Where <action-mappings> tag is able to include no of actions configurations.
Where <action> tag is able to provide mapping between user form, ActionForm class and
the respective Action class.
Where "path" attribute in <action> tag is able to take url pattern which we specified in User
form.
Where "name" attribute in <action> tag will take logical name of the form bean class which
664
class.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
Steps:
loginform.html
1. <!DOCTYPE html>
665
2. <html>
3. <head>
Page
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
success.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h2>Durga Software Solutions</h2>
9. <h3>User Login Status</h3>
10. <font color="red" size="6">
11. <b>User Login Success</b>
12. </font>
13. <h5>
14. <a href="./loginform.html">|User Login Form|</a>
15. </h5>
666
16. </body>
17. </html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h2>Durga Software Solutions</h2>
9. <h3>User Login Status</h3>
10. <font color="red" size="6">
11. <b>User Login Failure</b>
12. </font>
13. <h5>
14. <a href="./loginform.html">|User Login Form|</a>
15. </h5>
16. </body>
17. </html>
LoginActionForm.java
1. package com.durgasoft.beans;
2.
3. import org.apache.struts.action.ActionForm;
4.
5. public class LoginActionForm extends ActionForm {
6. private String uname;
7. private String upwd;
8.
9. public String getUname() {
10. return uname;
11. }
12. public void setUname(String uname) {
13. this.uname = uname;
14. }
15. public String getUpwd() {
16. return upwd;
17. }
667
20. }
21. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.action;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.apache.struts.action.Action;
7. import org.apache.struts.action.ActionForm;
8. import org.apache.struts.action.ActionForward;
9. import org.apache.struts.action.ActionMapping;
10.
11. import com.durgasoft.beans.LoginActionForm;
12.
13. public class LoginAction extends Action {
14. @Override
15. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRe
quest request,
16. HttpServletResponse response) throws Exception {
17. LoginActionForm laf = (LoginActionForm)form;
18. String uname = laf.getUname();
19. String upwd = laf.getUpwd();
20. String status = "";
21. if(uname.equals("durga") && upwd.equals("durga")) {
22. status = "success";
23. }else {
24. status = "failure";
25. }
26. return mapping.findForward(status) ;
27. }
28. }
struts-config.xml
6. <form-beans>
7. <form-bean name="loginForm" type="com.durgasoft.beans.LoginActionForm"/>
Page
8. </form-beans>
9. <action-mappings>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
If we want to integrate Struts application with Spring Framework then we have to use the following
steps.
In Struts and Spring Integration applications, we have to prepare presentation part as per Struts
rules and regulations only.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
success.jsp
failure.jsp
In Struts based web applications, we have to prepare ActionForm class inorder to manage user
form data at Server side .
In Struts applications, to prepare ActionForm class we will use the following steps.
1. Declare an USer defined class.
2. Extend org.apache.struts.action.ActionForm class to user defined class.
3. Declare properties as per user form in ActionForm class and provide setXXX() and
getXXX() methods for each and every property.
EX:
In Struts based web applications, the main intention of Action class is to include business logic or
to provide Business Components provided business method calls.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To prepare Action class in Struts with Spring integration applications we have to use the following
steps.
EX:
In Struts with Spring Integration application, we will provide Business component as per Spring
rules and regulation.
671
EX:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Struts with Spring Integration applications, we have to provide provide all Struts configurations
like FormBeans, Action classes,... and we must provide plug-in coinfiguration with the
"org.springframework.web.struts.ContextLoaderPlugIn" with the property "contextConfigLocation"
inorder to provide name and location of the Spring configuration.
<struts-config>
<form-beans>
<form-bean name="loginActionForm"
type="com.durgasoft.formbeans.LoginActionForm"/>
</form-beans>
<action-mappings>
<action path="/login" name="loginActionForm"
type="com.durgasoft.action.LoginAction">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/failure.jsp"/>
</action>
</action-mappings>
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-
INF/applicationContext.xml" />
</plug-in>
</struts-config>
In Struts with Spring Integration application we will prepare Spring configuration file with all the
beans configuration.
EX:
672
<beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
<web-app>
<display-name>struts_spring_app</display-name>
<welcome-file-list>
<welcome-file>loginform.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>actionServlet</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>actionServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
673
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
loginform.jsp
success.jsp
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
failure.jsp
LoginActionForm.java
1. package com.durgasoft.formbeans;
2.
3. import org.apache.struts.action.ActionForm;
4.
5. public class LoginActionForm extends ActionForm {
6. private String uname;
7. private String upwd;
8.
9. public String getUname() {
675
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
LoginAction.java
1. package com.durgasoft.action;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.apache.struts.action.ActionForm;
7. import org.apache.struts.action.ActionForward;
8. import org.apache.struts.action.ActionMapping;
9. import org.springframework.web.struts.ActionSupport;
10.
11. import com.durgasoft.formbeans.LoginActionForm;
12. import com.durgasoft.service.UserService;
13.
14. public class LoginAction extends ActionSupport {
15.
16.
17.
18. @Override
19. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRe
quest request,
20. HttpServletResponse response) throws Exception {
21. LoginActionForm laf = (LoginActionForm)form;
22. String uname = laf.getUname();
23. String upwd = laf.getUpwd();
24. UserService userService = (UserService) getWebApplicationContext().getBean("user
Service");
676
27. }
28. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.service;
2.
3. public class UserService {
4. String status = "";
5. public String checkLogin(String uname, String upwd) {
6. if(uname.equals("durga") && upwd.equals("durga")) {
7. status = "success";
8. }else {
9. status = "failure";
10. }
11. return status;
12. }
13. }
struts-config.xml
applicationContext.xml
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
antlr-2.7.2.jar
bsf-2.3.0.jar
commons-beanutils-1.8.0.jar
commons-chain-1.2.jar
commons-digester-1.8.jar
commons-fileupload-1.1.1.jar
commons-io-1.1.jar
commons-logging-1.0.4.jar
678
commons-validator-1.3.1.jar
jstl-1.0.2.jar
Page
oro-2.0.8.jar
spring-aop.jar
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
JSF stands for Java Server Faces, it is MVC based web framework, it can be used to
prepare web applications in standard mode.
JSF is MVC based web Framework, it has very good focus on Presentation layer in
enterprise bapplication development.
JSF is initialially provided by JCP[Java Community Process], later on it was given to SUN
Microsystems.
JSF is provided by SUN Microsystems in the form of the following versions.
1. JSF1.X
2. JSF2.X
3. JSf3.X
JSF Features:
JSF is view layered Framework, it has very good focus on view layer in MVC based
679
applications.
JSF is component based framework or Technology, it has very good compnent tag library
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
JSF Components:
To prepare web applications by using JSF then we have to use the following JSF Components.
1. View / Presentation Part
2. Controller or FacesServlet
3. Managed Bean
4. Faces Configuration File
5. Deployment Descriptor or web.xml
In web application , to prepare view part, we will use the technologies like HTML, JSP, Velocity,
Freemarker,......
680
There are two types of View part we are able to use in web applications.
Page
1. Information View
2. Form based View
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where form based view part is able to include user forms to get data from users and to submit
data to server side applications.
In JSF based web applications, to prepare View part we have to use JSF provided tag library.
To prepare View part , JSF has provided the following two types of tags.
1. Core Tags
2. Html Tags
Where core tag library includes the tags which are used for View representations, Conversions,
Validatins,....
EX:
<f:convertNUmber/>
<f:convertDateTime/>
<f:validateLength/>
<f:validateLongRange/>
Where Html tag library include the tags which are repersenting Html Components
EX:
<h:outputText/>
<h:inputText/>
<h:inputSecrete/>
<h:inputTextArea/>
In JSP based web applications, to prepare Usaer form we have to use the following steps.
1. Declare view part by using <f:view> tag.
2. Include Html header part and body part in <f:view> tag.
3. Prepare user form by using <h:form> tag.
4. Prepare Panelgrid by using <h:panelGrid> tag inorder to prepare layout for GUI
component.
5. Prepare html components by using the following html tags.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In JSF based web applications, FacesServlet will get Request from client and it will process the
request by performing the following request processing lifecycle actions.
1. Restore View
2. Apply Request values.
3. Process Validations.
4. Update Model Values.
5. Invoke Application.
6. Render Response.
3. Managed Bean:
In JSF Based web applications, Java Bean class is called as Managed Bean class, it is acting as
model component.
IN JSF Based web application, To prepare Managed Beans, we have to use the following rules
and regulations.
1. Managed Bean class must be a POJO class, it must not be extended and implementd
any predefined library.
2. It will take all properties as per User forms.
3. It will include a seperate set of SetXXX() and getXXX() methods for each and every
property.
4. It will include buisness methods which are bounded with action attribute in
CommandButton in User forms.
682
5. If we want to provide constructor in Managed Bean class then provid constructor, it must
be public and 0- arg.
Page
6. If we want to provide our own comparisions between managed Bean objets then we must
override equals() method
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
1. package com.durgasoft.beans;
2.
3. public class LoginBean {
4. private String uname;
5. private String upwd;
6.
7. public String getUname() {
8. return uname;
9. }
10. public void setUname(String uname) {
11. this.uname = uname;
12. }
13. public String getUpwd() {
14. return upwd;
15. }
16. public void setUpwd(String upwd) {
17. this.upwd = upwd;
18. }
19.
20. public String checkLogin() {
21. if(uname.equals("durga") && upwd.equals("durga")) {
22. return "success";
23. }else {
24. return "failure";
25. }
26. }
27. }
The main intention of Faces Configuration File in JSf is to provide the following configuration
details
1. Managed Beans configuration.
2. Navigations
683
3. Validators
4. Convertors.
Page
In Simple JSF applications, we will provide managed beans configuration and navigations in
Faces Configuration File.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To prepare Faces Configuration file we have to use the following XML tags.
1. <faces-config>
2. <managed-bean>
3. <managed-bean-name> --- </managed-bean-name>
4. <managed-bean-class> --- </managed-bean-class>
5. <managed-bean-scope> --- </managed-bean-scope>
6. </managed-bean>
7. <navigation-rule>
8. <from-view-id>----</from-view-id>
9. <navigation-case>
10. <from-outcome>----</from-outcome>
11. <to-view-id>----</to-view-id>
12. </navigation-case>
13. <navigation-case>
14. <from-outcome>----</from-outcome>
15. <to-view-id>-----</to-view-id>
16. </navigation-case>
17. </navigation-rule>
18. </faces-config>
EX:
684
1. <faces-config>
Page
2. <managed-bean>
3. <managed-bean-name>loginBean</managed-bean-name>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In general, in web applications, deployement descriptor is web.xml file, it able to provide the
following configuration details.
1. Welcome Files configuration.
2. Display Names Configuration.
3. Servlets Configuration.
4. Filters configuration.
5. Listeers Configurations.
6. Initialization parameters configuration.
7. Context Parameters Configurations.
In JSF based web applications, we have to provide FacesServlet configuration with load-on-
startup configuration and we must provide url pattern for FacesServlet i either of the following
forms.
/faces/*
*.jsf
*.faces
Example:
1. web-app>
2. <servlet>
685
3. <servlet-name>facesServlet</servlet-name>
4. <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
Page
5. <load-on-startup>1</load-on-startup>
6. </servlet>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
index.jsp
loginform.jsp
16.
17. <h:outputText value="Password"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
success.jsp
failure.jsp
10. <br><br>
11. <h1 style="color: red;" align="center">Login Failure</h1>
Page
12. </body>
13. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.beans;
2.
3. public class LoginBean {
4. private String uname;
5. private String upwd;
6.
7. public String getUname() {
8. return uname;
9. }
10. public void setUname(String uname) {
11. this.uname = uname;
12. }
13. public String getUpwd() {
14. return upwd;
15. }
16. public void setUpwd(String upwd) {
17. this.upwd = upwd;
18. }
19.
20. public String checkLogin() {
21. if(uname.equals("durga") && upwd.equals("durga")) {
22. return "success";
23. }else {
24. return "failure";
25. }
26. }
27. }
faces-config.xml
7. version="1.2">
8. <managed-bean>
Page
9. <managed-bean-name>loginBean</managed-bean-name>
10. <managed-bean-class>com.durgasoft.beans.LoginBean</managed-bean-class>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
If we want to integrate JSF with Spring Framework then we have to use the following steps.
1. Prepare Presentation part as per JSF Conventions.
2. Prepare Spring Beans and spring configuration file as per Spring Conventions
3. Add Dependent Spring Service Bean to Managed Bean of JSF in faces-config.xml
EX:
689
1. <faces-config>
Page
2. ------
3. <managed-bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: The main intention providing Spring Service Bean in faces-config.xml file is to inject Service
bean in Jsf Managed Bean inorder to access Business methods.
1. <faces-config>
2. -----
3. <application>
4. <el-resolver>
5. org.springframework.web.jsf.el.SpringBeanFacesELResolver
6. </el-resolver>
7. </application>
8. </faces-config>
Note: SpringBeanFacesResolver first delegates value lookups to the default resolver of the JSF
and then to Spring's WebApplicationContext. This allows to inject springbased dependencies into
JSF-managed beans.
5. Provide ContextLoaderListener and RequestContextListener in web.xml file
EX:
web.xml
1. <web-app>
2. -------
3. <listener>
4. <listener-class>
5. org.springframework.web.context.ContextLoaderListener
6. </listener-class>
7. </listener>
690
8.
9. <listener>
Page
10. <listener-class>
11. org.springframework.web.context.request.RequestContextListener
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: These Listeners are used to load the complete Spring context at the time of Startup the
Server.
Example:
index.jsp
loginform.jsp
12. <center>
13. <h:panelGrid columns="2" >
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
success.jsp
failure.jsp
8. </head>
9. <body>
Page
10. <br><br>
11. <h1 style="color: red;" align="center">Login Failure</h1>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
LoginBean.java
1. package com.durgasoft.beans;
2.
3. import com.durgasoft.service.UserService;
4.
5. public class LoginBean {
6. private String uname;
7. private String upwd;
8. private UserService userService;
9.
10. public String getUname() {
11. return uname;
12. }
13. public void setUname(String uname) {
14. this.uname = uname;
15. }
16. public String getUpwd() {
17. return upwd;
18. }
19. public void setUpwd(String upwd) {
20. this.upwd = upwd;
21. }
22.
23. public void setUserService(UserService userService) {
24. this.userService = userService;
25. }
26. public UserService getUserService() {
27. return userService;
28. }
29.
30. public String login() {
31. return userService.checkLogin(uname, upwd);
32. }
33. }
693
UserService.java
Page
1. package com.durgasoft.service;
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
applicationContext.xml
faces-config.xml
14. <managed-bean-name>loginBean</managed-bean-name>
15. <managed-bean-class>com.durgasoft.beans.LoginBean</managed-bean-class>
Page
16. <managed-bean-scope>session</managed-bean-scope>
17. <managed-property>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
18.
19. <!-- Add Support for Spring -->
Page
20. <listener>
21. <listener-class>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
SF Jars:
jsf1.2\jsf-api.jar
jsf-impl.jar
taglibs-standard-impl-1.2.5.jar
taglibs-standard-spec-1.2.5.jar
Spring JARs:
spring-aop-4.3.9.RELEASE.jar
spring-beans-4.3.9.RELEASE.jar
spring-context-4.3.9.RELEASE.jar
spring-context-support-4.3.9.RELEASE.jar
spring-core-4.3.9.RELEASE.jar
spring-expression-4.3.9.RELEASE.jar
commons-logiin-1.2.jar
696
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
MAVEN
COURSE MATERIAL
BY
NAGOOR BABU
697
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
698
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Index
1. Introduction………………………………………………………………….Page 700
2. Project Object Model……………………………………………………….Page 701
3. Archetypes in MAVEN………………………………………….…………..Page 713
4. Steps to prepare MAVEN Project in Eclipse……………………………..Page 716
5. Web Application in Maven………………………………………………….Page 728
6. Spring Core Module Application in MAVEN………………...……………Page 736
699
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
MAVEN
Introduction
MAVEN follows "Convention over Configuration" Principle, which means that developers are not
required to create build process themselves, Developers do not have to mention each and
every configuration detail. Maven provides sensible default behavior for projects.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In pom file, initial we will identify "Projection Description", it contains Project name, version
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2) Repository:
702
If we use Dependencies in MAVEN Project then MAVEN will search for the dependent JARs in
Repositories.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Local Repository:
It is a location to manage and supply all dependencies, it will be created by MAVEN when we
execute any MAVEN command first time.
2. Central Repository:
In MAVEN applications, if we want to use the above explict repositories then we have to configure
them in pom file by using the following xml tags.
1. <repositories>
2. <repository>
3. <id>jboss</id>
4. <name>jboss repo</name>
5. <url>http://repository.jboss.org/nexus/content/groups/public/</url>
6. </repository>
7. </repositories>
3. Remote Repository:
In some Situations, Maven does not find the dependencies in Local Repository and in central
repository, in this context, MAVEN stops the build process and generates some Exceptions. To
overcome this problems, Maven has provided a new Features like "Remote Repository".
Remote Repository is a developer's own custom repository containing required libraries or other
project jars.
To configure Remote Repository, we have to use the following XML tags in pom.xml file.
703
1. <repositories>
2. <repository>
Page
3. <id>durgasoft.lib</id>
4. <url>http://library.durgasoft.com/maven2/lib</url>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
When we run MAVEN project then MAVEN will search for the dependencies in the following order.
1) First, MAVEN will search for the dependencies in local repository, if the required
dependencies are available at Local Repository the MAVEN will use them in application. If
the dependencies are not available at Local Repository then MAVEN search for them at
Central Repository.
2) If the required Dependencies are existed in central repository then MAVEN will load them
into Local Repository and MAVEN will use them in the applications. If the required
dependencies are not existed in Central Repository then MAVEN will search for them in
Remote Repositories as per configuration.
3) If Remote Repository is not configured then MAVEN will stop the application execution and
generated some Exceptions.
4) If Remote Repository is configured then MAVEN will search for the required dependencies
in Remote Repository, if they are identified then MAVEN will load them into Local
Repository for futur reference. If the dependencies are not existed at Remote Repositories
then MAVEN will stop the execution and generate some Exceptions.
704
3) Dependency Management:
In Applications, Dependencies are the libraries[Collection of JARs] which are required to compile,
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The main Advantage of MAVEN in applications development is that not to store any Dependent
JAR files in Project Directory Structer by downloading them explicitly, MAVEN has given flexibility
to the developers like to specify dependent JAR files names in pom file, where MAVEN will search
for them in the repositories and MAVEN will load them into the project directory structer
automatically.
If we need any Library in MAVEN based applications then we have to declare them in pom file like
below.
1. <dependencies>
2. <dependency>
3. <groupId>org.hibernate</groupId>
4. <artifactId>hibernate-core</artifactId>
5. <version>3.5.6-Final</version>
6. <scope>provided</scope>
7. </dependency>
8. </dependencies>
If we provide the dependency like above then MAVEN will search for the hibernate library with the
name like
http://repo1.maven.org/maven2/org/hibernate/hibernate-core/3.5.6-Final/
MAVEN is following "Transitive Dependencies Mechanism", that is, if our dependencies are
required any other libraries then MAVEN will get them automatically without loading them explicitly
by the developers.
Dependency Scopes:
In Applications, some dependencies are required to all phases of the project lifecycle like compile,
test, run,... and some other required only some of phases of the project lifecycle.
In order to limit the dependencies for the lifecycle phases we will use Dependency Scopes.
2. Provided
3. Runtime
Page
4. Test
5. System
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Compile:
It is the default scope in MAVEN . This scope will make the dependencies to avail all phases like
compile, test, run,....
EX:
<dependency>
1. <groupId>org.hibernate</groupId>
2. <artifactId>hibernate-core</artifactId>
3. <version>3.5.6-Final</version>
4. <scope>compile</scope>
5. </dependency>
Note: In general, hibernate-core library is required for all phases of the application.
2. Provided:
This scope will make the dependency libraries to avail upto compilation and and upto testinbg, not
for runtime, because, at runtime, JDKs or Containers will provide the required dependencies at
runtime.
EX:
In web applications, Servlet API is required expliclty to compile and test the project, but, Servlet
API is provided by the container at runtime automatically, so that, they are not required to be
exported at runtime.
1. <dependency>
2. <groupId>javax.servlet</groupId>
3. <artifactId>servlet-api</artifactId>
4. <version>3.0.1</version>
5. <scope>provided</scope>
6. </dependency>
3. Runtime:
This scope indicates that the dependency is not required for compilation, but is for execution. It is
706
in the runtime and test class paths, but not the compile class path.
EX:
Page
1. <dependency>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4. Test:
This scope indicates that the dependency is not required for normal use of the application, and is
only available for the test compilation and execution phases. This scope is not transitive.
EX:
1. <dependency>
2. <groupId>junit</groupId>
3. <artifactId>junit</artifactId>
4. <version>4.12</version>
5. <scope>test</scope>
6. </dependency>
5. System:
Dependencies with system are similar to ones with scope provided. The only difference is system
dependencies are not retrieved from remote repository. They are present under project‘s
subdirectory and are referred from there.
EX:
1. <dependency>
2. <groupId>Explicit_Dependency</groupId>
3. <artifactId>Explicit_Dependency</artifactId>
4. <scope>system</scope>
5. <version>1.0</version>
6. <systemPath>apps\app.war\WEB-INF\lib\Explicit_Dependency.jar</systemPath>
7. </dependency>
6. Import:
It is available in Maven 2.0.9 or later.
Import scope is only supported on a dependency of type pom in the dependencyManagement
section. It indicates the dependency to be replaced with the effective list of dependencies in the
707
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <dependencyManagement>
2. <dependencies>
3. <dependency>
4. <groupId>other.pom.group.id</groupId>
5. <artifactId>other-pom-artifact-id</artifactId>
6. <version>SNAPSHOT</version>
7. <scope>import</scope>
8. <type>pom</type>
9. </dependency>
10. </dependencies>
11. </dependencyManagement>
4) Project Inheritance:
In MAVEN based applications, it is possible to inherit configurations from one pom file to another
pom file inorder to avoid configurations redundency.
To declare parent pom , we have to use "pom" as value to <packaging> tag in parent pom file.
EX:
If we want to inherit parent pom configuration details into a particular chaild pom then we have to
configure parent pom in chaild pom.
EX:
4. <groupId>com.durgasoft</groupId>
5. <artifactId>my-parent</artifactId>
Page
6. <version>0.0.1-SNAPSHOT</version>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: In JAVA, java.lang.Object class is common and default super class for every java class
inorder to provide 11 common and default methods to each and every java class, similarily , there
is a common and default super pom file is existed in maven inorder to provide all common
configurations and settings to the chaild pom file.
Note: By default, Maven looks for the parent POM first at project‘s root, then the local repository,
and lastly in the remote repository. If parent POM file is not located in any other place, then you
can use code tag. This relative path shall be relative to project root.
EX:
1. <parent>
2. <groupId>com.durgasoft</groupId>
3. <artifactId>MavenExamples</artifactId>
4. <version>0.0.1-SNAPSHOT</version>
5. <relativePath>../baseapp/pom.xml</relativePath>
6. </parent>
Note: If we want to get super pom from MAVEN then use the following command on command
prompt from the project root location which contains project specific pom file.
mvn help:effective-pom
5) Build Configuration:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1.Build Plugins: These plugins are executed during the build and they should be configured in
the <build/> element from the POM.
EX
2. Reporting plugins: These plugins are executed during the site generation and they should be
configured in the <reporting/> element from the POM.
EX:
1.changelog: Generate a list of recent changes from your SCM[Software Configuration
Management].
2.changes: Generate a report from an issue tracker or a change document.
3.javadoc: Generate Javadoc for the project.
4.project-info-resports: Generate standard project reports.
5.surfire-report: Generate a report based on the results of unit tests.
710
IN general, we will use MAVEN compiler plugin inorder to perform Compilation, for this we have to
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
By default, all files placed in "src\main\config" are packaged into the generated project artifact and
any file which we placed in "src\test\resources" are available in project classpath during unit tests.
If we want to provide our own customized resources location in project then we have to configure
them in pom.xml file under <build> tag like below.
1. <build>
2. ----
3. <resources>
4. <resource>
5. <directory>src/main/config</directory</directory>
6. </resource>
7. <resource>
8. <directory>src/main/resources</directory</directory>
9. </resource>
10. ----
11. </resources>
12. ----
13. </build>
6) Build Profiles:
IN general, profiles are used to customize the build lifecycle for different environments like
development, testing, production,.....
711
Example:
Page
1. <profiles>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where each and every profile has its own id, it can be used to access the respective environment
or profile.
In src/main/resources/db.properties
jdbc.connection.url = ${jdbc.connection.url}
If we provide the above setups like above then at compilation time, the respective jdbc URL will be
injected to the "jdbc.connection.url" property depending on the target environment.
Use the following command on command prompt inorder to compile the project.
C:/apps>mvn compile
Here "jdbc.connection.profile" property will take "jdbc:oracle:thin:@localhost:1521:xe" value.
If we provide the above setups like above then at compilation time, the respective jdbc URL will be
injected to the "jdbc.connection.url" property depending on the target environment.
Use the following command on command prompt inorder to compile the project.
C:/apps>mvn compile
Here "jdbc.connection.profile" property will take "jdbc:oracle:thin:@localhost:1521:xe" value.
712
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To create sample MAVEN standalone application directory structer we will use the following
command on command prompt .
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we do the above steps then MAVEN will create quick start project with the following directories
and files.
E:/mvn_projects
Sampleapp
|--src
| |---main
| | |----java
| | |---com
| | |---durgasoft
| | |----App.java
| |---test
| |----java
| |---com
| |----durgasoft
| |-----AppTest.java
|---pom.xml
App.java
1. package com.durgasoft;
2.
3. /**
4. * Hello world!
714
5. *
6. */
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
AppTest.java
1. package com.durgasoft;
2.
3. import static org.junit.Assert.assertTrue;
4.
5. import org.junit.Test;
6.
7. /**
8. * Unit test for simple App.
9. */
10. public class AppTest
11. {
12. /**
13. * Rigorous Test :-)
14. */
15. @Test
16. public void shouldAnswerWithTrue()
17. {
18. System.out.println("Welcome To Durgasoft");
19. assertTrue( true );
20. }
21. }
To Compile JAVA code, first, goto application folder then use the following command on
command prompt.
E:\mvn_projects\sampleapp>mvn compile
If we use the above command then MAVEN will compile JAVA files and generates the .class files
715
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
E:\mvn_projects\sampleapp>mvn test
c) version: 0.0.1-SNAPSHOT
d) package: com.durgasoft
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
33. <target>1.8</target>
34. </configuration>
Page
35. </plugin>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
src/test/java/AppTest.java
1. package com.durgasoft;
2. import junit.framework.Test;
3. import junit.framework.TestCase;
4. import junit.framework.TestSuite;
5. public class AppTest extends TestCase
6. {
7. public AppTest( String testName )
8. {
9. super( testName );
10. }
11. public static Test suite()
12. {
13. return new TestSuite( AppTest.class );
14. }
15. public void testApp()
16. {
17. System.out.println("Hello Maven!");
18. assertTrue( true );
19. }
20. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To prepare JDBC Application with MAVEN then we have to use the following steps with all the
above steps.
1. <dependencies>
2. <dependency>
3. <groupId>oracle</groupId>
4. <artifactId>oracle-jdbc</artifactId>
5. <version>11.2.0-XE</version>
6. <scope>runtime</scope>
7. </dependency>
8. </dependencies>
EX:
├───src
│ ├───main
│ │ └───java
│ │ └───com
│ │ └───durgasoft
| | |----App.java
| | |----JdbcApp.java
719
│ └───test
│ └───java
│ └───com
Page
│ └───durgasoft
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
pom.xml
33. <plugin>
34. <groupId>org.apache.maven.plugins</groupId>
Page
35. <artifactId>maven-compiler-plugin</artifactId>
36. <version>3.7.0</version>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
JdbcApp.java
1. package com.durgasoft;
2.
3. import java.sql.Connection;
4. import java.sql.DriverManager;
5. import java.sql.ResultSet;
6. import java.sql.Statement;
7.
8. public class JdbcApp {
9. Connection con;
10. Statement st;
11. ResultSet rs;
12. public JdbcApp() {
13. try {
14. Class.forName("oracle.jdbc.OracleDriver");
15. con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system
", "durga");
16. st = con.createStatement();
17. } catch (Exception e) {
18. e.printStackTrace();
19. }
20. }
21. public void displayEmpDetails() {
22. try {
23. rs = st.executeQuery("select * from emp1");
24. System.out.println("ENO\tENAME\tESAL\tEADDR");
25. System.out.println("------------------------------");
26. while(rs.next()) {
27. System.out.print(rs.getInt(1)+"\t");
721
28. System.out.print(rs.getString(2)+"\t");
29. System.out.print(rs.getFloat(3)+"\t");
Page
30. System.out.println(rs.getString(4));
31. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
AppTest.java
1. package com.durgasoft;
2.
3. import java.sql.Connection;
4. import java.sql.DriverManager;
5. import java.sql.ResultSet;
6. import java.sql.Statement;
7.
8. import junit.framework.Test;
9. import junit.framework.TestCase;
10. import junit.framework.TestSuite;
11.
12. /**
13. * Unit test for simple App.
14. */
15. public class AppTest
16. extends TestCase
17. {
18. /**
19. * Create the test case
20. *
21. * @param testName name of the test case
22. */
23. public AppTest( String testName )
24. {
25. super( testName );
26. }
27.
28. /**
29. * @return the suite of tests being tested
30. */
31. public static Test suite()
722
32. {
33. return new TestSuite( AppTest.class );
Page
34. }
35.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to use MySQL Database in Our project then we have to use the following dependency
in pom file.
1. <dependency>
2. <groupId>mysql</groupId>
3. <artifactId>mysql-connector-java</artifactId>
4. <version>8.0.11</version>
5. </dependency>
In Java Application
Driver Class: com.mysql.cj.jdbc.Driver
Driver UIRL: jdbc:mysql://localhost:3306/durgadb
DB User Name: root
DB Password : root
Example:
pom.xml
8. <packaging>jar</packaging>
9.
Page
10. <name>helloapp</name>
11. <url>http://maven.apache.org</url>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
51. </plugins>
52. </build>
Page
53. </project>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft;
2.
3. import java.sql.Connection;
4. import java.sql.DriverManager;
5. import java.sql.ResultSet;
6. import java.sql.Statement;
7.
8. public class JdbcApp {
9. Connection con;
10. Statement st;
11. ResultSet rs;
12. public JdbcApp() {
13. try {
14. Class.forName("com.mysql.jdbc.Driver");
15. con = DriverManager.getConnection("jdbc:mysql://localhost:3300/durgadb", "root", "
root");
16. st = con.createStatement();
17. } catch (Exception e) {
18. e.printStackTrace();
19. }
20. }
21. public void displayEmpDetails() {
22. try {
23. rs = st.executeQuery("select * from emp1");
24. System.out.println("ENO\tENAME\tESAL\tEADDR");
25. System.out.println("------------------------------");
26. while(rs.next()) {
27. System.out.print(rs.getInt(1)+"\t");
28. System.out.print(rs.getString(2)+"\t");
29. System.out.print(rs.getFloat(3)+"\t");
30. System.out.println(rs.getString(4));
31. }
32. } catch (Exception e) {
33. e.printStackTrace();
34. }
35. }
36. }
725
AppTest.java
Page
1. package com.durgasoft;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
43. jdbcApp.displayEmpDetails();
44. /*
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
727
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <plugin>
2. <groupId>org.apache.maven.plugins</groupId>
3. <artifactId>maven-compiler-plugin</artifactId>
4. <version>3.7.0</version>
5. <configuration>
6. <source>1.8</source>
728
7. <target>1.8</target>
8. </configuration>
9. </plugin>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <plugin>
2. <groupId>org.apache.tomcat.maven</groupId>
3. <artifactId>tomcat7-maven-plugin</artifactId>
4. <version>2.2</version>
5. </plugin>
1. <dependency>
2. <groupId>javax.servlet</groupId>
3. <artifactId>javax.servlet-api</artifactId>
4. <version>3.1.0</version>
5. <scope>provided</scope>
6. </dependency>
EX: pom.xml
7. <version>0.0.1-SNAPSHOT</version>
8. <name>loginapp Maven Webapp</name>
Page
9. <url>http://maven.apache.org</url>
10. <dependencies>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX: loginform.html
1. <html>
2. <body>
3. <form action="./hello" method="post">
4. User Name<input type="text" name="uname"/><br>
5. Password<input type="password" name="upwd"/><br>
6. <input type="submit" value="Login"/>
7. </form>
8. </body>
9. </html>
10.
11. success.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h1>Durga Software Solutions</h1>
9. <h2>User Login Status</h2>
10. <font color="red" size="7">User Login Success</font>
11. <h3>
12. <a href="./loginform.html">|User Login Form|</a>
13. </h3>
14. </body>
15. </html>
16.
17. failure.html
731
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
b) Prepare Servlets:
EX: LoginServlet.java
732
1. package com.durgasoft.servlets;
Page
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
7. <servlet>
8. <servlet-name>LoginServlet</servlet-name>
Page
9. <display-name>LoginServlet</display-name>
10. <description></description>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:UserService.java
1. package com.durgasoft.service;
2.
3. import java.sql.Connection;
4. import java.sql.DriverManager;
5. import java.sql.ResultSet;
6. import java.sql.Statement;
7.
8. public class UserService {
9. Connection con;
10. Statement st;
11. ResultSet rs;
12. String status = "";
13. public UserService() {
14. try {
15. Class.forName("oracle.jdbc.OracleDriver");
734
17. st = con.createStatement();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4. Update Project:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
1. <build>
2. <plugins>
3. <plugin>
4. <groupId>org.apache.maven.plugins</groupId>
5. <artifactId>maven-compiler-plugin</artifactId>
736
6. <version>3.7.0</version>
7. <configuration>
8. <source>1.8</source>
Page
9. <target>1.8</target>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
1. <dependencies>
2. <dependency>
3. <groupId>org.springframework</groupId>
4. <artifactId>spring-core</artifactId>
5. <version>4.3.18.RELEASE</version>
6. </dependency>
7.
8. <dependency>
9. <groupId>org.springframework</groupId>
10. <artifactId>spring-context</artifactId>
11. <version>4.3.18.RELEASE</version>
12. </dependency>
13.
14. <dependency>
15. <groupId>org.springframework</groupId>
16. <artifactId>spring-aop</artifactId>
17. <version>4.3.18.RELEASE</version>
18. </dependency>
19. </dependencies>
Note: In the above dependencies, just add spring-core and spring-context dependencies in
pom.xml file then automatically all other dependencies are also be loaded.
EX: pom.xml
3. <modelVersion>4.0.0</modelVersion>
4.
5. <groupId>com.durgasoft</groupId>
Page
6. <artifactId>springapp1</artifactId>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
46. <groupId>org.apache.maven.plugins</groupId>
47. <artifactId>maven-compiler-plugin</artifactId>
Page
48. <version>3.7.0</version>
49. <configuration>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX: HelloBean.java
1. package com.durgasoft.beans;
2.
3. public class HelloBean {
4. public String sayHello() {
5. return "Hello User!";
6. }
7. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX: applicationContext.xml
EX:TestClient.java
1. package com.durgasoft.test;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5.
6. import com.durgasoft.beans.HelloBean;
7.
740
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:TestApp.java
1. package com.durgasoft;
2. import com.durgasoft.test.TestClient;
3. import junit.framework.Test;
4. import junit.framework.TestCase;
5. import junit.framework.TestSuite;
6. public class AppTest
7. extends TestCase
8. {
9. public AppTest( String testName )
10. {
11. super( testName );
12. }
13.
14. public static Test suite()
15. {
16. return new TestSuite( AppTest.class );
17. }
18.
19. public void testApp()
20. {
21. TestClient client = new TestClient();
22. client.test();
23.
24. assertTrue( true );
25. }
26. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
LOG4J
COURSE MATERIAL
BY
NAGOOR BABU
742
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
743
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
744
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
1. class Transaction{
2. void deposit(){
3. System.out.println("logic for deposit");
4. }
5. void withdraw(){
6. System.out.println("logic for withdraw");
7. }
8. void transfer(){
9. System.out.println("logic for transfer");
10. }
11. }
12. class Test{
13. Transaction tx = new Transaction();
14. System.out.println("Before deposit() method call");
15. tx.deposit()
16. System.out.println("After deposit() method call");
17. -----
18. System.out.println("Before withdraw() method call");
19. tx.withdraw();
20. System.out.println("After withdraw method call");
21. ------
22. System.out.println("Before transfer() method call");
23. tx.transfer();
24. System.out.println("After transfer() method call");
25. }
If we execute the above application then we are able to get the following output on console or
command prompt.
Before deposit() method call
logic for deposit
745
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we use System.out.println() method in applications to trace flow of execution then we are able to
get the following problems.
1. System.out.println(--) will be used for only console display, not for sending data to any other
output systems like file systems[html files, xml files, text files...], databases, network,....
2. System.out.println() method contains synchronized block to display data, it is heavy weight,
expensive and time consuming.
3. In Applications, it is not suggestible to write too many no of System.out.println() methods in
applications, because, it will reduce application performance.
4. System.out.println() method is usefull in Development environment only, It is not suitable in
production environment , because, if we use System.out.println() method in server side
applications then it will display messages in servers console only, it will not be avaiable to
users.
5. System.out.println() will display the messages on console or on command prompt, it will not
show differences in Error messages, warning messaages, normal information,....
6. System.out.println() is suitable for simple standalone applications, not for complex
enterprise applications.
To overcome all the problems while tracing applications we have to use Logging.
Logging : It is the process of writing log messages during the execution of a program to a central
place. This logging allows you to report and persist error and warning messages as well as info
messages so that the messages can later be retrieved and analyzed.
Logging Framework: It is a set of classes and interfaces or a product to perform Logging in Java
applications.
EX:
2. Log4j
3. LogBack
Page
4. Commons Logging
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2. Quick Debugging: Once if we diagnose the problem and if we identify the location of the
problem by using logging framework then it is very simple to fix that problem and it simplifies
Debugging and it able to reduce overall Debugging time.
4. History: In general, all Logging Frameworks are tracing the applications flow of execution and
they are able to store tracing details in a file system, this logging details are usefull to analyze the
problems and to solve the problems.
5. Cost and Time Saving: Logging Frameworks will simplifies debugging, easy maintenance ,
persisting application information,..... , these qualities of Logging Framework saves time and cost
of the application.
1. Logging Frameworks needs to write some extra code in our java applications, it will
increase overhead to the application.
2. Logging Frameworks will provide some extra code in our applications, it will increase
application execution time at runtime, it will reduce application performance.
3. Logging Framework will provide some extra code in application, so that, it will increase
application length.
4. Poor logging strategies will increase confusion to the developers.
747
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Log4j Features:
Log4j is able to allow more than one thread at a time with out providing data inconsistency
,so that, Log4j is thread-safe.
Log4j will not slow down the application execution, it will be optimized to improve
application performance.
Log4j is providing environment to send logging messages to more than one output
appenders .
Log4j supports internationalization.
Log4j is providing services for both predefined and user defined facilities, it able to provide
some customizations also.
Log4j allows to set logging behaviours at runtime through the configuration file.
Log4j is providing very good environment to traace Exceptions from its root.
Log4j uses multiple levels like ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL to
generate messages.
Log4j allows to change the format of log output by extending Layout class.
Log4j is using appenders to generate log messages.
Log4j Architecture:
748
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Logger:
This Object is responsibile to get logging messages from Java applications
2. Appender:
The main intention of Appender object is to get logging messages from Logger object and
publishing that logging messages to the preffered destinations. Each and Every Appender Object
must have atleast one Destination object inorder to send logging messages.
3. Layout:
The main intention of Layout object is to format logging messages in different styles.Layout Object
is used by Appender object just before publishing Logging Messages.
4. Level:
The main intention of Level object is to define granualarity and priority of any Logging information.
Each and every Logging information must be with a particular Logging Level.
Log4j API has provided the following Levels to the Logging messages.
1. ALL
2. TRACE
3. DEBUG
4. ENFO
5. WRAN
6. ERROR
7. FATAL
8. OFF
Log4j is giving priorities for the logging messages in the following order.
749
ALL >TRACE > DEBUGG > INFO > WARN > ERROR > FATAL>OFF
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
7. Filter:
The main intention of Filter object is used to analyze logging information and takes the decision
whther the messages must be logged or not.
An Appender object may have no of Filter objects, they must approve our logging message before
publishing logging messages in destination.
8.ObjectRender
This Object will be used by Layout object in order to get string representation of the several
objects which are passed through Log4j framework.
750
1. If we create Logger object in Java application then a request will be send to Log4j Software
about to create Logger object.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Log4j , we are able to use the following two types of configuration files.
1.log4j.properties
2.log4j.xml
IN both the configuratin files, we have to use the following configurations at basic java
applications.
EX: log4j.properties:
Where "log4j.rootLogger" property will take Logging LEVEL and appender name,
where Log4j framework will display all the messages which are same as the specified Log
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: Where %m%n in the sense, %m is to display message and %n is to bring cursor to next
line.
log4j.xml Configuration:
In XML confioguration we have to use the following configuration.
1. Appender configuration.
2. Layout Configuration
3. Root Logger COnfiguration
To provide XML configuration then we have to use the following xml tags in log4j.xml file.
log4j.xml
10. </appender>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where <log4j:configuration> isa a root tag, it able to take log4j configuration details.
Where <appender> tag is able to configure Appender class with a logical name.
Where "name" attribute in <appender> tag will take logical name to the appender.
Where "class" attribute in <appender> tag is able to take fully qualified name of the
Appender class, that is, "org.apache.log4j.ConsoleAppender"
Where <layout> tag can be used to configure Layout class.
Where "class" attribute in <layout> tag will take fully qualified name of Layout class, that is,
"org.apache.log4j.PatternLayout".
Where <param> tag in <layout> tag will take layout parameter .
Where "name" attribute will take parameter name, tyhat is , "ConversionPattern".
Where "value" attribute will take value of the parameter , that is, %d{DD/MM/YYYY
HH:mm:SS} %-5p %c{1} - %m%n
Where <root> tag will provide rootLogger configuration.
Where <priority> tag tag will take logger level with "value" attribute.
Where <appender-ref> tag will take logical name of the appender with "ref" attribute.
Example:
log4j.properties
log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } : This is
%m%n
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package log4japp1;
2.
3. import org.apache.log4j.LogManager;
4. import org.apache.log4j.Logger;
5.
6. public class Log4jTest {
7.
8. public static void main(String[] args) {
9. Logger logger = LogManager.getLogger(Log4jTest.class);
10. logger.trace("trace Message");
11. logger.debug("debug Message");
12. logger.info("info Message");
13. logger.warn("warn Message");
14. logger.error("Error Message");
15. logger.fatal("fatal Message");
16.
17. }
18. }
Note: If we want to use XML configuration then we have to use the following XML file
log4j.xml
15. </root>
16.
Page
17. </log4j:configuration>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Appender is an object, it can be used to get logging messages from Logger object and publishing
that logging messages to the preffered destinations. Each and Every Appender Object must have
atleast one Destination object inorder to send logging messages.
Log4j has provided the following appenders inorder to publish logging messages.
1. ConsoleAppender
2. FileAppender
3. JDBCAppender
4. JMSAppender
5. SocketAppender
6. SMTPAppender
7. AsyncAppender
8. AppenderSkeleton
9. DailyRollingFileAppender
10. ExternallyRolledFileAppender
11. LF5Appender
12. NTEventLogAppender
13. NullAppender
14. RollingFileAppender
15. SocketHubAppender
16. SyslogAppender
17. TelnetAppender
18. WriterAppender
If we want to manage all logging messages in a File then we have to use FileAppenders.
1. FileAppender
2. RollingFileAppender
3. DailyRollingFileAppender
4. ExternallyRolledFileAppender
755
1. FileAppender:
If we want to use FileAppender in Java applications then we have to use the following properties
Page
in log4j.properties file.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. log4j.rootLogger
2. log4j.appender.Ref_Name
3. log4j.appender.Ref_Name.File : It will name and location of the file to manage logging
messages.
4. log4j.appender.Ref_Name.layout
5. log4j.appender.Ref_Name.layout.ConversionProperty
EX:
log4j.properties
Log4jTest.java
1. package log4japp1;
2.
3. import org.apache.log4j.LogManager;
4. import org.apache.log4j.Logger;
5.
6. public class Log4jTest {
7.
8. public static void main(String[] args) {
9.
10. Logger logger = LogManager.getLogger(Log4jTest.class);
11. logger.trace("trace Message");
12. logger.debug("debug Message");
13. logger.info("info Message");
14. logger.warn("warn Message");
15. logger.error("Error Message");
16. logger.fatal("fatal Message");
17.
18. }
756
19. }
Page
If we want to use both ConsoleAppender and FileAppender in Java Applications then we have to
define two Ref_Names at 'log4j.rootLogger' property.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
log4j.properties
#ConsoleAppender Configuration
log4j.appender.CONSOLE = org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } %-c %p
: This is %m%n
#FileAppender Configuration
log4j.appender.FILE = org.apache.log4j.FileAppender
log4j.appender.FILE.File=./logging/logs.log
log4j.appender.FILE.layout = org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } %-c %p :
This is %m%n
Log4jTest.java
1. package log4japp1;
2.
3. import org.apache.log4j.LogManager;
4. import org.apache.log4j.Logger;
5.
6. public class Log4jTest {
7.
8. public static void main(String[] args) {
9.
10. Logger logger = LogManager.getLogger(Log4jTest.class);
11. logger.trace("trace Message");
12. logger.debug("debug Message");
13. logger.info("info Message");
14. logger.warn("warn Message");
15. logger.error("Error Message");
16. logger.fatal("fatal Message");
757
17.
18. }
Page
19. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
log4j.properties
#FileAppender Configuration
log4j.appender.FILE = org.apache.log4j.RollingFileAppender
log4j.appender.FILE.file= e:/loggers/logs.txt
log4j.appender.FILE.MaxFileSize= 2kb
log4j.appender.FILE.MaxBackupIndex= 3
log4j.appender.FILE.layout = org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } %-c %p :
This is %m%n
Log4jTest.java
1. package log4japp1;
2.
3. import org.apache.log4j.LogManager;
4. import org.apache.log4j.Logger;
5.
6. public class Log4jTest {
7. static Logger logger = LogManager.getLogger(Log4jTest.class);
8. public static void main(String[] args) {
9.
10. logger.trace("trace Message");
758
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. DailyRollingFileAppender
The main intention of DailyRollingFileAppender is to roll files in FileAppender on daily basis.
Note: The default pattern for datePattern property is '.' '.' yyyy-MM-dd , it will roll over every day
midnight
Example:
log4j.properties
#FileAppender Configuration
log4j.appender.FILE = org.apache.log4j.DailyRollingFileAppender
log4j.appender.FILE.file= e:/loggers/logs.txt
log4j.appender.FILE.DatePattern='.' yyyy-MM-dd-HH-mm
#log4j.appender.FILE.MaxFileSize= 2kb
#log4j.appender.FILE.MaxBackupIndex= 3
759
log4j.appender.FILE.layout = org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } %-c %p :
Page
This is %m%n
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package log4japp1;
2.
3. import org.apache.log4j.LogManager;
4. import org.apache.log4j.Logger;
5.
6. public class Log4jTest {
7. static Logger logger = LogManager.getLogger(Log4jTest.class);
8. public static void main(String[] args) {
9.
10.
11. logger.trace("trace Message");
12. logger.debug("debug Message");
13. logger.info("info Message");
14. logger.warn("warn Message");
15. logger.error("Error Message");
16. logger.fatal("fatal Message");
17.
18. }
19. }
4. ExternallyRolledFileAppender:
This appender listens on a socket on the port specified by the Port property for a "RollOver"
message. When such a message is received, the underlying log file is rolled over and an
acknowledgment message is sent back to the process initiating the roll over.
760
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The main intention of Layout is to define a partidular Structer for the logging messages.
1. Simple Layout:
SimpleLayout is able to prepare logging messages with "LEVEL - Log_Message" . Log4j has
provided a predefiend class to represent Simple Layout,that is, org.apache.log4j.SimpleLayout
EX:
log4j.properties
Test.java
1. package com.durgasoft.log4j;
2. import org.apache.log4j.LogManager;
3. import org.apache.log4j.Logger;
4.
5. public class Log4jTest {
6. static Logger logger = LogManager.getLogger(Log4jTest.class);
7. public static void main(String[] args) {
8. logger.trace("Trace Message");
9. logger.debug("Debug Message");
10. logger.info("Info Message");
11. logger.warn("Warn Message");
761
15. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
OP:
2. Pattern Layout:
It able to prepare logging messages w.r.t the provided pattern. To represent Pattern Layout, Log4j
has provided a predefined class in the form of "org.apache.log4j.PatternLayout".
To define pattern for the logging messages, we must use "ConversionPattern" property from
PatternLayout class.
EX:
log4j.properties
Log4jTest.java
1. package com.durgasoft.log4j;
2.
3. import org.apache.log4j.LogManager;
4. import org.apache.log4j.Logger;
5.
6. public class Log4jTest {
762
9. logger.trace("Trace Message");
10. logger.debug("Debug Message");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
OP:
22/08/2018 18:50:885 com.durgasoft.log4j.Log4jTest TRACE : This Is Trace Message
22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest DEBUG : This Is Debug Message
22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest INFO : This Is Info Message
22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest WARN : This Is Warn Message
22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest ERROR : This Is Error Message
22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest FATAL : This Is Fatal Message
Note: We will use these patterns in general in PatternLayout for ConversionPattern property.
%d ----> Date
%c ----> Class to which we are providing Logging
%P ----> Logging Level
%L ----> Line NUmber
%m ----> Logging Message
%n ----> New Line Character
3. HTML Layout
It able to provide all logging messages in the form of Html file. To represent this Layout Log4j has
provided a predefined class in the form of "org.apache.log4j.HTMLLayout"
EX:
log4j.properties
Log4jTest.java
Page
1. package com.durgasoft.log4j;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4. XML Layout
It able to provide logging messages in the form of XML document. To rperepsent XMLLayout,
Log4j has provided a predefined class in the form of "org.apache.log4j.xml.XMLLayout"
EX:
log4j.properties
Log4jTest.java
1. package com.durgasoft.log4j;
2. import org.apache.log4j.LogManager;
3. import org.apache.log4j.Logger;
4.
5. public class Log4jTest {
6. static Logger logger = LogManager.getLogger(Log4jTest.class);
7. public static void main(String[] args) {
8. logger.trace("Trace Message");
764
9. logger.debug("Debug Message");
10. logger.info("Info Message");
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.jdbc;
2.
3. import java.sql.Connection;
4. import java.sql.DriverManager;
5. import java.sql.ResultSet;
6. import java.sql.Statement;
7.
8. import org.apache.log4j.LogManager;
9. import org.apache.log4j.Logger;
10.
11. public class Test {
12. //static Logger logger = LogManager.getLogger(Test.class);
13. static Logger logger = Logger.getLogger(Test.class);
14. public static void main(String[] args) {
15. logger.info("Application Starting Point");
16. Connection con = null;
17. Statement st = null;
18. ResultSet rs = null;
19. try {
20. Class.forName("oracle.jdbc.OracleDriver");
21. logger.info("Driver Loaded");
22. con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system
765
", "durga");
23. if(con == null) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
64. }
65. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
loginform.html
success.html
767
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
failure.html
web.xml
768
2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.c
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
log4j.properties
LoginServlet.java
1. package com.durgasoft.servlets;
2.
3. import java.io.IOException;
769
4.
5. import javax.servlet.RequestDispatcher;
Page
6. import javax.servlet.ServletException;
7. import javax.servlet.http.HttpServlet;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
UserService.java
1. package com.durgasoft.service;
2. import org.apache.log4j.Logger;
3.
4. import com.durgasoft.servlets.LoginServlet;
770
5.
6. public class UserService {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
771
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com