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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] Module
[Link]
[Link] Containers
1. BeanFactory
[Link]
2. Resources
[Link]
3
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] scope
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] Variables
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] ORM
[Link]
[Link] Integration with Spring
[Link] Introduction
[Link] Application Development
[Link] with Hibernate Integration.
[Link] Integration with Spring
[Link] Introduction.
9
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] Advice
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] Transactions
[Link]
[Link] Attributes
[Link] Levels
[Link] Based Transactions
[Link] Based Transactions.
[Link] Based Transactions
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
13
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
{CORE MODULE}
14
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
15
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
16
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
script functions.
[Link] interface will provide very good environment to send different request types from
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
19
2-Tier Arch:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Spring has provided very good Aspect Oriented Programming to prepare Applications.
Spring History:
[Link]: Interface1
[Link]: Mr. Rod Janson
[Link]: To simplify and Accelerate the complete Enterprise Applications.
[Link]: Open Source Software.
[Link] of Framework: Application Framework.
[Link] Version: Spring1.0[Oct, 2004]
[Link] Version: Spring3.x[Dec, 2014]
[Link] Version: Spring4.3.8[April, 2017]
[Link]: [Link]
[Link] on: Java[JAVA SE API, Servlets API]
[Link]: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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Spring3.x Version:
30
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Module5.x Version
31
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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();
[Link]();
[Link]();
Page
[Link]();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: [Link]
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: [Link]
--------------------
package [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
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) [Link]("hello");
[Link]([Link]());
}
}
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
package [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
import [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
app2:
-----
[Link]
----------------
package [Link];
[Link]
-----------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
45
xsi:schemaLocation="[Link]
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
----------
package [Link];
import [Link];
import [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] Process:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
48
package [Link];
public class User {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
setXXX()
getXXX()
}
6) Prepare COnfiguration File:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
spring_beans_config.xml
<beans>
<bean id="user" class="[Link]">
<property name="uname" value="Durga"/>
<property name="uqual" value="MTech"/>
<property name="uage" value="28"/>
<property name="uaddr" value="Hyd"/>
<property name="uemail" value="durga@[Link]"/>
<property name="umobile" value="91-9988776655"/>
</bean>
</beans>
Test class already created at the time of creating project, where provide
application logic.
[Link]
----------
package [Link];
import [Link];
import [Link];
import [Link];
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)[Link]("user");
user.display_User_Details();
50
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
"[Link]".
-->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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
-->To represent Resource object, Spring Framework has provided a predefined interface
in the form of
"[Link]"
-->For Resource interface, Spring Framework has provided the following implementation
classes.
1. [Link]:
--> It able to represent all the beans configuration details which are available in the form
of byte[].
2. [Link]:
--> It able to get all the beans confguration details which are available in the form of a file
in our system
hard disk.
3. [Link]:
--> It able to get all the beans configuration details which are existed at "classpath"
environment variable
refered locations.
4. [Link]:
52
--> It able to get all the beans configuration which are existed in the form of InputStream.
5. [Link]:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
6. [Link]:
--> It able to get all the beans configuration details which are existed in ServletContext.
--> It will be used in spring web applications.
7. [Link]:
--> 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("[Link]");
To get Bean object from BeanFactory we have to use the following method.
public Object getBean(String id_Name)
EX:
HelloBean bean=(HelloBean)[Link]("hello");
Example:
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
-----------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<bean id="helloBean" class="[Link]"/>
</beans>
[Link]
----------
package [Link];
import [Link];
import [Link];
import [Link];
54
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
ApplicationContext:
[Link]:
--> It able to get all the beans configuration details from confguration file which is existed
in application classpath.
[Link]:
--> It able to get all the beans configuration details from Configuration file which is
existed at our system harddisk.
56
[Link]:
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example:
[Link]
--------------
package [Link];
[Link]
-----------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<bean id="helloBean" class="[Link]"/>
</beans>
[Link]
57
package [Link];
import [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
import [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
[Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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="[Link]"/>
</beans>
MyBean mb=(MyBean)[Link]("bean1");
Status: Valid.
EX2:
<beans>
<bean id="bean1 bean2 bean3" class="[Link]"/>
</beans>
MyBean mb=(MyBean)[Link]("bean1");
Status: [Link]: 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX3:
<beans>
<bean name="bean1" class="MyBean"/>
</beans>
MyBean mb=(MyBean)[Link]("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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX6:
<beans>
<bean name="bean1" class="MyBean"/>
<alias name="bean1" alias="bean2"/>
<alias name="bean2" alias="bean3"/>
</bean>
</beans>
MyBean mb1=[Link](bean1); --> Valid
MyBean mb2=[Link](bean2); --> Valid
MyBean mb3=[Link](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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
<beans>
<bean id="bean1" class="[Link]" scope="singleton"/>
<bean id="bean2" class="[Link]" scope="singleton"/>
</beans>
[Link]([Link]("bean1"));//MyBean@a111
[Link]([Link]("bean1"));//MyBean@a111
[Link]([Link]("bean2"));//MyBean@a222
[Link]([Link]("bean2"));//MyBean@a222
2. prototype Scope:
EX:
[Link]
---------
65
<beans>
<bean id="bean1" class="[Link]" scope="prototype"/>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]([Link]("bean1"));//MyBean@a111
[Link]([Link]("bean1"));//MyBean@a222
[Link]([Link]("bean2"));//MyBean@a333
[Link]([Link]("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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
package [Link];
import [Link];
68
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
@Override
public String getConversationId() {
69
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public void registerDestructionCallback(String arg0, Runnable arg1) {
// TODO Auto-generated method stub
@Override
public Object remove(String name) {
Object obj = [Link](name);
return obj;
}
@Override
public Object resolveContextualObject(String arg0) {
// TODO Auto-generated method stub
return null;
}
[Link]
package [Link];
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]([Link]());
[Link]([Link]());
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
</beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link].@Configuration
--> It able to represent a class as configuration class.
[Link].@Bean
--> It will be used at method to represent the return object is bean object.
Example:
[Link]
package [Link];
}
public String sayHello() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
@Configuration
public class HelloBeanConfig {
@Bean
public HelloBean helloBean() {
return new HelloBean();
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
[Link]
<beans>
<bean id="hello" class="HelloBean"/>
76
</beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
class Test{
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
HelloBean bean=(HelloBean)[Link]("hello");
[Link]([Link]());
}
}
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:
[Link]
[Link]
<beans>
77
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
class Test{
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
HelloBean bean=(HelloBean)[Link]("hello");
[Link]([Link]());
}
}
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:
[Link]
[Link]
78
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
<beans>
<bean id="hello" class="HelloBean"
factory-method="getBeanInstance"
factory-bean="factory" />
<bean id="factory" class="HelloBeanFactory"/>
</beans>
[Link]
class Test{
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
HelloBean bean=(HelloBean)[Link]("hello");
[Link]([Link]());
}
}
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
package [Link];
[Link]
<beans>
<bean id="wel" class="[Link]"
80
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
WelcomeBean bean=(WelcomeBean)[Link]("wel");
[Link]([Link]());
[Link]();
}
}
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
import [Link];
import [Link];
[Link]
<beans>
82
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
WelcomeBean bean=(WelcomeBean)[Link]("wel");
[Link]([Link]());
[Link]();
}
}
@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:
[Link]
package [Link];
83
import [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
<beans >
<context:annotation-config/>
<bean id="wel" class="[Link]">
<property name="message" value="Welcome To Durgasoft"/>
</bean>
84
</beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
[Link]
spring_beans_config.xml
86
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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:
[Link]
87
package [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
setXXX()
getXXX()
}
[Link]
package [Link];
public class HelloBean {
private String wish_Message;
private String name;
setXXX()
getXXX()
88
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
public class WelcomeBean {
private String wish_Message;
private String name;
setXXX()
getXXX()
spring_beans_config.xml
<beans>
<bean id="wishBean" class="[Link]" 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="[Link]" parent="wishBean">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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)[Link]("helloBean");
[Link]([Link]());
[Link]();
WelcomeBean welcome=(WelcomeBean)[Link]("welcomeBean");
[Link]([Link]());
[Link]();
}
}
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
package [Link];
}
public void setWish_Message(String wish_Message) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
}
public String getName() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
}
public String getName() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
</bean>
</beans>
EX:
[Link]
package [Link];
public class Account {
private String accNo;
private String accName;
private String accType;
private long balance;
setXXX()
getXXX()
}
[Link]
package [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
<beans>
<bean id="emp" class="[Link]">
<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="[Link]">
<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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
Employee emp=(Employee)[Link]("emp");
[Link]();
}
}
BeanPostProcessor:
--> This method will be executed just before performing bean initialization and
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class BeanPostProcessorImpl implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String name) throws
BeansException {
[Link]("postProcessAfterInitialization()");
Customer cust=(Customer)bean;
[Link]("91-9988776655");
return cust;
}
99
@Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
public class Customer {
private String cid;
private String cname;
private String caddr;
private String cemail;
private String cmobile;
public Customer(){
[Link]("Customer Bean Object Creating");
}
public void init(){
[Link]("Customer Bean Object Initialization through init()
method");
}
public void destroy(){
[Link]("Customer Object Destroying through destroy()
method");
}
setXXX()
100
getXXX()
public void getCustomerDetails(){
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
<beans>
<bean id="cust" class="[Link]" 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="[Link]"/>
</beans>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
Customer cust=(Customer)[Link]("cust");
[Link]();
[Link]();
101
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] Lookup
[Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
105
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
------------
package [Link];
[Link]=cid;
[Link]=cname;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
<beans>
<bean id="crs" class="[Link]">
<constructor-arg value="C-111"/>
<constructor-arg value="JAVA"/>
<constructor-arg value="5000"/>
</bean>
</beans>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
107
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
package [Link];
setXXX()
getXXX()
}
108
[Link]
package [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
setXXX()
getXXX()
[Link]("Employee Details");
[Link]("-------------------");
[Link]("Employee Id :"+eid);
[Link]("Employee Name :"+ename);
[Link]("Employee Salary :"+esal);
[Link]("Employee Address:"+eaddr);
[Link]("Account Details");
[Link]("-------------------");
[Link]("Account Number :"+[Link]());
[Link]("Account Name :"+[Link]());
[Link]("Account Type :"+[Link]());
[Link]("Account Balance:"+[Link]());
}
}
[Link]
<beans>
<bean id="acc" class="[Link]">
109
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
Employee emp=(Employee)[Link]("emp");
[Link]();
}
}
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
</bean>
</beans>
In spring applications, if we want to inject List of elements in beans then we have to declare
the corresponding property as [Link] 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 [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
In Spring applications, if we want to inject Map of elements in Bean object then we have to
declare the corresponding property as [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example:
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
setXXX()
getXXX()
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
public class Address {
private String pno;
private String street;
private String city;
private String country;
setXXX()
getXXX()
[Link]
114
<beans>
<bean id="addr" class="[Link]">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
Student std=(Student)[Link]("std");
[Link]();
}
}
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Ex:
[Link]
package [Link];
[Link]
package [Link];
[Link]
<beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
[Link]
<beans>
<bean id="student" class="[Link]">
<property name="branch" ref="branch"/>
</bean>
<bean id="branch" class="[Link]">
<property name="student" ref="student"/>
</bean>
</beans>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
119
import [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
package [Link];
public class Student {
private String sid;
private String sname;
120
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
setXXX()
getXXX()
[Link]
------------------------
<beans>
<bean id="std" class="[Link]">
<constructor-arg index="0" value="S-111"/>
<constructor-arg index="1" value="AAA"/>
<constructor-arg index="2" value="Hyd"/>
[Link]
package [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] 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.
[Link] 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.
[Link] 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.
[Link] dependency injection will make the bean object as "Immutable Object".
Setter method dependency injection will make the bean object as "mutable Object".
[Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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="[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Note: To use c-namespace in spring configration file we have to define "c" namespace in
XSD like below.
xmlns:c="[Link]
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:
[Link]
package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
setXXX()
getXXX()
[Link]
package [Link];
setXXX()
126
getXXX()
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
[Link]
package [Link];
String cid;
String cname;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
<beans -------
xmlns:p="[Link]
xmlns:c="[Link]
-----
>
<bean id="emp" class="[Link]"
p:eid="E-111" p:ename="AAA" p:esal="15000" p:eaddr-ref="addr"/>
<bean name="addr" class="[Link]"
p:hno="23/3rt" p:street="M G Road" p:city="Hyd" p:state="Tel"/>
</beans>
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
129
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
"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.
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
It is representing "no" autowiring for the beans injection, we must provide explicit
configuration for the beans injection.
[Link]
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.
[Link]
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.
[Link]
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
[Link]
Page
package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
setXXX()
getXXX()
[Link]
package [Link];
public class Account {
private String accNo;
private String accName;
private String accType;
private long balance;
setXXX()
getXXX()
[Link]
package [Link];
public class Employee {
private String eid;
private String ename;
private Address eaddr;
132
setXXX()
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
<beans>
<bean id="eaddr" class="[Link]">
<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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
Employee emp=(Employee)[Link]("emp");
[Link]();
}
}
If we want to provide example for "constructor" autowiring then we have to use the
following components in the above example
Example:
134
[Link]
Page
package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
setXXX()
getXXX()
[Link]
package [Link];
public class Account {
private String accNo;
private String accName;
private String accType;
private long balance;
setXXX()
getXXX()
}
[Link]
[Link]=ename;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
<beans>
<bean id="eaddr" class="[Link]">
same as above
</bean>
<bean id="eacc" class="[Link]">
same as above
136
</bean>
<bean id="emp" class="[Link]" autowire="constructor">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
Employee emp=(Employee)[Link]("emp");
[Link]();
}
}
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="[Link]"
autowire-candidate="false">
----
</bean>
<bean id="student" class="[Link]" autowire="byType">
----
137
</bean>
</beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example:
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
return scourse;
}
Page
@Autowired(required=true)
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
public class Course {
private String cid;
private String cname;
private int ccost;
setXXX()
getXXX()
}
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
Student std=(Student)[Link]("std");
[Link]();
}
}
Example:
141
[Link]
Page
package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
import [Link];
import [Link];
import [Link];
@Autowired
public Student(String sid, String sname,
@Qualifier("adv_Java")Course scourse){
[Link]=sid;
[Link]=sname;
[Link]=scourse;
}
public void getStudentDetails(){
[Link]("Student Details");
[Link]("--------------------");
[Link]("Student Id :"+sid);
[Link]("Student Name :"+sname);
[Link]("Course Details");
[Link]("----------------");
[Link]("Course Id :"+[Link]());
[Link]("Course Name :"+[Link]());
[Link]("Course Cost :"+[Link]());
}
}
[Link]
package [Link];
142
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
setXXX()
getXXX()
}
[Link]
<beans>
<context:annotation-config/>
<bean id="core_Java" class="[Link]">
<property name="cid" value="C-111"/>
<property name="cname" value="Core Java"/>
<property name="ccost" value="10000"/>
</bean>
<bean id="adv_Java" class="[Link]">
<property name="cid" value="C-111"/>
<property name="cname" value="Adv Java"/>
<property name="ccost" value="20000"/>
</bean>
<bean id="std" class="[Link]" >
<constructor-arg name="sid" value="S-111"/>
<constructor-arg name="sname" value="Durga"/>
</bean>
</beans>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
143
ClassPathXmlApplicationContext("[Link]");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]-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
"[Link]"
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="[Link]"/>
<context:component-scan base-package="[Link]"/>
<context:component-scan base-package="[Link]"/>
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
----------------
package [Link];
import [Link];
[Link]
--------------------
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
//@Repository("accDao")
145
@Component("accDao")
public class AccountDaoImpl implements AccountDao {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public Account getAccount(String accNo) {
Account acc = null;
try {
Connection con = [Link]();
PreparedStatement pst = [Link]("select * from
account where accNO = ?");
[Link](1, accNo);
ResultSet rs = [Link]();
boolean b = [Link]();
if(b == true) {
acc = new Account();
[Link]([Link]("ACCNO"));
[Link]([Link]("ACCNAME"));
[Link]([Link]("ACCTYPE"));
147
[Link]([Link]("BALANCE"));
}else {
Page
acc = null;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public String delete(String accNo) {
try {
Connection con = [Link]();
PreparedStatement pst = [Link]("select * from
account where accNO = ?");
[Link](1, accNo);
ResultSet rs = [Link]();
148
boolean b = [Link]();
if(b == true) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
--------------------
package [Link];
import [Link];
[Link]
-----------------------
Page
package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
@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 [Link](accNo);
}
@Override
public Account getAccount(String accNo) {
return [Link](accNo);
}
@Override
public String updateAccount(String accNo, String accName, String accType, int
balance) {
150
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public String deleteAcount(String accNo) {
return [Link](accNo);
}
[Link]
-------------
package [Link];
}
public void setAccType(String accType) {
Page
[Link] = accType;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:context="[Link]
xsi:schemaLocation="[Link]
[Link]
[Link]
[Link]
<context:component-scan base-package="[Link]"/>
<context:component-scan base-package="[Link]"/>
<bean id="dataSource" class="[Link]">
<property name="URL" value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="user" value="system"/>
<property name="password" value="durga"/>
</bean>
</beans>
[Link]
152
package [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
while(true) {
[Link]();
[Link]("Account Operations Menu");
[Link]("[Link] Account");
[Link]("[Link] Account");
[Link]("[Link] Account");
[Link]("[Link] Account");
[Link]("[Link]");
[Link]("Your Option :");
int option = [Link]([Link]());
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
if([Link]("failure")) {
[Link]("Account Updation Failure");
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}
}
}
[Link]
156
----------------
package [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
//@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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public String search(String accNo) {
try {
Connection con = [Link]();
PreparedStatement pst = [Link]("select * from
account where accNo = ?");
[Link](1, accNo);
158
ResultSet rs = [Link]();
boolean b = [Link]();
Page
if(b == true) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public Account getAccount(String accNo) {
Account acc = null;
try {
Connection con = [Link]();
PreparedStatement pst = [Link]("select * from
account where accNO = ?");
[Link](1, accNo);
ResultSet rs = [Link]();
boolean b = [Link]();
if(b == true) {
acc = new Account();
[Link]([Link]("ACCNO"));
[Link]([Link]("ACCNAME"));
[Link]([Link]("ACCTYPE"));
[Link]([Link]("BALANCE"));
}else {
acc = null;
}
} catch (Exception e) {
[Link]();
159
}
return acc;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public String delete(String accNo) {
try {
Connection con = [Link]();
PreparedStatement pst = [Link]("select * from
account where accNO = ?");
[Link](1, accNo);
ResultSet rs = [Link]();
boolean b = [Link]();
if(b == true) {
pst = [Link]("delete from account where accNo
= ?");
[Link](1, accNo);
[Link]();
160
status = "success";
}else {
Page
status = "notexisted";
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
[Link]
package [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@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 [Link](accNo);
}
162
@Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
return [Link](accNo);
}
@Override
public String updateAccount(String accNo, String accName, String accType, int
balance) {
@Override
public String deleteAcount(String accNo) {
return [Link](accNo);
}
[Link]
package [Link];
}
public String getAccName() {
Page
return accName;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
164
@Configuration
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link]
-----
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
<beans>
<bean id="std" class="[Link]" scope="singleton">
----
<property name="scourse" ref="scourse"/>
</bean>
<bean id="scourse" class="[Link]" scope="prototype">
-----
</bean>
</beans>
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
package [Link];
[Link]
168
package [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
public class SavingsAccount implements Account {
public void create() {
[Link]("Savings Account is created");
}
public void search() {
[Link]("Savings Account is identified");
}
public void update() {
[Link]("Savings Account is Updated");
}
public void delete() {
[Link]("Savings Account is Deleted");
}
}
[Link]
169
package [Link];
Page
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
<beans>
<bean id="savingsAccount" class="[Link]" />
<bean id="currentAccount" class="[Link]" />
<bean id="savingsAccountFactory"
class="[Link]">
<lookup-method name="getAccount" bean="savingsAccount"/>
</bean>
<bean id="currentAccountFactory" class="[Link]">
<lookup-method name="getAccount" bean="currentAccount"/>
</bean>
</beans>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args) {
ApplicationContext context=new
ClassPathXmlApplicationContext("/com/durgasoft/cfgs/spring_beans_config.xml");
AccountFactory
savingsAccountFactory=(AccountFactory)[Link]("savingsAccountFactory");
SavingsAccount
savings_Account=(SavingsAccount)[Link]();
170
savings_Account.create();
savings_Account.search();
Page
savings_Account.update();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
AccountFactory
currentAccountFactory=(AccountFactory)[Link]("currentAccountFactory");
CurrentAccount
current_Account=(CurrentAccount)[Link]();
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:
[Link]
package [Link];
171
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
public class NewImpl implements MethodReplacer {
public Object reimplement(Object arg0, Method arg1, Object[] arg2) throws Throwable
{
[Link]("Course Details");
[Link]("-----------------");
[Link]("Course Id :C-222");
[Link]("Course Name :.NET");
[Link]("Course Cost :20000");
return null;
}
}
spring_beans_config.xml
<beans>
<bean id="newImpl" class="[Link]"/>
172
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
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)[Link]("course");
[Link]();
}
}
173
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] 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.
[Link] 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
"[Link]" .
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
public class Employee {
private String eid;
private String ename;
private float esal;
private int eage;
private String eemail;
private String emobile;
[Link]
[Link]=Employee Id is required.
[Link]=Invalid Employee Id.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
public boolean supports(Class type) {
[Link]("Hello");
return [Link](type);
}
@Override
177
[Link]("Hello...validate()");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}else{
if(![Link]().startsWith("91-")){
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
<beans>
<bean id="emp" class="[Link]">
<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="[Link]">
<property name="resource"
value="/com/durgasoft/resources/[Link]"/>
</bean>
</beans>
Test.java0
package [Link];
import [Link];
import [Link];
179
import [Link];
import [Link];
Page
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
180
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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".
[Link]
[Link]
[Link]
[Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
To Handle all the above Events, Spring Framework has provided a Listener in the form
of "[Link]" 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:
[Link]
182
package [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public void onApplicationEvent(ContextRefreshedEvent e) {
[Link]("Application Context is Refreshed");
}
[Link]
package [Link];
import [Link];
import [Link];
@Override
public void onApplicationEvent(ContextStartedEvent e) {
[Link]("Application Context Started....");
}
}
[Link]
183
package [Link];
Page
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public void onApplicationEvent(ContextStoppedEvent e) {
[Link]("Application Context Stopped");
}
[Link]
package [Link];
import [Link];
import [Link];
@Override
public void onApplicationEvent(ContextClosedEvent e) {
[Link]("Application Context has Closed");
}
[Link]
package [Link];
184
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
<beans>
<bean id="helloBean" class="[Link]">
<property name="uname" value="Durga"/>
</bean>
<bean id="contextRefreshedEvent"
class="[Link]"/>
<bean id="contextStartedEvent"
class="[Link]"/>
<bean id="contextStoppedEvent"
class="[Link]"/>
<bean id="contextClosedEvent"
class="[Link]"/>
</beans>
[Link]
package [Link];
import [Link];
185
import [Link];
import [Link];
Page
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Note:Spring4.2 version has provided very good annotations support for Event
Handling in the form of the following Annotations.
1)@EventListener({[Link],[Link]...})
Where [Link], [Link],... are Event class types wich we want to process.
EX:@EventListener({[Link],[Link]})
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.
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
} catch (Exception e) {
[Link]();
}
}
188
super(obj);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}
}
[Link]
package [Link];
import [Link];
import [Link];
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
import [Link];
@Override
public void onApplicationEvent(AccountEvent e) {
[Link]();
}
[Link]
package [Link];
import [Link];
}
public void updateAccount(){
Page
[Link]("Account Updated");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
<beans>
<bean id="account" class="[Link]">
<property name="publisher" ref="accountEventPublisher"/>
</bean>
<bean id="accountEventHandler"
class="[Link]"/>
<bean id="accountEventPublisher"
class="[Link]"/>
</beans>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
ConfigurableApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
Account account=(Account)[Link]("account");
[Link]();
[Link]();
[Link]();
191
[Link]();
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link] 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 "[Link]".
EX:
[Link] Formations
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. Number Formations:
Steps:
[Link] Formations:
It can be used to represent a Date w.r.t a particular Locale, for this, it will use
[Link] class.
Steps:
[Link] Formations:
It can be used to represent messages w.r.t a particular Locale, for this, we have to use
properties files and [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
Locale l = new Locale("it", "IT");
ResourceBundle resource_Bundle =
[Link]("com/durgasoft/resources/abc", l);
[Link](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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
For MessageSource interface Spring Framework has provided the following two
implementation classes.
[Link]
[Link]
Steps:
[Link] properties files with the messages and with the following format for
properties files names.
baseName_lang_Country.properties.
[Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example-1:
abc_en_US.properties
---------------------
welcome = Welcome To {0} and {1} User.
abc_fr_FR.properties
---------------------
welcome = Welcome To {0} and {1} Users.
[Link]
--------------
package [Link];
import [Link];
import [Link];
}
196
}
Page
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
<beans>
<bean id="i18nBean" class="[Link].I18NBean">
<property name="messageSource" ref="resourceBundleMessageSource"/>
</bean>
<bean id="resourceBundleMessageSource"
class="[Link]">
<property name="basename" value="com/durgasoft/resources/abc"/>
</bean>
</beans>
[Link]
package [Link];
import [Link].I18NBean;
import [Link];
import [Link];
<properties>
<entry key="message_Key"> Message_Value </entry>
Page
-----
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example:
abc_en_US.xml
--------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "[Link]
<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 "[Link]
<properties>
<entry key="welcome"> Welcome to fr France User from XML </entry>
</properties>
spring_beans_config.xml
------------------------
<beans>
<bean id="i18nBean" class="[Link].I18NBean">
<property name="messageSource"
ref="reloadableResourceBundleMessageSource"/>
</bean>
<bean id="reloadableResourceBundleMessageSource"
class="[Link]
198
e">
<property name="basename" value="com/durgasoft/resources_xml/abc"/>
Page
</bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
--------------
package [Link];
import [Link];
import [Link];
[Link]
package [Link];
import [Link].I18NBean;
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
ApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");
I18NBean bean = (I18NBean)[Link]("i18nBean");
199
[Link]();
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link];
public class Employee {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
To get BeanInfo object we have to use the following method from BeanInfoFactory
interface.
Example:
[Link]
package [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
203
import [Link];
import [Link];
Page
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 "[Link]" class.
To Check whether the property is readable or writable then we have to use the
following methods from BeanWrapper class.
Example:
[Link]
package [Link];
public class Employee {
private int eno;
205
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]("Employee Details");
[Link]("-------------------");
Page
[Link]("Employee Id :"+eno);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
[Link]("eaddr", "Hyd");
[Link](map);
Page
[Link](emp);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]("Employee Details");
[Link]("--------------------------");
[Link]("Employee No :"+[Link]("eno"));
[Link]("Employee Name :"+[Link]("ename"));
[Link]("Employee Salary :"+[Link]("esal"));
[Link]("Employee Address :"+[Link]("eaddr"));
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]();
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]: 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
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
@Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
spring_beans_config.xml
214
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
</bean>
<bean class="[Link]">
<property name="customEditors">
<map>
<entry key="[Link]"
value="[Link]"/>
</map>
</property>
</bean>
</beans>
215
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link] a seperate spring configuration file for each and every phase of the project
lifecyle with the respective configuration details.
EX: [Link]
[Link]
[Link]
[Link] all Spring Configuration files we must provide "profile" attribute in <beans> tag
with the respective lifecycle phyase name.
EX: [Link]
------------------------------
<beans profile="development">
216
------
</beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
Example:
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
</beans>
[Link]
</beans>
[Link]
package [Link];
import [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
220
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
[Link] 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......
[Link] 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 "[Link]" package.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
import [Link];
import [Link];
import [Link];
expr = [Link]("10*10");
int val2 = (Integer) [Link]();
[Link](val2);
expr = [Link]("'abc'+'def'");
String val3 = (String) [Link]();
[Link](val3);
}
}
[Link]
package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link](context, "5");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]("num1 :"+cal.getNum1());
[Link]("num2 :"+cal.getNum2());
[Link]("ADD :"+[Link]());
[Link]("SUB :"+[Link]());
[Link]("MUL :"+[Link]());
}
}
SpEL Features:
[Link]
[Link]
[Link]
[Link] Invocations
[Link]
[Link]
[Link] Expressions
---> It able to allow only literals inside the Expressions.
[Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example:
package [Link];
import [Link];
import [Link];
import [Link];
public class Test {
expr = [Link]("0xABCDEF*10+6");
[Link]([Link]());
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Syntax:
var_Name?.methid_or_Var_Name()
Example:
package [Link];
[Link]
package [Link];
import [Link];
import [Link];
228
import [Link];
import [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
expr = [Link]("T(Thread).MIN_PRIORITY");
[Link]([Link]());
expr = [Link]("T(Integer).toString(10)");
[Link]([Link]());
[Link]
#var_Name.
Example:
230
[Link]
Page
package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)throws Exception {
MyMath math = new MyMath();
StandardEvaluationContext context = new
StandardEvaluationContext(math);
[Link]("number1", 10);
[Link]("number2", 5);
ExpressionParser parser = new SpelExpressionParser();
231
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] 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.
[Link] StandardEvaluationContext object.
[Link] Method with a name.
public void registerFunction(String meth_Name, Method m)
[Link] an Expression with method call and access it.
Example:
[Link]
package [Link];
public class MyString {
public static void reverseString(String str) {
StringBuffer sb = new StringBuffer(str);
[Link]([Link]());
}
}
[Link]
232
package [Link];
import [Link];
Page
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
City_State_Collection.java
package [Link];
import [Link];
}
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].City_State;
import [Link].City_State_Collection;
}
235
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
{Spring JDBC
MODULE}
236
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
237
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
-->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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
In Service layer
StudentDao dao = [Link]();
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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)[Link]
b)[Link]
c)[Link]
d)[Link]
e)[Link]
f)[Link]
g)[Link]
h)[Link]
i)[Link]
j)[Link]
k)[Link]
l)[Link]
[Link]
a)[Link]
[Link]
a)ControllerServlet
[Link]:
a)StudentService
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Design Patterns:
a)DAO
b)MVC
c)DTO
d)Factory
Example:
[Link]
<frameset rows="20%,65%,15%">
<frame src="[Link]"/>
<frameset cols="20%,80%">
<frame src="[Link]"/>
<frame src="[Link]" name="body"/>
</frameset>
<frame src="[Link]"/>
</frameset>
[Link]
</html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
</html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
</tr>
<tr>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
244
"[Link]
<html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
<%@page import="[Link]"%>
<%!
StudentTo sto;
%>
<%
sto = (StudentTo)[Link]("sto");
%>
<html>
<body bgcolor="lightblue">
<center>
<br><br><br>
<table border = "1" bgcolor="white">
<tr>
<td>Student Id</td><td><%= [Link]() %></td>
</tr>
<tr>
245
<tr>
<td>Student Address</td><td><%= [Link]() %></td>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
</table>
</center>
</body>
</html>
[Link]
[Link]
<br><br><br>
<font color="red" size="6">
Page
<b>
Student Not Existed
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
Failure
</b>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ControllerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String button_Label = [Link]("button");
String status = "";
RequestDispatcher rd = null;
if(button_Label.equals("ADD")){
StudentService service = [Link]();
StudentTo sto = new StudentTo();
[Link]([Link]("sid"));
[Link]([Link]("sname"));
[Link]([Link]("saddr"));
status = [Link](sto);
if([Link]("success")){
rd = [Link]("./[Link]");
[Link](request, response);
}
if([Link]("failure")){
248
rd = [Link]("./[Link]");
[Link](request, response);
Page
}
if([Link]("existed")){
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
dispatcher = [Link]("[Link]");
[Link](request, response);
}
}
}
249
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
import [Link];
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
@Override
public StudentTo searchStudent(String sid) {
StudentTo sto = null;
StudentDao dao = [Link]();
sto = [Link](sid);
return sto;
}
@Override
public String deleteStudent(String sid) {
250
return status;
}
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link](2, [Link]());
[Link](3, [Link]());
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
ResultSet rs = [Link]();
boolean b = [Link]();
Page
if(b == true) {
pst = [Link]("delete from student where sid = ?");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
[Link] = saddr;
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
import [Link];
import [Link];
[Link]
package [Link];
import [Link];
import [Link];
[Link]
package [Link];
import [Link];
254
import [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}
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 ―[Link]‖ package.
255
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link] 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.
[Link] 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.
[Link] Plain JDBC, to hold the results we are able to use only ResultSet object, which is not
implementing [Link] 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 [Link] interface and which are
transferable in Network.
256
[Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] 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".
[Link] 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
"[Link]" 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
"[Link]" which contains the following method .
Example
[Link]
package [Link];
import [Link];
import [Link];
public interface StudentDao {
258
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
@Override
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
[Link] = jdbcTemplate ;
}
@Override
public String add(Student std) {
try {
[Link]("insert into student
values('"+[Link]()+"','"+[Link]()+"','"+[Link]()+"')");
status = "success";
}catch(Exception e) {
status = "failure";
[Link]();
}
return status;
}
259
@Override
public Student search(String sid) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public String update(Student std) {
try {
[Link]("update student set
sname='"+[Link]()+"',saddr='"+[Link]()+"' where sid='"+[Link]()+"'");
status="success";
[Link]
}catch(Exception e) {
status="failure";
[Link]();
}
return status;
}
@Override
public String delete(String sid) {
try {
[Link]("delete from student where sid='"+sid+"'");
status="success";
} catch (Exception e) {
status="failure";
[Link]();
}
return status;
}
}
[Link]
package [Link];
260
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
261
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]("S-222");
[Link]("Anil");
[Link]("Hyd");
status = [Link](std);
[Link]("Student Insertion :"+status);
[Link]("S-333");
[Link]("Sekhar");
[Link]("Hyd");
status = [Link](std);
[Link]("Student Insertion :"+status);
[Link]();
//----Retriving Record-----
Student std1 = [Link]("S-111");
if(std1 == null) {
[Link]("Student Search Status :NotExisted");
}else {
[Link]("Student Details");
[Link]("--------------------");
[Link]("Student Id :"+[Link]());
[Link]("Student Name :"+[Link]());
[Link]("Student Address :"+[Link]());
}
[Link]();
//----Updating a Record------
[Link]("S-111");
[Link]("XXX");
262
[Link]("YYY");
status = [Link](std);
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
//----Deleting a record-----
status = [Link]("S-111");
[Link]("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:
[Link]
package [Link];
import [Link];
import [Link];
263
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
@Override
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
[Link] = jdbcTemplate ;
}
@Override
public String add(Student std) {
try {
String query = "insert into student values(?,?,?)";
[Link](query, new Object[] {[Link](), [Link](),
[Link]()});
status = "success";
}catch(Exception e) {
status = "failure";
[Link]();
}
return status;
264
}
Page
@Override
public Student search(String sid) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public String update(Student std) {
try {
[Link]("update student set sname=?, saddr=? where
sid=?",new Object[] { [Link](), [Link](), [Link]()});
status="success";
}catch(Exception e) {
status="failure";
[Link]();
}
return status;
}
@Override
public String delete(String sid) {
try {
[Link]("delete from student where sid=?", new Object[] {sid});
status="success";
} catch (Exception e) {
status="failure";
[Link]();
}
return status;
}
}
[Link]
265
xmlns:xsi="[Link]
xmlns:context="[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
<bean id="dataSource"
class="[Link]" >
<property name="driverClassName" value="[Link]"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="durga"/>
</bean>
</beans>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]([Link]("SNAME"));
[Link]([Link]("SADDR"));
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]("S-222");
[Link]("Anil");
[Link]("Hyd");
status = [Link](std);
[Link]("Student Insertion :"+status);
[Link]("S-333");
[Link]("Sekhar");
[Link]("Hyd");
status = [Link](std);
267
//----Retriving Record-----
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
//----Updating a Record------
[Link]("S-111");
[Link]("XXX");
[Link]("YYY");
status = [Link](std);
[Link]("Student Updation :"+status);
[Link]();
//----Deleting a record-----
status = [Link]("S-111");
[Link]("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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]("AAA");
[Link]("Hyd");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Note: JdbcTemplate is allowing DataSource object injection through setter method, but,
NamedParameterJdbcTemplate class is allowing DataSource object injection through Constructor
Dependency Injection.
Example
[Link]
package [Link];
import [Link];
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@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);
[Link](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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
272
import [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}
}
[Link]
</beans>
Page
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
import [Link];
import [Link];
Customer c1 = [Link]("C-111");
[Link]("Customer Details");
[Link]("--------------------");
[Link]("Customer Id :"+[Link]());
[Link]("Customer Name :"+[Link]());
[Link]("Customer Address :"+[Link]());
[Link]();
Customer c2 = new Customer();
[Link]("C-111");
[Link]("BBB");
[Link]("Sec");
status = [Link](c2);
[Link]("Student Updation Status :"+status);
Customer c3 = [Link]("C-111");
[Link]("Customer Updated Details");
[Link]("--------------------");
[Link]("Customer Id :"+[Link]());
[Link]("Customer Name :"+[Link]());
[Link]("Customer Address :"+[Link]());
274
[Link]();
status = [Link]("C-111");
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
package [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
}
@Override
public String add(Employee emp) {
String query = "insert into emp1
values("+[Link]()+",'"+[Link]()+"',"+[Link]()+",'"+[Link]()+"')";
[Link]().execute(query);
status = "SUCCESS";
return status;
}
@Override
public Employee search(int eno) {
String query = "select * from emp1 where eno=?";
Employee emp = [Link](query, new
EmployeeMapper(), eno);
return emp;
}
@Override
public String update(Employee emp) {
String query = "update emp1 set ename=?, esal =?, eaddr=? where eno=?";
[Link](query, [Link](), [Link](),
[Link](), [Link]());
276
status = "SUCCESS";
return status;
Page
}
@Override
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
return status;
}
}
[Link]
package [Link];
}
public void setEaddr(String eaddr) {
Page
[Link] = eaddr;
}
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
}
}
[Link]
</bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
</beans>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]("--------------------");
[Link]("Employee Number :"+[Link]());
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link]
[Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link]
package [Link];
281
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
282
import [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
}
@Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link] = [Link]
[Link] = jdbc:oracle:thin:@localhost:1521:xe
[Link] = system
[Link] = durga
[Link]
<bean id="dataSource"
class="[Link]">
<property name="driverClassName" value="${[Link]}"/>
<property name="url" value="${[Link]}"/>
<property name="username" value="${[Link]}"/>
284
<context:property-placeholder location="[Link]"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
</beans>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]("Hyd");
[Link](e3);
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}
}
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();
[Link]("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)
[Link]
286
package [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
287
import [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import
[Link]
e;
import
[Link];
import [Link];
import [Link];
}
@Override
public void create(Employee emp) {
try {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql= "insert into emp1 values("+[Link]()+",'"+[Link]()+"',"+[Link]()+"
,'"+[Link]()+"')";
[Link](sql);
}catch(Exception e) {
[Link]();
288
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
// [Link](map);
return [Link]("SAL");
}
}
[Link]
xmlns:context="[Link]
xsi:schemaLocation="
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]">
<bean id="empDao" class="[Link]">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id = "dataSource" class =
"[Link]">
<property name = "driverClassName" value = "[Link]"/>
<property name = "url" value = "jdbc:oracle:thin:@localhost:1521:xe"/>
<property name = "username" value = "system"/>
<property name = "password" value = "durga"/>
</bean>
</beans>
[Link]
289
package [Link];
Page
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
import [Link];
import [Link];
[Link]([Link]()+"---->"+salary3);
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
}
292
[Link]
Page
package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
//[Link](map);
return map;
}
}
[Link]
</bean>
<bean id = "dataSource"
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]("Employee Details");
[Link]("ENO\tENAME\tESAL\tEADDR");
[Link]("-----------------------------");
for(Employee e: list) {
[Link]([Link]()+"\t"+[Link]()+"\t"+[Link]()+"\t"+[Link]());
}
}
294
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
In Spring JDBC Applications, to process BLOB and CLOB Data, Spring JDBC has provided the
following three interfaces mainly.
[Link]
--> It will be used to store Blob and Clob related data in Database.
protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException,
DataAccessException
[Link]
--> It will be used to retrive BLOB and CLOB data from database.
streamData(ResultSet rs)throws SQLException, IOException, DataAccessException
[Link]
--> It contains the following methods to prepare Binary stream and character streams to send blob
and clob data to database.
setBlobAsBinaryStream()
setClobAsCharacterStream()
[Link]
--> It contains the following methods to get Binary stream and character stream to get blob and
clob data.
getBlobAsBinaryStream()
getClobAsCharacterStream()
Example:
[Link]
package [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
[Link]
Page
package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
AbstractLobCreatingPreparedStatementCallback(lobHolder) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@Override
public Employee readEmployee() {
Employee emp = new Employee();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}
});
return emp;
}
[Link]
<bean id="dataSource"
class="[Link]">
<property name="driverClassName" value="${[Link]}"/>
<property name="url" value="${[Link]}"/>
<property name="username" value="${[Link]}"/>
<property name="password" value="${[Link]}"/>
</bean>
<bean id="lobHolder" class="[Link]">
</bean>
<context:property-placeholder location="[Link]"/>
</beans>
299
[Link]
Page
[Link] = [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]("Employee Resume
:"+emp2.getEmp_Resume().getAbsolutePath());
Page
}
}
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
To overcome the above problem we have to use Connection Pooling in [Link] 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 [Link] in beans
configuration file with the following properties .
[Link]
[Link]
[Link]
[Link]
---
---
EX:
301
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
In Spring JDBC applications we are able to use the following third party connection pooling
mechanisms
[Link] DBCP
2.C3P0
[Link]
[Link] DBCP:
[Link]
[Link]
[Link]
[Link]
[Link]:It will take Initial pool size.
[Link]: It will allow the specified no of max connections.
---
---
EX:
---
<bean id="dataSource" class="[Link]">
<property name="driverClassName" value="[Link]" />
<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
[Link]
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
[Link]
[Link]
[Link]:It will take Initial pool size.
[Link]: It will allow the specified no of max connections.
[Link]: Max statements it allows.
[Link]: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-[Link].jar
[Link]
[Link]:
[Link]
Page
[Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Note: To use this mechanism in Spring JDBC Applications then we have to add the following two
jar files to Library.
[Link]
[Link]
Example:
[Link]
package [Link];
}
public void setEname(String ename) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}
}
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Test {
[Link](111);
[Link]("Nag");
Page
[Link](5000);
[Link]("Hyd");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
}
}
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Database Name: xe
Host Name: localhost
Page
Port : 1521
Database User Name: system
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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)[Link]
2)[Link]
3)[Link]
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:
[Link]
package [Link];
310
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
package [Link];
import [Link];
}
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
}
}
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
</beans>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
{SPRING AOP}
314
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
315
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link]:
[Link]:
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
"[Link]".
If we want to use Before Advice in Spring applications , first, we have to declare an user defined
class, it must implement [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link] 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 "[Link]".
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link].
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
"[Link]".
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. public interface EmployeeService {
6. public void displayEmployee(Employee emp);
7. public void getEmployeeDetails(Employee emp);
8. }
326
[Link]
Page
1. package [Link];
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. import [Link];
6.
7.
8. import [Link];
9.
327
12. @Override
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
15. </bean>
16.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
329
4. import [Link];
5. import [Link];
Page
6. import [Link];
7.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
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. [Link] = sname;
14. }
15. public String getSqual() {
16. return squal;
17. }
330
20. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. public interface InstituteService {
6. public void enquiry(Student std, String course_Name);
7. public void registration(Student std, String course_name);
8. }
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. public class InstituteServiceImpl implements InstituteService {
6.
7. @Override
8. public void enquiry(Student std, String course_Name) {
9. [Link]("Student Enquiry Details");
10. [Link]("-----------------------------");
331
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. import [Link];
6.
7. import [Link];
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. [Link]("ThanQ "+[Link]()+" for your course "+[Link]()+"
on "+course_Name);
16. [Link]("Durgasoft Team will contact with you for the Course Schedule");
17. }
18. }
[Link]
2. <beans xmlns="[Link]
3. xmlns:xsi="[Link]
Page
4. xmlns:aop="[Link]
5. xsi:schemaLocation="
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
333
8.
9. public class Test {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. public interface MovieService {
6. public void playMovie(Movie movie)throws Exception;
7. }
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. public class MovieServiceImpl implements MovieService {
6.
7. @Override
8. public void playMovie(Movie movie)throws Exception {
9. [Link]("Movie Details");
10. [Link]("----------------");
11. [Link]("Movie Name :"+movie.getMovie_Name());
12. [Link]("Movie Time :"+movie.getShow_Time());
13. [Link]("Price :"+[Link]());
14. throw new RuntimeException("Power Failure Occurred");
15. }
16.
17. }
[Link]
1. package [Link];
2.
3.
4. import [Link];
335
5.
6. import [Link];
Page
7.
8.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
27. </list>
28. </property>
Page
29. </bean>
30. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8.
9. public class Test {
10.
11. public static void main(String[] args) {
12. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
[Link]");
13. Movie movie = (Movie)[Link]("movieBean");
14.
15. MovieService movie_Service = (MovieService) [Link]("proxy");
16. try {
17. movie_Service.playMovie(movie);
18. } catch (Exception e) {
19.
20. }
21.
22. }
23.
24. }
[Link]
1. package [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. public interface TransactionService {
7. public void debit(Account acc, Cheque cheque );
8. }
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. public class TransactionServiceImpl implements TransactionService {
7.
8. @Override
9. public void debit(Account acc, Cheque cheque) {
10. int initial_Amount = [Link]();
11. int debit_Amount = [Link]();
12. int total_Amount = initial_Amount - debit_Amount;
13. [Link](total_Amount);
14. [Link]("*******Transaction Success*******************");
15. [Link]("*******Amount is debited from Account********");
16. }
17. }
[Link]
1. package [Link];
2.
339
3. import [Link];
4. import [Link];
Page
5.
6.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. public class Test {
11.
12. public static void main(String[] args) {
13. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
[Link]");
14. Account account = (Account) [Link]("accBean");
15. Cheque cheque = (Cheque) [Link]("chequeBean");
16. TransactionService tx_Service = (TransactionService) [Link]("proxy");
341
19.
20. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
1. <aop:config>
2. <aop:aspect id="loggingAspect" ref="loggingAspectBean">
3.
4. <aop:pointcut id="loggingOperation" expression="execution(* [Link]
.EmployeeService.*(..))" />
5.
6. </aop:aspect>
7. </aop:config>
8.
9. <bean id="loggingAspectBean" class="[Link]
ct" />
1. execution (* [Link].*(..))
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.
[Link](* 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.
[Link](public * EmployeeService.*(..))
The above Expression matches all public methods of EmployeService interface with any
return type.
[Link](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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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="[Link]
2. xmlns:xsi="[Link]
3. xmlns:aop="[Link]
4. xsi:schemaLocation="[Link]
5. [Link]
6. [Link]
7. [Link] ">
8.
9. <aop:config>
10.
11. <!-- Spring AOP Pointcut definitions -->
12. <aop:pointcut id="loggingOperation"
13. expression="execution(* [Link].*(..))" />
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
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. [Link] = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. [Link] = ename;
346
20. }
21. public float getEsal() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
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. }
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. public class EmployeeServiceImpl implements EmployeeService {
6.
7. @Override
8. public String createEmployee(Employee emp){
9. [Link]("Employee "+[Link]()+" Inserted Successfully from createEm
ployee()");
347
10.
11. return "Success";
Page
12. }
13.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10. import [Link];
11. public class LoggingAspectBean {
12. public void before(JoinPoint jp) {
13. [Link]("Before "+[Link]().getName()+" method execution");
14. }
15. public void after(JoinPoint jp) {
348
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8.
9. public class Test {
10. public static void main(String[] args) {
11. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
[Link]");
12. EmployeeService empService = (EmployeeService)[Link]("empService");
13. Employee emp = (Employee) [Link]("empBean");
14. String message = "";
15. try {
16. message = [Link](emp);
17. } catch (Exception e) {
350
18.
19. }
Page
20. [Link](message);
21. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example:
[Link]
1. package [Link];
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. [Link] = name;
13. }
14. public String getTime() {
15. return time;
16. }
17. public void setTime(String time) {
18. [Link] = time;
19. }
20. public int getPrice() {
21. return price;
22. }
23. public void setPrice(int price) {
24. [Link] = price;
25. }
26. }
[Link]
1. package [Link];
2.
3. import [Link];
4.
351
7. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. public class ShowAspect {
6. public void before() {
7. [Link]("Get Tickets for the Show");
8. }
9. public void around(ProceedingJoinPoint jp) {
10. [Link]("Show is Ready To start, Take Chairs and Keep mobiles in Silent m
ode");
11. try {
12. [Link]();
13. } catch (Throwable e) {
14. [Link]();
15. }
352
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]([Link]))" id="showPointcut"/>
25.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8.
9. public class Test {
10.
11. public static void main(String[] args) {
12. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
[Link]");
13. Show show = (Show) [Link]("showBean");
14. ShowService showService = (ShowService) [Link]("showService");
15. try {
16. [Link](show);
17. } catch (RuntimeException e) {
18. //[Link]([Link]());
19. }
20. }
21. }
Business method.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Note: To activate all the above annotations in Spring applications we have to use <aop:aspectj-
autoproxy/> tag in spring configuration file.
Example:
[Link]
1. package [Link];
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. [Link] = accNo;
14. }
15. public String getAccName() {
16. return accName;
17. }
18. public void setAccName(String accName) {
19. [Link] = accName;
20. }
21. public String getAccType() {
22. return accType;
23. }
355
26. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. public interface TransactionService {
7. public String withdraw(Account acc, int wd_Amt)throws InsufficientFundsException;
8. }
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. import [Link];
6. import [Link];
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([Link]() > wd_Amt) {
15. int total_Bal = [Link]() - wd_Amt;
16. [Link](total_Bal);
356
19. }else {
20. status = "FAILURE";
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. public class InsufficientFundsException extends Exception {
4. public InsufficientFundsException(String desc) {
5. super(desc);
6. }
7. }
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10. import [Link];
11. import [Link];
12.
13. import [Link];
14. import [Link];
15. @Component("aspect")
16. @Aspect
17. public class TransactionAspect {
18. @Before("execution(* [Link].*(..))")
19. public void before(JoinPoint jp) {
20. Object[] args = [Link]();
21. Account acc = (Account) args[0];
357
24.
25. @After("execution(* [Link].*(..))")
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
33. returning="result")
34. public void afterReturning(JoinPoint jp, String result) {
35. [Link]("After Returning Advice: Transaction Status :"+result);
36. }
37.
38. @Around("execution(* [Link].*(..))")
39. public void around(ProceedingJoinPoint jp) {
40. [Link]("Around Advice : Before "+[Link]().getName()+" Method E
xecution");
41. String status = "";
42. try {
43. status = (String)[Link]();
44. } catch (Throwable e) {
45. [Link]();
46. }
47. [Link]("Around Advice : After "+[Link]().getName()+" Method Ex
ecution");
48. [Link]("Around Advice : Transaction Status :"+status);
49. }
50.
51. //@AfterThrowing(pointcut="execution(* [Link].*(..))",
52. //throwing="exception")
53. public void afterThrowing(JoinPoint jp, InsufficientFundsException exception) {
54. [Link]("After Throwing Advice : "+[Link]().getName()+" In Tra
nsaction :"+[Link]());
55. }
56. }
[Link]
358
3. <beans xmlns="[Link]
4. xmlns:xsi="[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
Page
1. package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
360
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
{SPRING ORM}
361
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
362
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
To remove the above boilerplate code, SPRING Framework has provided ORM Module.
Spring has provided the complete ORM module in the form of "[Link]"
package.
To abstract the above boilerplate code Spring-ORM module has provided a predefined class in
the fomr of "[Link]" 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Prepare JAVA project in Eclipse IDE and add the following JAR files to Buildpath in the form of the
following Libraries.
Spring4_Lib:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Hibernate4_Lib:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
jboss-transaction-api_1.2_spec-[Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
45. @Transactional
46. public Employee getStudent(int sid) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
34. <tx:annotation-driven/>
35. <bean id="transactionManager" class="[Link]
Page
nsactionManager">
36. <property name="sessionFactory" ref="sessionFactory"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
The main intention of Client Application is to get Dao object and to access Dao object.
Example:
22. [Link](status);
23. or
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
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. [Link] = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. [Link] = ename;
20. }
21. public float getEsal() {
22. return esal;
23. }
24. public void setEsal(float esal) {
25. [Link] = esal;
26. }
27. public String getEaddr() {
28. return eaddr;
29. }
30. public void setEaddr(String eaddr) {
31. [Link] = 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
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. }
[Link]
1. package [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6.
7. import [Link];
8.
9. public class EmployeeDaoImpl implements EmployeeDao {
10. String status = "";
11. private HibernateTemplate hibernateTemplate;
12. public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
13. [Link] = hibernateTemplate;
14.
15. }
16.
17. @Override
18. @Transactional
19. public String insert(Employee e) {
20. try {
21. [Link](e);
372
24. [Link]();
25. status = "Insertion Failure";
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
65. }
66. return emp;
Page
67. }
68. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
actoryBean">
22. <property name="dataSource" ref="dataSource"/>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6.
7. import [Link];
8. import [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
376
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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[[Link]]
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.
[Link]
1. package [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
1. <hibernate-mapping>
2. <class name="[Link]" 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 [Link]:
Page
1. <persistence>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
[Link]
1. package [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
src/META-INF/[Link]
382
2. <persistence xmlns:xsi="[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. import [Link];
9.
10. public class Test {
11.
12. public static void main(String[] args)throws Exception {
13. EntityManagerFactory factory = [Link]("emp");
14. EntityManager entManager = [Link]();
15. Employee emp = new Employee();
16. [Link](111);
17. [Link]("AAA");
383
18. [Link](5000);
19. [Link]("Hyd");
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. <persistence>
2. <persistence-unit name="std">
3. <class>[Link]</class>
4. ------
5. </persistence-unit>
6. </persistence>
Example:
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
src/META-INF/[Link]
ersistence/persistence_2_0.xsd"
4. version="2.0" xmlns="[Link]
Page
5. <persistence-unit name="emp">
6. <class>[Link]</class>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. import [Link];
9.
10. public class Test {
11.
12. public static void main(String[] args)throws Exception {
13. EntityManagerFactory factory = [Link]("emp");
14. EntityManager entManager = [Link]();
15. Employee emp = new Employee();
16. [Link](111);
17. [Link]("AAA");
18. [Link](5000);
19. [Link]("Hyd");
20. EntityTransaction tx = [Link]();
21. [Link]();
22. [Link](emp);
386
23. [Link]();
24. [Link]("Employee Inserted Succssfully");
Page
25. }
26. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 "[Link]" under src folder and create Entity class.
[Link]
1. package [Link];
2. import [Link];
3. import [Link];
4. import [Link].*;
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
48.
49. public void setEaddr(String eaddr) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Open [Link] file which is existed under"src\META-INF" folder and provide the following
details.
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. import [Link];
389
9.
10. public class Test {
Page
11.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
53. }
54. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Hibernate Library:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Page
1. package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8.
9. import [Link];
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. [Link](emp);
23. status = "SUCCESS";
24. return status;
25. }
26.
27. @Override
392
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
41. </property>
42. </bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
Page
2.
3. import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
44. }
45. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
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. [Link] = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. [Link] = ename;
20. }
21. public float getEsal() {
22. return esal;
23. }
24. public void setEsal(float esal) {
25. [Link] = esal;
26. }
27. public String getEaddr() {
28. return eaddr;
29. }
30. public void setEaddr(String eaddr) {
31. [Link] = 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
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. }
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8.
9. import [Link];
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. [Link](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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
11. </class>
12. </hibernate-mapping>
Page
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
40. </props>
41. </property>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6.
7. import [Link];
8. import [Link];
9.
10. public class Test {
11.
12. public static void main(String[] args) {
13. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
[Link]");
14. EmployeeDao empDao = (EmployeeDao) [Link]("empDao");
15. /*
16. Employee emp = new Employee();
17. [Link](111);
18. [Link]("AAA");
19. [Link](5000);
20. [Link]("Hyd");
21. String status = [Link](emp);
22. [Link](status);
23. */
24. /*
25. Employee emp = [Link](111);
26. [Link]("Employee Details");
27. [Link]("----------------------");
28. [Link]("Employee Number :"+[Link]());
402
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
403
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
{SPRING
TraNSACTIONS}
404
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
405
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link]: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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Transaction tx = null;
1. try{
2. -----
3. tx = [Link]();
4. ----
5. -----
6. [Link]();
7. }catch(Exception e){
8. [Link]();
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
409
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
1. <hibernate-configuration>
2. <session-factory>
3. ----
4. <property name="[Link]>
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: [Link](TransactionDefinition.ISOLATION_DEFAULT);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Spring Framewrk has provided very good suport for Propagation Behaviour in the form of the
following constants from "[Link] .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 [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link] Manager:
Spring Framework has provided Transaction manager in the form of a predefined interfaces
1. [Link]
2. [Link]
3. [Link]
4. [Link]
------
------
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
3. TransactionStatus:
[Link]
1. package [Link];
2. public interface TransactionDao {
3. public String transferFunds(String fromAccount, String toAccount, int transfer_Amt);
4. }
[Link]
415
1. package [Link];
2. import [Link];
3. import [Link];
Page
4. import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
42.
43. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
Page
1. package [Link];
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2. public interface TransactionDao {
3. public String transferFunds(String fromAccount, String toAccount, int transfer_Amt);
4. }
[Link]
1. package [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8.
420
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
20. </bean>
21. <bean id="jdbcTemplate" class="[Link]">
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2. import [Link];
3. import [Link];
4.
5. import [Link];
6.
7. public class Test {
8.
9. public static void main(String[] args) {
10. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
[Link]");
11. TransactionDao tx_Dao = (TransactionDao)[Link]("transactionDao");
12. String status = tx_Dao.transferFunds("abc123", "xyz123", 100);
13. [Link](status);
422
14. }
15. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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"/>
[Link]
1. package [Link];
2. public interface TransactionDao {
3. public String transferFunds(String fromAccount, String toAccount, int transfer_Amt);
4. }
[Link]
1. package [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8.
9.
10. public class TransactionDaoImpl implements TransactionDao {
11.
12. private JdbcTemplate jdbcTemplate;
13. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
14. [Link] = jdbcTemplate;
15. }
16.
17. @Transactional
18. @Override
423
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
23. </bean>
24. <bean id="transactionDao" class="[Link]">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7.
8. public class Test {
9.
10. public static void main(String[] args) {
11. ApplicationContext context = new ClassPathXmlApplicationContext("applicationConte
[Link]");
12. TransactionDao tx_Dao = (TransactionDao)[Link]("transactionDao");
13. String status = tx_Dao.transferFunds("abc123", "xyz123", 100);
14. [Link](status);
15. }
16. }
425
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
{SPRING WEB
MODULE}
426
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
427
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
[Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. View
2. [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] :
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] 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 , [Link] 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>[Link]</servlet-class>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Note: The default name and location of Spring configuration file is under WEB-INF folder with the
name "Servlet_Logical_Name-[Link]", 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/[Link]</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.
[Link]
1. <web-app>
2. <servlet>
3. <servlet-name>dispatcherServlet</servlet-name>
4. <servlet-class>[Link]</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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 "[Link]".
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 [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
“[Link]”.
EX:
1. <beans>
2. -----
3. <bean name=‖/[Link]‖ class=‖[Link]‖/>
4. <bean name=‖/[Link]‖ class=‖[Link]‖/>
5. <bean name=‖handlerMapping‖ class=‖[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
1. <beans>
2. ------
3. <bean name=‖addEmp‖ class=‖[Link]‖/>
4. <bean name=‖searchEmp‖ class=‖[Link]‖/
>
5. <bean name=‖deleteEmp‖ class=‖[Link]‖/>
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. <beans>
2. ------
3. <bean id=‖welcome‖ class=‖[Link]‖/>
4. <bean name=‖hello‖ class=‖[Link]‖/>
5. <bean name=‖handlerMapping‖ class=―[Link].C
ontrollerClassNameHandlerMapping‖/>
6.
7.
8. </beans>
iv. CommonsPathMapHandlerMapping
The [Link] is one of the
implementation of HandlerMapping interface.
To use this HandlerMapping the controller class must have a class level metadata of the form
@[Link]("/[Link]").
We can configure multiple path maps for a single controller.
EX:
1. @[Link](
2. "/[Link]")
3.
4. public class FirstController implements Controller {
5.
441
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. <beans>
2. -----
3. <bean name=‖/[Link]‖ class=‖[Link]‖/>
4. <bean name=‖/[Link]‖ class=‖[Link]‖/>
5. <bean name=‖handlerMapping‖ class=‖[Link]
NameUrlHandlerMapping‖/>
6. <bean id=‖viewResolver‖ class=‖[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
app1
|---[Link]
|---src
| |-----[Link]
|---WEB-INF
|-----[Link]
|-----[Link]
|-----[Link]
|-----classes
|----[Link]
446
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
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. }
[Link]
2. <beans xmlns="[Link]
3. xmlns:xsi="[Link]
Page
4. xmlns:p="[Link]
5. xmlns:context="[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
19. <url-pattern>*.ds</url-pattern>
20. </servlet-mapping>
Page
21. </web-app>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
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. }
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
450
5.
6. import [Link];
Page
7. import [Link];
8.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
451
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Application-3
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7.
8. import [Link];
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. }
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
454
6. import [Link];
7. import [Link];
Page
8.
9. public class WishController implements Controller {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
Application-4:
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
9. <body>
10. <h2>Durga Software Solutions</h2>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8.
9. public class LoginController implements Controller {
10.
11. @Override
12. public ModelAndView handleRequest(HttpServletRequest request, HttpServletRespons
e response) throws Exception {
13. String uname = [Link]("uname");
14. String upwd = [Link]("upwd");
15. ModelAndView mav = null;
16. if([Link]("durga") && [Link]("durga")) {
17. mav = new ModelAndView("success");
18. }else {
19. mav = new ModelAndView("failure");
20. }
21. return mav;
22. }
23. }
[Link]
11.
12. <bean name="/loginpage" class="[Link]"/>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@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=[Link])
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 = [Link])
public String printHello(ModelMap model) {
[Link]("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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
@RequestParam("paramName")
EX:
@Controller
public class LoginController {
@RequestMapping(value="/login", method=[Link])
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=[Link])
public ModelAndView checkLogin(@RequestParameter("uname") String uname,
@RequestParameer("upwd") String upwd, ModelMap map){
------
[Link]("status", "Login SUCCESS");
return new ModelAndView("success");
}
}
[Link]
463
1. <h1>
Page
2. <%
3. String status = [Link]("status");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example-5:
[Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
465
9. import [Link];
10. import [Link];
Page
11.
12.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
16. </bean>
17. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
467
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. <html>
2. <body>
3. <jsp:forward page="hellopage"/>
4. </body>
5. </html>
[Link]
21. </table>
22. </form>
23. </body>
Page
24. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
16. </web-app>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
36. </dependency>
37.
Page
38.
39. <dependency>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
472
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
To prepare Controller classes, Spring framework has provided a set of predefined classes in
"[Link]" 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
1. package [Link];
2.
3.
4. import [Link];
5.
474
6. import [Link];
7. import [Link];
Page
8.
9. import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
17. </bean>
18. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example:
476
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
8. </head>
9. <body>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
1. package [Link];
2.
478
3.
4. import [Link];
Page
5. import [Link];
6.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
24. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 "[Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
29. <tr>
30. <td><input type="submit" value="ADD"/></td>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
484
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
student_edit_form.jsp
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
28. </table>
29. <h3>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8.
9. import [Link];
10. import [Link];
11.
12. public class StudentAction extends MultiActionController {
13. StudentDao studentDao;
14. String status = "";
15. String message = "";
16.
17. public void setStudentDao(StudentDao studentDao) {
18. [Link] = studentDao;
19. }
20.
21. public ModelAndView add(HttpServletRequest request, HttpServletResponse response)
throws Exception{
22. StudentTo sto = new StudentTo();
23. [Link]([Link]("sid"));
24. [Link]([Link]("sname"));
25. [Link]([Link]("saddr"));
26. status = [Link](sto);
27. if([Link]("success")) {
28.
29. message = "Student Added Successfully";
30. }
31. if([Link]("failure")) {
32. message = "Student Insertion Failure";
33. }
489
34. if([Link]("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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
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. [Link]
13. --------------------
14. package [Link];
15.
16. import [Link];
17.
491
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
60. std_Entity.setSname([Link]("SNAME"));
61. std_Entity.setSaddr([Link]("SADDR"));
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
104. }
105.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
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. [Link] = sid;
13. }
14. public String getSname() {
15. return sname;
16. }
17. public void setSname(String sname) {
18. [Link] = sname;
19. }
20. public String getSaddr() {
21. return saddr;
22. }
23. public void setSaddr(String saddr) {
24. [Link] = saddr;
25. }
26.
27.
28. }
[Link]
3. xmlns:xsi="[Link]
4. xmlns:p="[Link]
Page
5. xmlns:context="[Link]
6. xsi:schemaLocation="
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
43.
44. <bean name="/*" class="[Link]">
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
26.
27.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
To run the above application we need the following jar files in web application lib folder.
o [Link]
o [Link]
o [Link]
o [Link]
497
o [Link]
o [Link]
o [Link]
Page
o [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
[Link]
[Link]
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html>
Page
4. <html>
5. <head>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
16. </body>
17. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9.
10.
11. import [Link];
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 = [Link]();
19. String upwd = [Link]();
20. ModelAndView mav = null;
21. if([Link]("durga") && [Link]("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. }
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. public class User implements Serializable{
502
8.
9. public String getUname() {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
12. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
37. </body>
38. </html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
507
1. package [Link];
2.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
508
8. import [Link];
9.
Page
10.
11. import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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 [Link] in web application lib folder and we have to use the following
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
[Link]
[Link]
<beans>
-----
511
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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){
[Link] = 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
<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){
[Link] = married;
}
public boolean isMarried(){
return married;
}
}
EX:
In Command Class:
public class User{
private String maritalStatus;
----
public void setMaritalStatus(String maritalStatus) {
[Link] = maritalStatus;
}
public String getMaritalStatus() {
if(maritalStatus == null || [Link]("")) {
maritalStatus="Not Married";
}
return maritalStatus;
514
}
----
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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");
[Link]("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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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){
[Link] = uworkLocation;
}
public String getUworkLocation(){
return uworkLocation;
}
}
In Controller class:
[Link]("Mumbai");
[Link]("uworkLocation", uworkLocation);
Page
return map;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
In Command Class:
public class User{
private String[] uskillSet;
----
public void setUskillSet(String[] uskillSet){
[Link] = uskillSet;
}
public String[] getUskillSet(){
return uskeillSet;
}
}
EX:
In Command Class:
public class User{
private String[] uhobbies;
----
public void setUhobbies(String[] uhobbies){
[Link] = uhobbies;
}
public String[] getUhobbies(){
return uhobbies;
}
}
In Controller class:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link](―uhobbies‖, uhobbies);
return map;
}
EX:
IN Command Class:
public class User{
private String uprofession;
----
public void setUprofession(String uprofession){
[Link] = 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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){
[Link] = 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link]
9. <body>
10. <jsp:forward page="reg"></jsp:forward>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
35. </tr>
36. <tr>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
78. </tr>
79. <tr>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
75. </h3>
76.
Page
77. </body>
78. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
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. [Link] = uname;
24. }
25. public String getUpwd() {
26. return upwd;
27. }
28. public void setUpwd(String upwd) {
29. [Link] = 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
83.
84. public void setUprofession(String uprofession) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. import [Link];
9. import [Link];
10.
11. import [Link];
12. import [Link];
13. import [Link];
14.
15. import [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
6. xsi:schemaLocation="
7. [Link]
Page
8. [Link]
9. [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
10. <welcome-file>[Link]</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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 "[Link]".
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example:
[Link]
[Link]
4. <html>
5. <head>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
28. </td>
29. </tr>
Page
30. </table>
31. </center>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
33. </form:form>
34. </body>
Page
35. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
43. </body>
44. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. import [Link];
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. }
[Link]
1. package [Link];
2.
3. public class User {
538
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
47.
48.
Page
49. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
540
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
541
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
[Link]
Example:
[Link]
[Link]
10. .error{
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
50. </tr>
51. <tr>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
31. <tr>
32. <td>User Mobile No</td>
Page
33. <td>${[Link]}</td>
34. </tr>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
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. [Link] = uname;
15. }
16. public String getUpwd() {
17. return upwd;
18. }
19. public void setUpwd(String upwd) {
20. [Link] = upwd;
21. }
22. public int getUage() {
23. return uage;
24. }
25. public void setUage(int uage) {
26. [Link] = uage;
27. }
28. public String getUemail() {
29. return uemail;
30. }
31. public void setUemail(String uemail) {
32. [Link] = uemail;
546
33. }
34. public String getUmobile() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. import [Link];
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. }
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6.
7. import [Link];
547
8.
9. public class UserValidator implements Validator {
Page
10.
11. @Override
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
validation_Messages.properties
[Link] = User Name is Required.
[Link] = User Password is required.
[Link] = User Age is Required.
[Link] = User Email Id Required.
548
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link]
<context:component-scan base-package="[Link]"/>
<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) [Link]
3) hibernate-validator-5.x/[Link]
4) [Link]
5) [Link]
Example:
552
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
25. <table>
26. <tr>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
Page
1. package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
41.
42. public String getUname() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
557
1. package [Link];
2.
Page
3.
4. import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
validation_Messages.properties
typeMismatch = {0} is in invalid format
[Link] = User Name is Required.
[Link] = User Password is Required.
[Link] = User Password must be minimum {2} characters and maximum {1}
characters.
558
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example on Data Validations through Java Validation API provided Annotations by using
properties file provided validation Messages:
[Link]
4. <html>
5. <head>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
reg_form.jsp
30. <tr>
31. <td>User Password</td>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
9. <body>
10. <h2 style="color: red;" align="center">Durga Software Solutions</h2>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. import [Link];
563
6. import [Link];
7. import [Link];
Page
8. import [Link];
9.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
48. }
49. public void setUpwd(String upwd) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. import [Link];
6. import [Link];
7. import [Link];
565
8. import [Link];
9. import [Link];
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
error_Messages.properties
typeMismatch = {0} is in invalid format
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Spring Web MVC has provided a set of predefined HandlerMappings in the package like
"[Link]".
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:
[Link]
<beans>
-----
<bean name="handlerMapping"
class="[Link]"/>
<bean name="/welcome" class="[Link]"/>
------
</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
"[Link]" and send its details to DispatcherServlet.
EX: [Link]
568
Example:
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
24. </form>
25. </body>
Page
26. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6.
7. import [Link];
8. import [Link];
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. }
[Link]
570
1. package [Link];
Page
2.
3. import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
20. </bean>
21. </beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. <beans>
2. -----
3. <bean name="wishController" class="[Link]"/>
4. <bean name="welcomeController" class="[Link]"/>
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
"[Link]" from Spring configuration file.
EX:
Example:
[Link]
9. <body>
10. <jsp:forward page="hello"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
4. <html>
5. <head>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6.
7. import [Link];
8.
9. import [Link];
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. }
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8.
575
11. @Override
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
28. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
3. ControllerClassHandlerMapping
[Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
<beans ...>
<bean name="handlerMapping"
class="[Link]"/>
<bean class="[Link]" />
<bean class="[Link]" />
</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="[Link]">
<property name="caseSensitive" value="true"/>
<bean class="[Link]" />
<bean class="[Link]" />
</beans>
EX:
EXAMPLE:
578
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
25. </body>
26. </html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6.
7. import [Link];
8.
9. import [Link];
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
[Link]
Page
1. package [Link];
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
19. <props>
20. <prop key="/hello">helloFormController</prop>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
21. </web-app>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
[Link]
13. <center>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
584
6. import [Link];
7. import [Link];
Page
8. import [Link];
9. import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
22. </property>
23. </bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
19. <url-pattern>/</url-pattern>
20. </servlet-mapping>
Page
21. </web-app>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
28. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link] 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
[Link] interface or extend
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
To configure Interceptor class in Spring configuration file , we have to use the following
approaches.
<beans>
-----
<bean class="[Link]">
<property name="interceptors">
<list>
<ref bean="maintenanceInterceptor" />
<ref bean="executeTimeInterceptor" />
</list>
</property>
</bean>
----
</beans>
<beans>
----
<interceptors>
<interceptor>
<mapping path="/home" />
<beans:bean
class="[Link]"></beans:bean>
</interceptor>
</interceptors>
------
590
</beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
<beans>
-----
<mvc:interceptors>
<bean class="[Link]" />
<mvc:interceptor>
<mvc:mapping path="/AnimalList" />
<bean class="[Link]" />
</mvc:interceptor>
</mvc:interceptors>
-----
</beans>
Example:
[Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
18. </body>
19. </html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10.
11.
12. @Controller
13. @RequestMapping("/wish")
14. public class WishController {
15. @RequestMapping(method=[Link])
16. public String getForm() {
17. return "helloform";
18. }
19.
20. @RequestMapping(method=[Link])
21. public ModelAndView wish(HttpServletRequest request, HttpServletResponse response)
{
22. String uname = [Link]("uname");
23. return new ModelAndView("wish", "uname", uname);
24. }
25. }
[Link]
1. package [Link];
2. import [Link];
3. import [Link];
4.
5. import [Link];
6. import [Link];
7.
8. public class ProcessingTimeInterceptor implements HandlerInterceptor {
593
9.
10. @Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
10. [Link]
11. <context:annotation-config/>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
<beans>
<bean name="viewResolver"
class="[Link]">
<property name="viewClass" value="[Link]"/>
<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 .[Link]
2. [Link]
Example:
[Link]
12. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
9. <body>
10. <h2 style="color: Red;" align="center">Durga Software Solutions</h2>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. import [Link];
11.
12.
13. @Controller
14. @RequestMapping("/hello")
15. public class HelloController {
16. @RequestMapping(method=[Link])
17. public String showForm() {
18. return "helloform";
19. }
20.
21. @RequestMapping(method=[Link])
22. public ModelAndView wish(HttpServletRequest request, HttpServletResponse response
){
23. String uname = [Link]("uname");
24. return new ModelAndView("wish", "uname", uname);
25. }
26. }
[Link]
3. xmlns:xsi="[Link]
4. xmlns:p="[Link]
Page
5. xmlns:context="[Link]
6. xsi:schemaLocation="
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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="[Link]">
<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/[Link]
601
2. <beans xmlns="[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
<beans>
----
<bean name="viewResolver" class="[Link]">
<property name="location" value="/WEB-INF/[Link]"/>
-----
</beans>
Example:
[Link]
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. import [Link];
11.
12.
13. @Controller
14. @RequestMapping("/hello")
15. public class HelloController {
16. @RequestMapping(method=[Link])
17. public String showForm() {
18. return "helloform";
19. }
20.
21. @RequestMapping(method=[Link])
22. public ModelAndView wish(HttpServletRequest request, HttpServletResponse response
){
604
25. }
26. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
18. </beans>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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) = [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX: src/[Link]
helloform.(class)=[Link]
[Link]=/WEB-INF/pages/[Link]
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=" [Link]">
<property name="basename" value="views"/>
</bean>
----
</beans>
Example:
[Link]
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
13. </body>
14. </html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. import [Link];
11.
12. @Controller
13. @RequestMapping("/hello")
14. public class HelloController {
15. @RequestMapping(method=[Link])
16. public String showForm() {
17.
18. return "helloform";
19. }
20. @RequestMapping(method=[Link])
21. public ModelAndView wish(HttpServletRequest request, HttpServletResponse response
){
22. String uname = [Link]("uname");
23. return new ModelAndView("wish", "uname", uname);
24. }
25. }
[Link]
helloform.(class)=[Link]
[Link]=/WEB-INF/pages/[Link]
wish.(class)=[Link]
[Link]=/WEB-INF/pages/[Link]
[Link]
4. xmlns:p="[Link]
5. xmlns:context="[Link]
Page
6. xsi:schemaLocation="
7. [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
To perform File Upload operation in SPring WEB MVC applications, Spring WEB MVC framework
has provided some predefined library in the form of
"[Link]"
If we want to perform Upload operation in Spring WEB MVC applications then we have to use the
following steps.
EX:
[Link]
EX:[Link]:
@Controller
public class UploadController {
-----
@RequestMapping(value="/upload", method=[Link])
public ModelAndView uploadFiles(@RequestParam MultipartFile file) {
611
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
} catch (Exception e) {
status = "FAILURE";
[Link]();
}
return new ModelAndView("status", "status", status);
}
}
EX: [Link]
<bean id="multipartResolver"
class="[Link]"/>
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.
[Link]
[Link]
Example:
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html>
Page
4. <html>
5. <head>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10. import [Link];
11.
12. @Controller
13. public class UploadController {
14. @RequestMapping(value="/upload", method=[Link])
15. public String showUploadForm() {
16. return "uploadform";
17. }
18.
19. @RequestMapping(value="/upload", method=[Link])
20. public ModelAndView uploadFiles(@RequestParam MultipartFile[] file) {
21. String status = "";
22.
23. try {
24. for(MultipartFile multipartFile: file) {
25. String file_Name = [Link]();
26. FileOutputStream fos = new FileOutputStream("E:/uploads/"+file_Name);
27. byte[] bt = [Link]();
28. [Link](bt);
29. status = "SUCCESS";
614
30. }
31.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
16.
17. <bean class = "[Link]">
18. <property name = "prefix" value = "/WEB-INF//" />
19. <property name = "suffix" value = ".jsp" />
20. </bean>
21.
22. </beans>
[Link]
3. <display-name>exception_handling_web</display-name>
4. <welcome-file-list>
Page
5. <welcome-file>[Link]</welcome-file>
6. <welcome-file>[Link]</welcome-file>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
616
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
IN Controller class and in action method we have to use the following steps.
a) Set Content Type as "APPLICATION/OCTET-STREAM".
[Link]("APPLICATION/OCTET-STREM);
b) Set "content-disposition" response header to response object.
[Link]("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 = [Link]()
e) Get bit by bit from FileInputStream and write bit by bit to OutputStream
int val = [Link]();
while(val != -1) {
[Link](val);
val = [Link]();
}
Example:
617
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
Page
1. package [Link];
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Java is providing very good Internationalization support in Java applications due to UNICODE
representations and the predefined library like [Link] and some of the predefined classes
from [Link] 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="[Link]">
<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="[Link]">
<property name="paramName" value="lang" />
</bean>
<bean
class="[Link]">
<property name="interceptors">
<list>
621
</bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 "[Link]
<spring:message code="--"/>
Where code attribute will take key of the message defined in properties file.
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. <beans>
623
erAdapter" />
4.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
6. <html>
7. <head>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
2. pageEncoding="ISO-8859-1"%>
3. <%@taglib uri="[Link] prefix="form" %>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
627
1. package [Link];
2.
Page
3. import [Link];
4. import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
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. [Link] = uname;
14. }
15. public String getUpwd() {
16. return upwd;
17. }
18. public void setUpwd(String upwd) {
19. [Link] = upwd;
20. }
628
23. }
24. public void setUemail(String uemail) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
25.
26. <bean class="[Link]
Page
rMapping">
27. <property name="interceptors">
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
22. </web-app>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 "[Link]
<tiles:insertAttribute name="--"/>
633
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
org\apache\tiles\resources\tiles-config_2_1.dtd
EX:
[Link]
pages names.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. @Controller
2. public class StudentController {
3.
4. @RequestMapping(value="/welcome", method=[Link])
5. public String welcome() {
6. return "welcomeDef";
7. }
8.
9. @RequestMapping(value="/add", method=[Link])
10. public ModelAndView addStudent() {
11. return new ModelAndView("addDef", "student", new Student());
12. }
13.
14. @RequestMapping(value="/search", method=[Link])
15. public ModelAndView searchStudent() {
16. return new ModelAndView("searchDef", "student", new Student());
17. }
18.
19. @RequestMapping(value="/delete", method=[Link])
20. public ModelAndView deleteStudent() {
21. return new ModelAndView("deleteDef", "student", new Student());
22. }
23.
24. @RequestMapping(value="/add", method=[Link])
25. public ModelAndView add(Student student) {
26. String status = [Link](student);
27. return new ModelAndView("statusDef", "status", status);
28. }
29.
30. @RequestMapping(value="/search", method=[Link])
31. public ModelAndView search(Student student) {
32. Student std = [Link]([Link]());
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
[Link]
1. <beans>
2. -----
3. <bean id="viewResolver"
4. class="[Link]">
5. <property name="viewClass">
6. <value>
7. [Link]
8. </value>
9. </property>
10. </bean>
11.
12. <bean id="tilesConfigurer"
13. class="[Link]">
14. <property name="definitions">
15. <list>
16. <value>/WEB-INF/[Link]</value>
17. </list>
18. </property>
19. </bean>
20. ------
638
21. </beans>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
21. </td>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
8. </head>
9. <body>
Page
10. <br>
11. <h3>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
34. </html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
9. </head>
10. <body><br><br>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
21. <tr>
22. <td>Student Address</td>
Page
23. <td>${[Link]}</td>
24. </tr>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8.
9. import [Link];
10. import [Link];
11.
12. @Controller
13. public class StudentController {
14.
15. @Autowired
645
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
Page
1. package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6.
7. import [Link];
8. import [Link];
9. import [Link];
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. [Link]([Link]());
23. [Link]([Link]());
24. [Link]([Link]());
25.
26. String status = [Link](stdEntity);
27. return status;
28. }
647
29.
30. @Override
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4.
5. public interface StudentDao {
6. public String add(StudentEntity stdEntity);
7. public StudentEntity search(String sid);
8. public String delete(String sid);
9. }
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
648
6. import [Link];
7. import [Link];
Page
8. import [Link];
9. import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
48. try {
49. stdEntity = (StudentEntity) [Link]([Link], sid);
Page
50.
51. } catch (Exception e) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
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. [Link] = sid;
13. }
650
16. }
17. public void setSname(String sname) {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
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. [Link] = sid;
24. }
25. public String getSname() {
651
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
28. </tiles-definitions>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
38. </bean>
39.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
org/xml/ns/javaee [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
To run this application we have to use the following JARs in web application lib folder.
Spring JARS:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
655
[Link]
[Link]
Page
[Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Jstl Jars
[Link]
[Link]
Hibernate Jars:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
jboss-transaction-api_1.2_spec-[Link]
[Link]
[Link]
[Link]
Page
[Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Spring_Struts Integration:
Struts Overview:
implementation
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: [Link]
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: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
2. Deployment Descriptor:
Deployment descriptor is [Link] 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, [Link] file will provide the following configuration details.
1. <web-app>
660
2. <servlet>
3. <servlet-name>actionServlet</servlet-name>
Page
4. <servlet-class>[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link] .
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EXAMPLE:
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: [Link]
[Link]
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
"[Link]" 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
Steps:
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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="./[Link]">|User Login Form|</a>
15. </h5>
666
16. </body>
17. </html>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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="./[Link]">|User Login Form|</a>
15. </h5>
16. </body>
17. </html>
[Link]
1. package [Link];
2.
3. import [Link];
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. [Link] = uname;
14. }
15. public String getUpwd() {
16. return upwd;
17. }
667
20. }
21. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10.
11. import [Link];
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 = [Link]();
19. String upwd = [Link]();
20. String status = "";
21. if([Link]("durga") && [Link]("durga")) {
22. status = "success";
23. }else {
24. status = "failure";
25. }
26. return [Link](status) ;
27. }
28. }
[Link]
6. <form-beans>
7. <form-bean name="loginForm" type="[Link]"/>
Page
8. </form-beans>
9. <action-mappings>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
[Link]
[Link]
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 [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
"[Link]" with the property "contextConfigLocation"
inorder to provide name and location of the Spring configuration.
<struts-config>
<form-beans>
<form-bean name="loginActionForm"
type="[Link]"/>
</form-beans>
<action-mappings>
<action path="/login" name="loginActionForm"
type="[Link]">
<forward name="success" path="/[Link]"/>
<forward name="failure" path="/[Link]"/>
</action>
</action-mappings>
<plug-in className="[Link]">
<set-property property="contextConfigLocation" value="/WEB-
INF/[Link]" />
</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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
<web-app>
<display-name>struts_spring_app</display-name>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>actionServlet</servlet-name>
<servlet-class>[Link]</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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
1. package [Link];
2.
3. import [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10.
11. import [Link];
12. import [Link];
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 = [Link]();
23. String upwd = [Link]();
24. UserService userService = (UserService) getWebApplicationContext().getBean("user
Service");
676
27. }
28. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. public class UserService {
4. String status = "";
5. public String checkLogin(String uname, String upwd) {
6. if([Link]("durga") && [Link]("durga")) {
7. status = "success";
8. }else {
9. status = "failure";
10. }
11. return status;
12. }
13. }
[Link]
[Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
678
[Link]
[Link]
Page
[Link]
[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example:
1. package [Link];
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. [Link] = uname;
12. }
13. public String getUpwd() {
14. return upwd;
15. }
16. public void setUpwd(String upwd) {
17. [Link] = upwd;
18. }
19.
20. public String checkLogin() {
21. if([Link]("durga") && [Link]("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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
In general, in web applications, deployement descriptor is [Link] 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>[Link]</servlet-class>
Page
5. <load-on-startup>1</load-on-startup>
6. </servlet>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Example:
[Link]
[Link]
16.
17. <h:outputText value="Password"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
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. [Link] = uname;
12. }
13. public String getUpwd() {
14. return upwd;
15. }
16. public void setUpwd(String upwd) {
17. [Link] = upwd;
18. }
19.
20. public String checkLogin() {
21. if([Link]("durga") && [Link]("durga")) {
22. return "success";
23. }else {
24. return "failure";
25. }
26. }
27. }
[Link]
7. version="1.2">
8. <managed-bean>
Page
9. <managed-bean-name>loginBean</managed-bean-name>
10. <managed-bean-class>[Link]</managed-bean-class>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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 [Link]
EX:
689
1. <faces-config>
Page
2. ------
3. <managed-bean>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Note: The main intention providing Spring Service Bean in [Link] 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. [Link]
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 [Link] file
EX:
[Link]
1. <web-app>
2. -------
3. <listener>
4. <listener-class>
5. [Link]
6. </listener-class>
7. </listener>
690
8.
9. <listener>
Page
10. <listener-class>
11. [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Note: These Listeners are used to load the complete Spring context at the time of Startup the
Server.
Example:
[Link]
[Link]
12. <center>
13. <h:panelGrid columns="2" >
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
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. [Link] = uname;
15. }
16. public String getUpwd() {
17. return upwd;
18. }
19. public void setUpwd(String upwd) {
20. [Link] = upwd;
21. }
22.
23. public void setUserService(UserService userService) {
24. [Link] = userService;
25. }
26. public UserService getUserService() {
27. return userService;
28. }
29.
30. public String login() {
31. return [Link](uname, upwd);
32. }
33. }
693
[Link]
Page
1. package [Link];
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
14. <managed-bean-name>loginBean</managed-bean-name>
15. <managed-bean-class>[Link]</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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
18.
19. <!-- Add Support for Spring -->
Page
20. <listener>
21. <listener-class>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
SF Jars:
jsf1.2\[Link]
[Link]
[Link]
[Link]
Spring JARs:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
696
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
MAVEN
COURSE MATERIAL
BY
NAGOOR BABU
697
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
698
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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>[Link]
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 [Link] file.
703
1. <repositories>
2. <repository>
Page
3. <id>[Link]</id>
4. <url>[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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>[Link]</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
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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>[Link]</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>[Link]</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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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\[Link]\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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. <dependencyManagement>
2. <dependencies>
3. <dependency>
4. <groupId>[Link]</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>[Link]</groupId>
5. <artifactId>my-parent</artifactId>
Page
6. <version>0.0.1-SNAPSHOT</version>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Note: In JAVA, [Link] 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>[Link]</groupId>
3. <artifactId>MavenExamples</artifactId>
4. <version>0.0.1-SNAPSHOT</version>
5. <relativePath>../baseapp/[Link]</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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link] 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:
[Link]: Generate a list of recent changes from your SCM[Software Configuration
Management].
[Link]: Generate a report from an issue tracker or a change document.
[Link]: Generate Javadoc for the project.
[Link]-info-resports: Generate standard project reports.
[Link]-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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Where each and every profile has its own id, it can be used to access the respective environment
or profile.
In src/main/resources/[Link]
[Link] = ${[Link]}
If we provide the above setups like above then at compilation time, the respective jdbc URL will be
injected to the "[Link]" property depending on the target environment.
Use the following command on command prompt inorder to compile the project.
C:/apps>mvn compile
Here "[Link]" 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 "[Link]" property depending on the target environment.
Use the following command on command prompt inorder to compile the project.
C:/apps>mvn compile
Here "[Link]" property will take "jdbc:oracle:thin:@localhost:1521:xe" value.
712
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
| | |----[Link]
| |---test
| |----java
| |---com
| |----durgasoft
| |-----[Link]
|---[Link]
[Link]
1. package [Link];
2.
3. /**
4. * Hello world!
714
5. *
6. */
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import static [Link];
4.
5. import [Link];
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. [Link]("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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
E:\mvn_projects\sampleapp>mvn test
c) version: 0.0.1-SNAPSHOT
d) package: [Link]
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
33. <target>1.8</target>
34. </configuration>
Page
35. </plugin>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
src/test/java/[Link]
1. package [Link];
2. import [Link];
3. import [Link];
4. import [Link];
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( [Link] );
14. }
15. public void testApp()
16. {
17. [Link]("Hello Maven!");
18. assertTrue( true );
19. }
20. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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
| | |----[Link]
| | |----[Link]
719
│ └───test
│ └───java
│ └───com
Page
│ └───durgasoft
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
33. <plugin>
34. <groupId>[Link]</groupId>
Page
35. <artifactId>maven-compiler-plugin</artifactId>
36. <version>3.7.0</version>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. public class JdbcApp {
9. Connection con;
10. Statement st;
11. ResultSet rs;
12. public JdbcApp() {
13. try {
14. [Link]("[Link]");
15. con = [Link]("jdbc:oracle:thin:@localhost:1521:xe", "system
", "durga");
16. st = [Link]();
17. } catch (Exception e) {
18. [Link]();
19. }
20. }
21. public void displayEmpDetails() {
22. try {
23. rs = [Link]("select * from emp1");
24. [Link]("ENO\tENAME\tESAL\tEADDR");
25. [Link]("------------------------------");
26. while([Link]()) {
27. [Link]([Link](1)+"\t");
721
28. [Link]([Link](2)+"\t");
29. [Link]([Link](3)+"\t");
Page
30. [Link]([Link](4));
31. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. import [Link];
9. import [Link];
10. import [Link];
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( [Link] );
Page
34. }
35.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: [Link]
Driver UIRL: jdbc:mysql://localhost:3306/durgadb
DB User Name: root
DB Password : root
Example:
[Link]
8. <packaging>jar</packaging>
9.
Page
10. <name>helloapp</name>
11. <url>[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
51. </plugins>
52. </build>
Page
53. </project>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. public class JdbcApp {
9. Connection con;
10. Statement st;
11. ResultSet rs;
12. public JdbcApp() {
13. try {
14. [Link]("[Link]");
15. con = [Link]("jdbc:mysql://localhost:3300/durgadb", "root", "
root");
16. st = [Link]();
17. } catch (Exception e) {
18. [Link]();
19. }
20. }
21. public void displayEmpDetails() {
22. try {
23. rs = [Link]("select * from emp1");
24. [Link]("ENO\tENAME\tESAL\tEADDR");
25. [Link]("------------------------------");
26. while([Link]()) {
27. [Link]([Link](1)+"\t");
28. [Link]([Link](2)+"\t");
29. [Link]([Link](3)+"\t");
30. [Link]([Link](4));
31. }
32. } catch (Exception e) {
33. [Link]();
34. }
35. }
36. }
725
[Link]
Page
1. package [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
43. [Link]();
44. /*
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
727
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. <plugin>
2. <groupId>[Link]</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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. <plugin>
2. <groupId>[Link]</groupId>
3. <artifactId>tomcat7-maven-plugin</artifactId>
4. <version>2.2</version>
5. </plugin>
1. <dependency>
2. <groupId>[Link]</groupId>
3. <artifactId>[Link]-api</artifactId>
4. <version>3.1.0</version>
5. <scope>provided</scope>
6. </dependency>
EX: [Link]
7. <version>0.0.1-SNAPSHOT</version>
8. <name>loginapp Maven Webapp</name>
Page
9. <url>[Link]
10. <dependencies>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX: [Link]
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. [Link]
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="./[Link]">|User Login Form|</a>
13. </h3>
14. </body>
15. </html>
16.
17. [Link]
731
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
b) Prepare Servlets:
EX: [Link]
732
1. package [Link];
Page
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. public class UserService {
9. Connection con;
10. Statement st;
11. ResultSet rs;
12. String status = "";
13. public UserService() {
14. try {
15. [Link]("[Link]");
734
17. st = [Link]();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
4. Update Project:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
1. <build>
2. <plugins>
3. <plugin>
4. <groupId>[Link]</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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
1. <dependencies>
2. <dependency>
3. <groupId>[Link]</groupId>
4. <artifactId>spring-core</artifactId>
5. <version>[Link]</version>
6. </dependency>
7.
8. <dependency>
9. <groupId>[Link]</groupId>
10. <artifactId>spring-context</artifactId>
11. <version>[Link]</version>
12. </dependency>
13.
14. <dependency>
15. <groupId>[Link]</groupId>
16. <artifactId>spring-aop</artifactId>
17. <version>[Link]</version>
18. </dependency>
19. </dependencies>
Note: In the above dependencies, just add spring-core and spring-context dependencies in
[Link] file then automatically all other dependencies are also be loaded.
EX: [Link]
3. <modelVersion>4.0.0</modelVersion>
4.
5. <groupId>[Link]</groupId>
Page
6. <artifactId>springapp1</artifactId>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
46. <groupId>[Link]</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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX: [Link]
1. package [Link];
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX: [Link]
EX:[Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7.
740
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:[Link]
1. package [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
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( [Link] );
17. }
18.
19. public void testApp()
20. {
21. TestClient client = new TestClient();
22. [Link]();
23.
24. assertTrue( true );
25. }
26. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
LOG4J
COURSE MATERIAL
BY
NAGOOR BABU
742
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
743
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
744
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
1. class Transaction{
2. void deposit(){
3. [Link]("logic for deposit");
4. }
5. void withdraw(){
6. [Link]("logic for withdraw");
7. }
8. void transfer(){
9. [Link]("logic for transfer");
10. }
11. }
12. class Test{
13. Transaction tx = new Transaction();
14. [Link]("Before deposit() method call");
15. [Link]()
16. [Link]("After deposit() method call");
17. -----
18. [Link]("Before withdraw() method call");
19. [Link]();
20. [Link]("After withdraw method call");
21. ------
22. [Link]("Before transfer() method call");
23. [Link]();
24. [Link]("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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
If we use [Link]() method in applications to trace flow of execution then we are able to
get the following problems.
1. [Link](--) 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. [Link]() 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 [Link]() methods in
applications, because, it will reduce application performance.
4. [Link]() method is usefull in Development environment only, It is not suitable in
production environment , because, if we use [Link]() method in server side
applications then it will display messages in servers console only, it will not be avaiable to
users.
5. [Link]() will display the messages on console or on command prompt, it will not
show differences in Error messages, warning messaages, normal information,....
6. [Link]() 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link] 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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.
[Link]
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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
In Log4j , we are able to use the following two types of configuration files.
[Link]
[Link]
IN both the configuratin files, we have to use the following configurations at basic java
applications.
EX: [Link]:
Where "[Link]" 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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
Note: Where %m%n in the sense, %m is to display message and %n is to bring cursor to next
line.
[Link] 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 [Link] file.
[Link]
10. </appender>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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, "[Link]"
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,
"[Link]".
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:
[Link]
[Link] = [Link]
[Link] = %d{yyyy-mm-dd hh:mm:ss } : This is
%m%n
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package log4japp1;
2.
3. import [Link];
4. import [Link];
5.
6. public class Log4jTest {
7.
8. public static void main(String[] args) {
9. Logger logger = [Link]([Link]);
10. [Link]("trace Message");
11. [Link]("debug Message");
12. [Link]("info Message");
13. [Link]("warn Message");
14. [Link]("Error Message");
15. [Link]("fatal Message");
16.
17. }
18. }
Note: If we want to use XML configuration then we have to use the following XML file
[Link]
15. </root>
16.
Page
17. </log4j:configuration>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 [Link] file.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. [Link]
2. [Link].Ref_Name
3. [Link].Ref_Name.File : It will name and location of the file to manage logging
messages.
4. [Link].Ref_Name.layout
5. [Link].Ref_Name.[Link]
EX:
[Link]
[Link]
1. package log4japp1;
2.
3. import [Link];
4. import [Link];
5.
6. public class Log4jTest {
7.
8. public static void main(String[] args) {
9.
10. Logger logger = [Link]([Link]);
11. [Link]("trace Message");
12. [Link]("debug Message");
13. [Link]("info Message");
14. [Link]("warn Message");
15. [Link]("Error Message");
16. [Link]("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 '[Link]' property.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
[Link]
#ConsoleAppender Configuration
[Link] = [Link]
[Link] = [Link]
[Link] = %d{yyyy-mm-dd hh:mm:ss } %-c %p
: This is %m%n
#FileAppender Configuration
[Link] = [Link]
[Link]=./logging/[Link]
[Link] = [Link]
[Link] = %d{yyyy-mm-dd hh:mm:ss } %-c %p :
This is %m%n
[Link]
1. package log4japp1;
2.
3. import [Link];
4. import [Link];
5.
6. public class Log4jTest {
7.
8. public static void main(String[] args) {
9.
10. Logger logger = [Link]([Link]);
11. [Link]("trace Message");
12. [Link]("debug Message");
13. [Link]("info Message");
14. [Link]("warn Message");
15. [Link]("Error Message");
16. [Link]("fatal Message");
757
17.
18. }
Page
19. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
EX:
[Link]
#FileAppender Configuration
[Link] = [Link]
[Link]= e:/loggers/[Link]
[Link]= 2kb
[Link]= 3
[Link] = [Link]
[Link] = %d{yyyy-mm-dd hh:mm:ss } %-c %p :
This is %m%n
[Link]
1. package log4japp1;
2.
3. import [Link];
4. import [Link];
5.
6. public class Log4jTest {
7. static Logger logger = [Link]([Link]);
8. public static void main(String[] args) {
9.
10. [Link]("trace Message");
758
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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:
[Link]
#FileAppender Configuration
[Link] = [Link]
[Link]= e:/loggers/[Link]
[Link]='.' yyyy-MM-dd-HH-mm
#[Link]= 2kb
#[Link]= 3
759
[Link] = [Link]
[Link] = %d{yyyy-mm-dd hh:mm:ss } %-c %p :
Page
This is %m%n
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package log4japp1;
2.
3. import [Link];
4. import [Link];
5.
6. public class Log4jTest {
7. static Logger logger = [Link]([Link]);
8. public static void main(String[] args) {
9.
10.
11. [Link]("trace Message");
12. [Link]("debug Message");
13. [Link]("info Message");
14. [Link]("warn Message");
15. [Link]("Error Message");
16. [Link]("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: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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, [Link]
EX:
[Link]
[Link]
1. package [Link].log4j;
2. import [Link];
3. import [Link];
4.
5. public class Log4jTest {
6. static Logger logger = [Link]([Link]);
7. public static void main(String[] args) {
8. [Link]("Trace Message");
9. [Link]("Debug Message");
10. [Link]("Info Message");
11. [Link]("Warn Message");
761
15. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 "[Link]".
To define pattern for the logging messages, we must use "ConversionPattern" property from
PatternLayout class.
EX:
[Link]
[Link]
1. package [Link].log4j;
2.
3. import [Link];
4. import [Link];
5.
6. public class Log4jTest {
762
9. [Link]("Trace Message");
10. [Link]("Debug Message");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
OP:
22/08/2018 [Link] [Link].log4j.Log4jTest TRACE : This Is Trace Message
22/08/2018 [Link] [Link].log4j.Log4jTest DEBUG : This Is Debug Message
22/08/2018 [Link] [Link].log4j.Log4jTest INFO : This Is Info Message
22/08/2018 [Link] [Link].log4j.Log4jTest WARN : This Is Warn Message
22/08/2018 [Link] [Link].log4j.Log4jTest ERROR : This Is Error Message
22/08/2018 [Link] [Link].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 "[Link]"
EX:
[Link]
[Link]
Page
1. package [Link].log4j;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
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 "[Link]"
EX:
[Link]
[Link]
1. package [Link].log4j;
2. import [Link];
3. import [Link];
4.
5. public class Log4jTest {
6. static Logger logger = [Link]([Link]);
7. public static void main(String[] args) {
8. [Link]("Trace Message");
764
9. [Link]("Debug Message");
10. [Link]("Info Message");
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. import [Link];
9. import [Link];
10.
11. public class Test {
12. //static Logger logger = [Link]([Link]);
13. static Logger logger = [Link]([Link]);
14. public static void main(String[] args) {
15. [Link]("Application Starting Point");
16. Connection con = null;
17. Statement st = null;
18. ResultSet rs = null;
19. try {
20. [Link]("[Link]");
21. [Link]("Driver Loaded");
22. con = [Link]("jdbc:oracle:thin:@localhost:1521:xe", "system
765
", "durga");
23. if(con == null) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
64. }
65. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
767
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
768
2. <web-app xmlns:xsi="[Link]
instance" xmlns="[Link] xsi:schemaLocation="[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
[Link]
1. package [Link];
2.
3. import [Link];
769
4.
5. import [Link];
Page
6. import [Link];
7. import [Link];
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
[Link]
1. package [Link];
2. import [Link];
3.
4. import [Link];
770
5.
6. public class UserService {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]
771
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
+91- 7207 21 24 27/28 WEBSITE: [Link]