Sunteți pe pagina 1din 195

Advanced Java

INDEX
Part No

Contents

Page no.

JSP Introduction
1. JSP Tutorial
2. JSP Scripting Elements
3. JSP Implicit Object
4. JSP Directive
5. JSP Exception
6. Action Elements
7. Expression language
8. MVC in JSp
9. JSTL
10. JSTL Custom Tag
11. Development in JSP
JSP INTERVIEW QUESTION

4
5
18
22
23
27
33
40
43
47
50
64
71

Servlet Tutorial
1. Servlet API
2. Servlets Interface
3. Http Servlets Class

75
82
84
87

3.

Hibernate introduction
1. Introduction
2. Hibernate in IDE
3. Hibernate Example
4. Hibernate Log4j
5. Inheritance mapping
6. Collection Mapping

101
102
105
109
122
124
138

7. Assciation Mapping
8. Transaction management
9. Hibernate Query Language
10.Hibernate Criterion Query
Language
11. Named Query
Hibernate Interview Question

181
189
191
193

4.
2
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

195
214

Spring Tutorial
1. Spring introduction
2. Spring IDE
3. Dependency Injection
4. Spring AOP
5. Spring JDBC Template
6. SPEL
7. Spring ORM
8. Spring MVC
9. Spring Remoting
10. Spring OXM
11. Spring JAVA Mail
12. Spring WEB
Spring Interview Questions
Spring JDBC interview Question
Spring AOP interview Question
Spring MVC interview Question
5.

1. Struts 2 tutorial
2. Core Components of struts
4. Struts Architecture
5. Struts2 Action
6. Struts2 Configuration
7. Interceptor
8. Struts2 Validation
9. AwareInterfaces
10.Struts2 with I18N
11.Zero Configuration
12.Struts with Tiles2
13.Development
Interview Question

3
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

218
219
221
226
260
287
293
296
307
320
335
343
349
355

360
364
367
369
371
374
381
383
392
399
403
419
426

1-JSP Introduction

4
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

The jsp:forward action tag is used to forward the request to another resource it may be jsp, html
or anotherTutorial
resource.
1.JSP
Syntax of jsp:forward action tag without parameter

JSP expression tag

<jsp:forward page="relativeURL | <%= expression %>" />


The code placed within JSP expression tag is written to the output stream of the response. So
Syntax
action
tag data.
withItparameter
you need of
notjsp:forward
write out.print()
to write
is mainly used to print the values of variable or
method.
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param
Syntax ofname="parametername"
JSP expression tag value="parametervalue | <%=expression%>" />
</jsp:forward>
JSP technology is used to create web application just like Servlet technology. It can be thought
<%= statement %>
of as an extension to servlet because it provides more functionality than servlet such as
<%= statement %>
expression language, jstl etc.
Example of JSP expression tag
A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than
Example of jsp:forward action tag without parameter
servlet
because we
canexpression
separate designing
andsimply
development.
It provides
some
additional features
In this example
of jsp
tag, we are
displaying
a welcome
message.
such
Expression
Tag the
etc.request to the printdate.jsp file.
In thisasexample,
weLanguage,
are simplyCustom
forwarding
<html>
index.jsp
<body>
<%= "welcome to jsp" %>
Advantage
of JSP over Servlet
<html>
</body>
<body>
</html>
There are many advantages of JSP over servlet. They are as follows:
<h2>this
<html> is index page</h2>
<jsp:forward
page="printdate.jsp" />
<body>
1) Extension to Servlet
</body>
<%= "welcome to jsp" %>
</html>
</body>
JSP technology is the extension to servlet technology. We can use all the features of servlet in
</html>
JSP. In addition to, we can use implicit objects, predefined tags, expression language and
printdate.jsp
Custom tags in JSP, that makes JSP development easy.
Note: Do not end your statement with semicolon in case of expression tag.

<html>
2) Easy to maintain
<body>
Example of JSP expression tag that prints current time
<%
is:"+java.util.Calendar.getInstance().getTime());
%> logic with presentation
JSP out.print("Today
can be easily managed
because we can easily separate our business
To
display
the current
time, we
used
the getTime()
method
of Calendarlogic.
class. The getTime()
</body>
logic.
In servlet
technology,
we have
mix our
business
logic with
the presentation
is an instance method of Calendar class, so we have called it after getting the instance of Calendar
</html>
class
by Development:
the getInstance()No
method.
3)
Fast
need to recompile and redeploy
Example of jsp:forward action tag with parameter
index.jsp
If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code
In
thistoexample,
weand
arerecompiled
forwardingif we
the have
request
to the the
printdate.jsp
fileofwith
parameter and
needs
be updated
to change
look and feel
the application.
<html>
printdate.jsp
file prints the parameter value with date and time.
4) Less code than Servlet
<body>
index.jsp
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
In
JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code.
</body>
Moreover,
<html>
</html> we can use EL, implicit objects etc.
5
<body>
<html>
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
<h2>this
page</h2>
<body> 2isndindex
Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
<jsp:forward
>
Current Time:page="printdate.jsp"
<%= java.util.Calendar.getInstance().getTime()
%>
.MobileNo:9328994901
Life
cycle
of
a
JSP
Page
<jsp:param
name="name"
value="javatpoint.com"
/>
</body>
</jsp:forward>
</html>
The JSP pages follows these phases:

Example of JSP expression tag that prints the user name


In this example, we are printing the username using the expression tag. The index.html file gets
the username and sends the request to the welcome.jsp file, which displays the username.
File: index.jsp

3-JSP Implicit Object


9)
exception implicit object
<html>
<body>
In JSP, exception is an implicit object of type java.lang.Throwable class. This object can be used
<form action="welcome.jsp">
to print the exception. But it can only be used in error pages.It is better to learn it after page
<input type="text" name="uname"><br/>
directive. Let's see a simple example:
<input type="submit" value="go">
</form>
</body>
Example of exception implicit object:
</html>
<html>
error.jsp
<body>
<form page
action="welcome.jsp">
<%@
isErrorPage="true" %>
<input type="text" name="uname"><br/>
<html>
<input type="submit" value="go">
<body>
</form>
Sorry following exception occured:<%= exception %>
</body>
</html>
<%@ page isErrorPage="true" %>
File: welcome.jsp
<html>
<body>
<html>
Sorry following exception occured:<%= exception %>
<body>
</body>
<%=
"Welcome "+request.getParameter("uname") %>
</html>
</body>
</html>
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>

6
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
JSP Declaration
Tag
.MobileNo:9328994901
The JSP declaration tag is used to declare fields and methods.

generated servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:


<%! field or method declaration %>
Difference between JSP Scriptlet tag and Declaration tag

4-JSP Directive

Jsp Scriptlet Tag


Jsp Declaration Tag
The jsp scriptlet tag can only declare variables The jsp declaration tag can declare variables as
not methods.
well as methods.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is placed
inside the _jspService() method.
outside the _jspService() method.
Example of JSP declaration tag that declares field
In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example of JSP declaration tag that declares method
In this example of JSP declaration tag, we are defining the method which returns the cube of
given number and calling this method from the jsp expression tag. But we can also use jsp
scriptlet tag to call the declared method.
index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
7
%> B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
<%= "Cube
ndof 3 is:"+cube(3) %>
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
</body>
.MobileNo:9328994901
</html>

JSP directives
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
There are three types of directives:
page directive
include directive
taglib directive
Syntax of JSP Directive6
<%@ directive attribute="value" %>

JSP page directive


The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>
Attributes of JSP page directive
import
contentType
extends
info
buffer
language
isELIgnored
isThreadSafe
autoFlush
session
pageEncoding
errorPage
isErrorPage
1)import
The import attribute is used to import class,interface or all the members of a package.It is
similar to import keyword in java class or interface.
8
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
Example
of
import
attribute
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
<html>
<body>

5-JSP Exception

9
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Exception Handling in JSP


The exception is normally an object that is thrown at runtime. Exception Handling is the process
to handle the runtime errors. There may occur exception any time in your web application. So
handling exceptions is a safer side for the web developer. In JSP, there are two ways to perform
exception handling:
By errorPage and isErrorPage attributes of page directive
By <error-page> element in web.xml file
Example of exception handling in jsp by the elements of page directive:
In this case, you must define and create a page to handle the exceptions, as in the error.jsp page.
The pages where may occur exception, define the errorPage attribute of page directive, as in the
process.jsp page.
There are 3 files:
index.jsp for input values
process.jsp for dividing the two numbers and displaying the result
error.jsp for handling the exception
index.jsp

<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
process.jsp

<%@ page errorPage="error.jsp" %>


<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
10
B-208
Manubhai
, Sayajigunj
MobileNo:9327219987
Exception
is: <%=
exceptionTower
%>
nd
Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
Output of2
this example:
.MobileNo:9328994901

JSP Action Tags


There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action
tags are given below.
JSP
Tags

Action Description

jsp:forward

forwards the request and response to another


resource.

jsp:include

includes another resource.

jsp:useBean

creates or locates bean object.

jsp:setProperty

sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.


jsp:plugin

embeds another components such as applet.

jsp:param

sets the parameter value. It is used in forward and


include mostly.

jsp:fallback

can be used to print the message if plugin is working.


It is used in jsp:plugin.

The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development. So we
will see these tags in bean developement.

jsp:forward action tag


11
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

12
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

6-Action Element

13
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

jsp:include action tag


The jsp:include action tag is used to include the content of another resource it may be jsp, html
or servlet.
The jsp include action tag includes the resource at request time so it is better for dynamic pages
because there might be changes in future.
The jsp:include tag can be used to include static as well as dynamic pages.
Advantage of jsp:include action tag
Code reusability : We can use a page many times such as including header and footer pages in
all pages. So it saves a lot of time.
Difference between jsp include directive and include action
JSP include directive

JSP include action

includes resource at translation time.

includes resource at request


time.

better for static pages.

better for dynamic pages.

includes the original content in the generated calls the include method.
servlet.
Syntax of jsp:include action tag without parameter
<jsp:include page="relativeURL | <%= expression %>" />
Syntax of jsp:include action tag with parameter
<jsp:include page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:include>
Example of jsp:include action tag without parameter
In this example, index.jsp file includes the content of the printdate.jsp file.
File: index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
File: printdate.jsp
14
B-208 Manubhai
Tower , Sayajigunj
MobileNo:9327219987
<% out.print("Today
is:"+java.util.Calendar.getInstance().getTime());
%>
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Displaying applet in JSP (jsp:plugin action tag)


The jsp:plugin action tag is used to embed applet in the jsp file. The jsp:plugin action tag
downloads plugin at client side to execute an applet or bean.
Syntax of jsp:plugin action tag:
<jsp:plugin type= "applet | bean" code= "nameOfClassFile"
codebase= "directoryNameOfClassFile"
</jsp:plugin>
Example of displaying applet in JSP:
In this example, we are simply displaying applet in jsp using the jsp:plugin tag. You must have
MouseDrag.class file (an applet class file) in the current folder where jsp file resides. You may
simply download this program that contains index.jsp, MouseDrag.java and MouseDrag.class
files to run this application.
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Mouse Drag</title>
</head>
<body bgcolor="khaki">
<h1>Mouse Drag Example</h1>
<jsp:plugin align="middle" height="500" width="500"
type="applet" code="MouseDrag.class" name="clock" codebase="."/>
</body>
</html>

7-Expression Language

15
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Expression Language (EL) in JSP


The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean
component, and other objects like request, session, application etc.
There are many implicit objects, operators and reserve words in EL.
It is the newly added feature in JSP technology version 2.0.
Syntax for Expression Language (EL):
${ expression }
Implicit Objects in Expression Language (EL):
There are many implicit objects in the Expression Language. They are as follows:
Implicit
Usage
Objects
pageScope

it maps the given attribute name with the value set in


the page scope

requestScope

it maps the given attribute name with the value set in


the request scope

sessionScope

it maps the given attribute name with the value set in


the session scope

applicationScop it maps the given attribute name with the value set in
e
the application scope
Param

it maps the request parameter to the single value

paramValues

it maps the request parameter to an array of values

Header

it maps the request header name to the single value

headerValues

it maps the request header name to an array of


values

Cookie

it maps the given cookie name to the cookie value

initParam

it maps the initialization parameter

pageContext

it provides access to many objects request, session


etc.
Simple example of Expression Language that prints the name of the user
In this example, we have created two files index.jsp and process.jsp. The index.jsp file gets input
from the user and sends the request to the process.jsp which in turn prints the name of the user
[] .
()

9.JSTL
-(unary) not ! empty
JSTL
(JSP
* / div %
modStandard Tag Library)

The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
+ - (binary)
Advantage
<<= >>= ltof
le JSTL:
gt ge
Fast Developement JSTL provides many tags that simplifies the JSP.
Code
Reusability
We can use the JSTL tags in various pages.
== !=
eq ne
16
No need
to
use
scriptlet
tag
It
avoids
the
use
of
scriptlet
tag.
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
&& and nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
There JSTL mainly provides 5 types of tags:
.MobileNo:9328994901
|| or
Tag Name
Description
?: core tags
The JSTL core tag provide variable support, URL management,

index.jsp
<form action="process.jsp">
Enter Name:<input type="text" name="name" /><br/><br/>
<input type="submit" value="go"/>
</form>

process.jsp
10-JSTL
Welcome, ${CUSTOM
param.name } TAG

Custom Tags in JSP

Custom
are user-defined
tags.that
They
eliminates
of scriptlet
Exampletags
of Expression
Language
prints
the valuethe
setpossibility
in the session
scope tag and separates the
business
logic from
JSP page.
In this example,
wethe
printing
the data stored in the session scope using EL. For this purpose, we
The
logic can
be used many times by the use of costom tag.
havesame
usedbusiness
sessionScope
object.
index.jsp
Advantages
of Custom
<h3>welcome
to indexTags:
page</h3>
The
key
advantages
of
Custom
tags are as follows:
<%
Eliminates
the need of srciptlet tag The custom tags eliminates the need of scriptlet tag which is
session.setAttribute("user","sonoo");
considered
bad
programming approach in JSP.
%>
Separation
of business logic from JSP The custom tags separate the the business logic from the JSP
<a href="process.jsp">visit</a>
page
so
that
process.jsp it may be easy to maintain.
Reusability
The custom tags makes
the possibility to reuse the same business logic again
Value is ${ sessionScope.user
}
and again.

Precedence of Operators in EL
Syntax
custom
tag :
There to
areusemany
operators
that have been provided in the Expression Language. Their
There
are
two
ways
to
use
the
custom
tag. They are given below:
precedence are as follows:
<prefix:tagname
attr1=value1....attrn=valuen
/>
Reserve words in EL
<prefix:tagname
attr1=value1....attrn=valuen
> Language. They are as follows:
There are many reserve
words in the Expression
body code
Lt
Le
gt
Ge
</prefix:tagname>
Eq
Ne
true
false
JSP Custom Tag API
And
Or package contains
not
The javax.servlet.jsp.tagext
classes andinstanceof
interfaces for JSP custom tag API. The
JspTag is the root interface in the Custom Tag hierarchy.
Div
Mod
empty
null

JspTag interface
The JspTag is the root interface for all the interfaces and classes used in custom tag. It is a marker
interface.
17
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Tag interface:
The Tag interface is the sub interface of JspTag interface. It provides methods to perform action at the
start and end of the tag.

8.MVC in JSP

Fields
MVCof Tag interface:
There
four for
fields
defined
in and
the Tag
interface.
are: pattern that separates the business
MVCare
stands
Model
View
Controller.
It They
is a design
logic,
presentation
logic
and
data.
Field Name
Description
Controller acts as an interface between View and Model. Controller intercepts all the incoming
public
static
int it evaluates the body content.
requests.
EVAL_BODY_INCLUDE
Model
represents the state of the application i.e. data. It can also have business logic.
View
represents
theEVAL_PAGE
presentaion i.e. UI(User Interface).
public static int
it evaluates the JSP page content after the custom
tag.
Advantage of MVC (Model 2) Architecture:
public static
int SKIP_BODY
it skips the body content of the tag.
Navigation
Control
is centralized
Easy
to maintain
theSKIP_PAGE
large application
public
static int
it skips the JSP page content after the custom tag.
Methods of Tag interface:
The methods of the Tag interface are as follows:
Method Name
Description
public
void it sets the given PageContext object.
setPageContext(PageContext pc)
public void setParent(Tag t)

it sets the parent of the tag handler.

public Tag getParent()

it returns the parent tag handler object.

public int doStartTag()throws it is invoked by the JSP page implementation object. The
Example
of following MVC in JSP : JSP programmer should override this method and define
JspException
In this example, we are using servlet as the
a controller,
jsp astoa view
component,
Java
Bean
class
business logic
be performed
at the
start
of the
tag.as
a model.
int we
doEndTag()throws
it is invoked by the JSP page implementation object. The
In public
this example,
have created 5 pages:
JspException
programmer should override this method and define
index.jsp
a page that gets input from theJSP
user.
the
business
logic to be performed at the end of the tag.
ControllerServlet.java a servlet that acts as a controller.
public void release()

it is invoked by the JSP page implementation object to


release the state.

IterationTag interface
The IterationTag interface is the sub interface of the Tag interface. It provides an
additional method to reevaluate the body.

Field of IterationTag interface:


There is only one field defined in the IterationTag interface.
public static int EVAL_BODY_AGAIN it reevaluates the body content.
Method of Tag interface:
There is only one method defined in the IterationTag interface.
public int doAfterBody()throws JspException it is invoked by the JSP page implementation object
18
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

after the evaluation of the body. If this method returns EVAL_BODY_INCLUDE, body content will
be reevaluated, if it returns SKIP_BODY, no more body cotent will be evaluated.
TagSupport class
The TagSupport class implements the IterationTag interface. It acts as the base class for new Tag
Handlers. It provides some additional methods also.
There is given two simple examples of JSP custom tag. One example of JSP custom tag, performs
action at the start of the tag and second example performs action at the start and end of the tag.
Attributes in Custom Tag

Here, we will learn how we can define attributes for the custom tag.

Iteration using Custom Tag


In this example, we are iterating the body content of the custom tag.

Custom URI in Custom Tag


We may also refer the TLD file by using the URI. Here we will learn how can we use
custom URI.

Example of JSP Custom Tag:


In this example, we are going to create a custom tag that prints the current date and time. We are
performing action at the start of tag.
For creating any custom tag, we need to follow following steps:
Create the Tag handler class and perform action at the start or at the end of the tag.
Create the Tag Library Descriptor (TLD) file and define tags
Create the JSP file that uses the Custom tag defined in the TLD file
Understanding flow of custom tag in jsp:

1) Create the Tag handler class


To create the Tag Handler, we are inheriting the TagSupport class and overriding its method
doStartTag().To write data for the jsp, we need to use the JspWriter class.
The PageContext class provides getOut() method that returns the instance of JspWriter class.
TagSupport class provides instance of pageContext bydefault.
File: MyTagHandler.java
package com.javatpoint.sonoo;
import java.util.Calendar;
import javax.servlet.jsp.JspException;
19
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class MyTagHandler extends TagSupport{
public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();//returns the instance of JspWriter
try{
out.print(Calendar.getInstance().getTime());//printing date and time using JspWriter
}catch(Exception e){System.out.println(e);}
return SKIP_BODY;//will not evaluate the body content of the tag
}
}
2) Create the TLD file
Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It must be
contained inside the WEB-INF directory.
File: mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<tag>
<name>today</name>
<tag-class>com.javatpoint.sonoo.MyTagHandler</tag-class>
</tag>
</taglib>
3) Create the JSP file
Let's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it is
recommended to use the uri name instead of full path of tld file. We will learn about uri later.
It uses taglib directive to use the tags defined in the tld file.
File: index.jsp
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
Current Date and Time is: <m:today/>
Output
Attributes in JSP Custom Tag
There can be defined too many attributes for any custom tag. To define the attribute, you need to
perform two tasks:
20
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Define the property in the TagHandler class with the attribute name and define the setter method
define the attribute element inside the tag element in the TLD file
Let's understand the attribute by the tag given below:
<m:cube number="4"></m:cube>
Here m is the prefix, cube is the tag name and number is the attribute.

Simple example of attribute in JSP Custom Tag:


In this example, we are going to use the cube tag which return the cube of any given number.
Here, we are defining the number attribute for the cube tag. We are using the three file here:
index.jsp
CubeNumber.java
mytags.tld
index.jsp
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
Cube of 4 is: <m:cube number="4"></m:cube>
CubeNumber.java
package com.javatpoint.taghandler;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class CubeNumber extends TagSupport{
private int number;
public void setNumber(int number) {
this.number = number;
}
public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();
try{
out.print(number*number*number);
}catch(Exception e){e.printStackTrace();}
return SKIP_BODY;
}
}
mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
Output:
21
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Cube of 4 is: 64
JSP Custom Tag attribute example with database

Let's create a custom tag that prints a particular record of table for the given table
name and id.
So, you have to have two properties in the tag handler class.

PrintRecord.java
package com.javatpoint;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.sql.*;
public class PrintRecord extends TagSupport{
private String id;
private String table;
public void setId(String id) {
this.id = id;
}
public void setTable(String table) {
this.table = table;
}
public int doStartTag()throws JspException{
JspWriter out=pageContext.getOut();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from "+table+" where id=?");
ps.setInt(1,Integer.parseInt(id));
ResultSet rs=ps.executeQuery();
if(rs!=null){
ResultSetMetaData rsmd=rs.getMetaData();
int totalcols=rsmd.getColumnCount();
//column name
out.write("<table border='1'>");
out.write("<tr>");
for(int i=1;i<=totalcols;i++){
out.write("<th>"+rsmd.getColumnName(i)+"</th>");
}
out.write("</tr>");
//column value
if(rs.next()){
22
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

out.write("<tr>");
for(int i=1;i<=totalcols;i++){
out.write("<td>"+rs.getString(i)+"</td>");
}
out.write("</tr>");
}else{
out.write("Table or Id doesn't exist");
}
out.write("</table>");
}
con.close();
}catch(Exception e){System.out.println(e);}
return SKIP_BODY;
}
}
m.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.2</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>c</short-name>
<uri>javatpoint</uri>
<tag>
<name>printRecord</name>
<tag-class>com.javatpoint.PrintRecord</tag-class>
<attribute>
<name>id</name>
<required>true</required>
</attribute>
<attribute>
<name>table</name>
<required>true</required>
</attribute>
</tag>
</taglib>
index.jsp
<%@ taglib uri="javatpoint" prefix="j" %>
23
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<j:printRecord table="user874" id="1"></j:printRecord>

Output:

24
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Iteration using JSP Custom Tag


We can iterate the body content of any tag using the doAfterBody() method of IterationTag
interface.
Here we are going to use the TagSupport class which implements the IterationTag interface. For
iterating the body content, we need to use the EVAL_BODY_AGAIN constant in the doAfterBody()
method.
Example of Iteration using JSP Custom Tag
In this example, we are going to use the attribute in the custom tag, which returns the power of any
given number. We have created three files here
index.jsp
PowerNumber.java
mytags.tld
index.jsp
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
3 ^ 5 = <m:power number="3" power="5">
body
</m:power>
PowerNumber.java
package com.javatpoint.taghandler;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class PowerNumber extends TagSupport{
private int number;
private int power;
private static int counter;
private static int result=1;
public void setPower(int power) {
this.power = power;
}
public void setNumber(int number) {
this.number = number;
}
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspException {
JspWriter out=pageContext.getOut();
25
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<description>A simple tab library for the examples</description>
<tag>
<name>power</name>
<tag-class>com.javatpoint.taghandler.PowerNumber</tag-class>
<attribute>
<name>number</name>
<required>true</required>
</attribute>
<attribute>
<name>power</name>
<required>true</required>
</attribute>
</tag>
</taglib>
Looping using Iteration Tag (creating tag for loop)
Let's create a loop tag that iterates the body content of this tag.
File: index.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/h
tml4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%@taglib prefix="m" uri="sssuri" %>
<m:loop end="5" start="1">
<p>My Name is khan</p>
</m:loop>
</body>
</html>
File: mytags.tld
26
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<?xml version="1.0" encoding="ISO-8859-1" ?>


<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>abc</short-name>
<uri>sssuri</uri>
<tag>
<name>loop</name>
<tag-class>com.javatpoint.customtag.Loop</tag-class>
<attribute>
<name>start</name>
<required>true</required>
</attribute>
<attribute>
<name>end</name>
<required>true</required>
</attribute>
</tag>
</taglib>
File: Loop.java
package com.javatpoint.customtag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class Loop extends TagSupport{
private int start=0;
private int end=0;
public void setStart(int start) {
this.start = start;
}
public void setEnd(int end) {
this.end = end;
}
@Override
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE;
}

27
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

@Override
public int doAfterBody() throws JspException {
if(start<end){
start++;
return EVAL_BODY_AGAIN;
}else{
return SKIP_BODY;
}
}
}
File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln
s="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/jav
aee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<jsp-config>
<taglib>
<taglib-uri>sssuri</taglib-uri>
<taglib-location>/WEB-INF/mytags.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
Output:

28
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Custom URI in JSP Custom Tag


We can use the custom URI, to tell the web container about the tld file. In such case, we need to
define the taglib element in the web.xml. The web container gets the information about the tld file
from the web.xml file for the specified URI.
Example to use custom URI in JSP Custom Tag
In this example, we are going to use the custom uri in the JSP file. For this application, we need to
focus on 4 files.
index.jsp
web.xml
mytags.tld
PrintDate.java
index.jsp
<%@ taglib uri="mytags" prefix="m" %>
Today is: <m:today></m:today>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<jsp-config>
<taglib>
<taglib-uri>mytags</taglib-uri>
<taglib-location>/WEB-INF/mytags.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>mytags</uri>
<description>A simple tab library for the examples</description>
<tag>
<name>today</name>
29
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<tag-class>com.javatpoint.taghandler.PrintDate</tag-class>
</tag>
</taglib>
PrintDate.java
package com.javatpoint.taghandler;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class PrintDate extends TagSupport{
public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();
try{
out.print(java.util.Calendar.getInstance().getTime());
}catch(Exception e){e.printStackTrace();}
return SKIP_BODY;
}
}

30
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

11-DEVELOPMENT IN JSP

31
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Registration Form in JSP


For creating registration form, you must have a table in the database. You can write the database
logic in JSP file, but separating it from the JSP page is better approach. Here, we are going to use
DAO, Factory Method, DTO and Singletion design patterns. There are many files:
index.jsp for getting the values from the user
User.java, a bean class that have properties and setter and getter methods.
process.jsp, a jsp file that processes the request and calls the methods
Provider.java, an interface that contains many constants like DRIVER_CLASS,
CONNECTION_URL, USERNAME and PASSWORD
ConnectionProvider.java, a class that returns an object of Connection. It uses the Singleton and
factory method design pattern.
RegisterDao.java, a DAO class that is responsible to get access to the database
Example of Registration Form in JSP:
In this example, we are using the Oracle10g database to connect with the database. Let's first
create the table in the Oracle database:
CREATE TABLE "USER432"
( "NAME" VARCHAR2(4000),
"EMAIL" VARCHAR2(4000),
"PASS" VARCHAR2(4000)
)
/
We have created the table named user432 here.
index.jsp
We are having only three fields here, to make the concept clear and simplify the flow of the
application. You can have other fields also like country, hobby etc. according to your
requirement.
<form action="process.jsp">
<input type="text" name="uname" value="Name..." onclick="this.value=''"/><br/>
<input type="text" name="uemail" value="Email ID..." onclick="this.value=''"/><br/>
<input type="password" name="upass" value="Password..." onclick="this.value=''"/><br/>
<input type="submit" value="register"/>
</form>
process.jsp
This jsp file contains all the incoming values to an object of bean class which is passed as an
argument in the register method of the RegisterDao class.
<%@page import="bean.RegisterDao"%>
<jsp:useBean id="obj" class="bean.User"/>
<jsp:setProperty property="*" name="obj"/>
<%
int status=RegisterDao.register(obj);
if(status>0)
out.print("You are successfully registered");
%>
User.java
It is the bean class that have 3 properties uname, uemail and upass with its setter and getter
methods.
32
package
bean;
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
2nd Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
public class User {
.MobileNo:9328994901
private String uname,upass,uemail;
public String getUname() {
return uname;

Jsp Interview questions


There is a list of 25 jsp interview questions for freshers and professionals. If you know any jsp
interview question that has not been included here, post your question in the Ask Question
section.
1)What is JSP?
Java Server Pages technology (JSP) is used to create dynamic web page. It is an extension to the
servlet technology. A JSP page is internally converted into servlet.
2) What are the life-cycle methods for a jsp?
Method

Description

public void jspInit()

It is invoked only once, same


as init method of servlet.

public
void
_jspService(ServletRequest It is invoked at each request,
request,ServletResponse)throws
same as service() method of
ServletException,IOException
servlet.
public void jspDestroy()

It is invoked only once, same


as destroy() method of servlet.

3)What is difference between hide comment and output comment?


The jsp comment is called hide comment whereas html comment is called output comment. If
user views the source of the page, the jsp comment will not be shown whereas html comment
will be shown.
4)What are the JSP implicit objects ?
JSP provides 9 implicit objects by default. They are as follows:
Object

Type

1) out

JspWriter

2) request

HttpServletRequest

3) response

HttpServletResponse

4) config

ServletConfig

5) session

HttpSession

6) application

ServletContext

7) pageContext

PageContext

8) page

Object

9) exception

Throwable

5)What is difference between include directive and include action?


include directive

include action

1) The include directive includes the 1) The include action includes the content at
content at page translation time.
request time.
2) The include directive includes the 2) The include action
33 doesn't include the
original
content
of
the
page
so
page
size
original
content
rather
invokes the include()
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
increases
at runtime.
method of Char
Vendor Rasta,
provided Manjalpur
class.
2nd Floor,
Ronak Plaza, Tulsidham
3) It's better for static pages. .MobileNo:9328994901
3) It's better for dynamic pages.
6) Is JSP technology extensible?

34
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

2-Servlet Tutorial

35
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
Servlet technology is used to create web application (resides at server side and generates
dynamic web page).

36
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

1.Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
Let's see what are the interfaces of javax.servlet package.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
Servlet
ServletRequest
ServletResponse
RequestDispatcher
ServletConfig
ServletContext
SingleThreadModel
Filter
FilterConfig
FilterChain
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
GenericServlet
ServletInputStream
ServletOutputStream
ServletRequestWrapper
ServletResponseWrapper
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
ServletException
UnavailableException
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
37
HttpServlet
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
Cookie 2nd Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
HttpServletRequestWrapper
.MobileNo:9328994901
HttpServletResponseWrapper
HttpSessionEvent
HttpSessionBindingEvent

Life Cycle of a Servlet (Servlet Life Cycle)


The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
Servlet class is loaded.
Servlet instance is created.
init method is invoked.
service method is invoked.
destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In
the ready state, servlet performs all the tasks. When the web container invokes the destroy()
method, it shifts to the end state.

1) Servlet class is loade


The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance. The init
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException
4) service method is invoked
The web container calls the service method each time when request for the servlet is received. If
servlet is not initialized, it follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only
once. The syntax of the service method of the Servlet interface is given below:
38
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory, thread
etc. The syntax of the destroy method of the Servlet interface is given below:
public void destroy()
Steps to create a servlet example:
Steps to create the servlet using Tomcat server
Create a directory structure
Create a Servlet
Compile the Servlet
Create a deployment descriptor
Start the server and deploy the application
There are given 6 steps to create a servlet example. These steps are required for all the servers.
The servlet example can be created by three ways:
By implementing Servlet interface,
By inheriting GenericServlet class, (or)
By inheriting HttpServlet class
The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.
Here, we are going to use apache tomcat server in this example. The steps are as follows:
Create a directory structure
Create a Servlet
Compile the Servlet
Create a deployment descriptor
Start the server and deploy the project
Access the servlet

39
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

How Servlet works?


It is important to learn how servlet works for understanding the servlet well. Here, we are going
to get the internal detail about the first servlet program.
The server checks if the servlet is requested for the first time.
If yes, web container does the following tasks:
loads the servlet class.
instantiates the servlet class.
calls the init method passing the ServletConfig object
else
calls the service method passing request and response objects
The web container calls the destroy method when it needs to remove the servlet such as at time
of stopping server or undeploying the project.
How web container handles the servlet request?
The web container is responsible to handle the request. Let's see how it handles the request.
maps the request with the servlet in the web.xml file.
creates request and response objects for this requestcalls the service method on the threadThe
public service method internally calls the protected service method
The protected service method calls the doGet method depending on the type of request.
The doGet method generates the response and it is passed to the client.
After sending the response, the web container deletes the request and response objects. The
thread is contained in the thread pool or deleted depends on the server implementation.
What is written inside the public service method?
The public service method converts the ServletRequest object into the HttpServletRequest type
and ServletResponse object into the HttpServletResponse type. Then, calls the service method
passing these objects. Let's see the internal code:
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
HttpServletRequest request;
HttpServletResponse response;
try
{
request = (HttpServletRequest)req;
response = (HttpServletResponse)res;
}
catch(ClassCastException e)
{
throw new ServletException("non-HTTP request or response");
}
service(request, response);
}
What is written inside the protected service method?
The protected service method checks the type of request, if request type is get, it calls doGet
method, if request type is post, it calls doPost method, so on. Let's see the internal code:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String method = req.getMethod();
if(method.equals("GET"))
40
{B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
longndlastModified = getLastModified(req);
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
if(lastModified == -1L)
.MobileNo:9328994901
{
doGet(req, resp);
}

//rest of the code


}
}

41
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

3-Hibernate introduction

1.Hibernate Introduction
42
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
Hibernate Framework
Hibernate framework simplifies the development of java application to interact with the

43
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Hibernate Architecture
3.Hibernate
Example
The Hibernate
architecture
includes many
objects persistent
object, session
Example
to create
the Hibernate
Application
in Eclipse
IDE factory, transaction

factory,
factory,
etc.hibernate
There areapplication
4 layers in using
hibernate
architecture
Here,
weconnection
are going to
createsession,
a simpletransaction
example of
eclipse
IDE. For
java
application
layer,
hibernate
framework
layer,
backhand
api
layer
and
database
layer.Let's
creating the first hibernate application in Eclipse IDE, we need to follow following steps:
see the diagram of hibernate architecture
Create the java project
Add jar files for hibernate
Create the Persistent class
Create the mapping file for Persistent class
Create the Configuration file
Create the class that retrieves or stores the persistent object
Run the application
1) Create the java project
Create the java project by File Menu - New - project - java project . Now specify the project
name e.g. firsthb then next - finish .
2) Add jar files for hibernate
To add the jar files Right click on your project - Build path - Add external archives. Now select
all the jar files as shown in the image given below then click open.

This is the high level architecture of Hibernate with mapping file and configuration file.
Hibernate framework uses many objects session factory, session, transaction etc. alongwith
existing Java API such as JDBC (Java Database Connectivity), JTA (Java Transaction API) and
JNDI (Java Naming Directory Interface).
Elements of Hibernate Architecture:
For creating the first hibernate application, we must know the elements of Hibernate
architecture. They are as follows:
SessionFactory
The SessionFactory is a factory of session and client of ConnectionProvider. It holds second
level cache (optional) of data. The org.hibernate.SessionFactory interface provides factory
method to get the object of Session.
Session
The session object provides an interface between the application and data stored in the database.
It is a short-lived object and wraps the JDBC connection. It is factory of Transaction, Query and
Criteria. It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface
provides methods to insert, update and delete the object. It also provides factory methods for
In
this example,
weand
areCriteria.
connecting the application with oracle database. So you must add the
Transaction,
Query
ojdbc14.jar
Transactionfile.
3)
the Persistent
TheCreate
transaction
objectclass
specifies the atomic unit of work. It is optional. The
Here,
we are creating the interface
same persistent
class
whichfor
wetransaction
have created
in the previous topic. To
org.hibernate.Transaction
provides
methods
management.
ConnectionProvider
create the persistent class, Right click on src - New - Class - specify the class with package name
It
is acom.javatpoint.mypackage)
factory of JDBC connections. -Itfinish.
abstracts the application from DriverManager or DataSource. It is
(e.g.
44
optional.
Employee.java
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
TransactionFactory
package com.javatpoint.mypackage;
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
It is a factory of Transaction. It is optional.
.MobileNo:9328994901
public class Employee {
private int id;
private String firstName,lastName;

public int getId() {


Hibernate
return id; with Annotation
The
} hibernate application can be created with annotation. There are many annotations that can
be
usedvoid
to create
hibernate
public
setId(int
id) { application such as @Entity, @Id, @Table etc.
Hibernate
are based on the JPA 2 specification and supports all the features.
this.id =Annotations
id;
All
} the JPA annotations are defined in the javax.persistence.* package. Hibernate EntityManager
implements
interfaces and{life cycle defined by the JPA specification.
public Stringthe
getFirstName()
The
core firstName;
advantage of using hibernate annotation is that you don't need to create mapping (hbm)
return
file.
} Here, hibernate annotations are used to provide the meta data.
public void setFirstName(String firstName) {
Example
to create=the
hibernate application with Annotation
this.firstName
firstName;
}There are 4 steps to create the hibernate application with annotation.
Add theString
jar file
for oracle (if your
database is oracle) and annotation
public
getLastName()
{
Create
thelastName;
Persistent class
return
}Add mapping of Persistent class in configuration file
Create void
the class
that retrieves or lastName)
stores the persistent
object
public
setLastName(String
{
this.lastName = lastName;
1)
} Add the jar file for oracle and annotation
}For oracle you need to add ojdbc14.jar file. For using annotation, you need to add:
hibernate-commons-annotations.jar
4) Create the mapping file for Persistent class
ejb3-persistence.jar
Here, we are creating the same mapping file as created in the previous topic. To create the
hibernate-annotations.jar
mapping file, Right click on src - new - file - specify the file name (e.g. employee.hbm.xml) 2)
Persistent
ok.Create
It mustthe
be outside
the class
package.
Here,
we
are
creating
the
same persistent class which we have created in the previous topic. But
employee.hbm.xml
here,
are using annotation.
<?xmlwe
version='1.0'
encoding='UTF-8'?>
@Entity
annotation
marks
this class
as an entity.
<!DOCTYPE hibernate-mapping
PUBLIC
@Table
annotation specifies
the table
where data of this entity is to be persisted. If you
"-//Hibernate/Hibernate
Mapping
DTDname
3.0//EN"
don't
use @Table annotation, hibernate will use the class name as the table name bydefault.
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
@Id annotation marks the identifier for this entity.
@Column
annotation specifies the details of the column for this property or field. If @Column
<hibernate-mapping>
annotation
is not specified, property name will be used table="emp1000">
as the column name bydefault.
<class name="com.javatpoint.mypackage.Employee"
Employee.java
<id name="id">
package
com.javatpoint;
<generator
class="assigned"></generator>
</id>
import
javax.persistence.Entity;
<property
name="firstName"></property>
import
javax.persistence.Id;
<property
name="lastName"></property>
import
javax.persistence.Table;
</class>
</hibernate-mapping>
@Entity
5) Create the Configuration file
@Table(name= "emp500")
The configuration file contains all the informations for the database such as connection_url,
public class Employee {
driver_class, username, password etc. The hbm2ddl.auto property is used to create the table in
@Id
the database automatically. We will have in-depth learning about Dialect class in next topics. To
private int id;
create the configuration file, right click on src - new - file. Now specify the configuration file
private String firstName,lastName;
name e.g. hibernate.cfg.xml.
hibernate.cfg.xml
45
public int getId() {
<?xml version='1.0' encoding='UTF-8'?>
B-208
MobileNo:9327219987
return
id; Manubhai Tower , Sayajigunj
<!DOCTYPE
nd hibernate-configuration PUBLIC
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
}
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
.MobileNo:9328994901
public void setId(int id) {
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
this.id = id;
}

<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property
name="connection.password">oracle</property>
Web
Application
with Hibernate
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
Here, we are going to create a web application with hibernate. For creating the web application, we
<mapping
resource="employee.hbm.xml"/>
are
using JSP
for presentation logic, Bean class for representing data and DAO class for database
</session-factory>
codes.
</hibernate-configuration>
As we create the simple application in hibernate, we don't need to perform any extra operations in
6)hibernate
Create the
thatweb
retrieves
or stores
the persistent
object
for class
creating
application.
In such
case, we are
getting the value from the user using the
InJSP
thisfile.
class, we are simply storing the employee object to the database.
package com.javatpoint.mypackage;
Example to create web application using hibernate
import
In thisorg.hibernate.Session;
example, we are going to insert the record of the user in the database. It is simply a registration
import
org.hibernate.SessionFactory;
form.
import org.hibernate.Transaction;
import
org.hibernate.cfg.Configuration;
index.jsp
This page gets input from the user and sends it to the register.jsp file using post method.
public
StoreData {
<formclass
action="register.jsp"
method="post">
public
static
void
main(String[]
args) {
Name:<input type="text" name="name"/><br><br/>
//creating configuration
object name="password"/><br><br/>
Password:<input
type="password"
Configuration
cfg=new
Configuration();
Email ID:<input type="text" name="email"/><br><br/>
cfg.configure("hibernate.cfg.xml");//populates
the data of the configuration file
<input
type="submit" value="register"/>"
//creating seession factory object
</form>
SessionFactory factory=cfg.buildSessionFactory();
register.jsp
//creating
session
objectparameters and stores this information into an object of User class. Further, it
This
file gets
all request
Session
session=factory.openSession();
calls
the register
method of UserDao class passing the User class object.
//creating
transaction
object
<%@page import="com.javatpoint.mypack.UserDao"%>
Transaction t=session.beginTransaction();
<jsp:useBean
id="obj" class="com.javatpoint.mypack.User">
Employee
e1=new
Employee();
</jsp:useBean>
e1.setId(115); property="*" name="obj"/>
<jsp:setProperty
e1.setFirstName("sonoo");
<%
e1.setLastName("jaiswal");
int
i=UserDao.register(obj);
session.persist(e1);//persisting
the object
if(i>0)
t.commit();//transaction
is committed
out.print("You
are successfully
registered");
session.close();
%>
System.out.println("successfully saved");
User.java
}It is the simple bean class representing the Persistent class in hibernate.
}

package com.javatpoint.mypack;
7) Run the application
public class User {
Before running the application, determine that directory structure is like this.
private int id;
private String name,password,email;
//getters and setters
46
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

To run the hibernate application, right click on the StoreData class - Run As - Java
Application.
}
user.hbm.xml
It maps the User class with the table of the database.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypack.User" table="u400">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<property name="password"></property>
<property name="email"></property>
</class>
</hibernate-mapping>
UserDao.java
A Dao class, containing method to store the instance of User class.
package com.javatpoint.mypack;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class UserDao {
public static int register(User u){
int i=0;
Session session=new Configuration().
configure().buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
t.begin();
i=(Integer)session.save(u);
t.commit();
session.close();
return i;
}
}

47
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

hibernate.cfg.xml
It is a configuration file, containing informations about the database and mapping file.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">create</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="user.hbm.xml"/>
Generator
classes in Hibernate
</session-factory>
The
<generator> subelement of id used to generate the unique identifier for the objects of
</hibernate-configuration>

persistent class. There are many generator classes defined in the Hibernate Framework.
All the generator classes implements the org.hibernate.id.IdentifierGenerator interface. The
application programmer may create one's own generator classes by implementing the
IdentifierGenerator interface. Hibernate framework provides many built-in generator classes:
assigned
increment
sequence
hilo
native
identity
seqhilo
uuid
guid
select
foreign
sequence-identity
1) assigned
It is the default generator strategy if there is no <generator> element . In this case, application
assigns the id. For example:
<hibernate-mapping>
<class ...>
<id ...>
<generator class="assigned"></generator>
</id>
48
.....
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
</class>
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
</hibernate-mapping>
.MobileNo:9328994901
2) increment
It generates the unique id only if no other process is inserting data into this table. It generates
short, int or long type

....
<hibernate-mapping>
<class ...>
<id ...>
<generator class="increment"></generator>
</id>
.....
</class>
</hibernate-mapping>
3) sequence
It uses the sequence of the database. if there is no sequence defined, it creates a sequence
automatically e.g. in case of Oracle database, it creates a sequence named
HIBERNATE_SEQUENCE. In case of Oracle, DB2, SAP DB, Postgre SQL or McKoi, it uses
sequence but it uses generator in interbase. Syntax:
.....
<id ...>
<generator class="sequence"></generator>
</id>
..... For defining your own sequence, use the param subelement of generator.
.....
<id ...>
<generator class="sequence">
<param name="sequence">your_sequence_name</param>
</generator>
</id>
4) hilo
It uses high and low algorithm to generate the id of type short, int and long. Syntax:
<id ...>
<generator class="hilo"></generator>
</id>
5) native
It uses identity, sequence or hilo depending on the database vendor. Syntax:
.....
<id ...>
<generator class="native"></generator>
</id>
.....
6) identity
49
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

It is used in Sybase, My SQL, MS SQL Server, DB2 and HypersonicSQL to support the id
column. The returned id is of type short, int or long.
7) seqhilo
It uses high and low algorithm on the specified sequence name. The returned id is of type short,
int or long.
8) uuid
It uses 128-bit UUID algorithm to generate the id. The returned id is of type String, unique
within a network (because IP is used). The UUID is represented in hexadecimal digits, 32 in
length.
It uses GUID generated by database of type string. It works on MS SQL Server and MySQL.
9) guid
10) select
It uses the primary key returned by the database trigger.
11) foreign
It uses the id of another associated object, mostly used with <one-to-one> association.

50
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

SQL Dialects in Hibernate


For connecting any hibernate application with the database, you must specify the SQL dialects.
There are many Dialects classes defined for RDBMS in the org.hibernate.dialect package. They
are as follows:
RDBMS
Oracle (any version)
Oracle9i
Oracle10g
MySQL
MySQL with InnoDB
MySQL with MyISAM
DB2
DB2 AS/400
DB2 OS390
Microsoft SQL Server
Sybase
Sybase Anywhere
PostgreSQL
SAP DB
Informix
HypersonicSQL
Ingres
Progress
Mckoi SQL
Interbase
Pointbase
FrontBase
Firebird

Dialect
org.hibernate.dialect.OracleDialect
org.hibernate.dialect.Oracle9iDialect
org.hibernate.dialect.Oracle10gDialect
org.hibernate.dialect.MySQLDialect
org.hibernate.dialect.MySQLInnoDBDialect
org.hibernate.dialect.MySQLMyISAMDialect
org.hibernate.dialect.DB2Dialect
org.hibernate.dialect.DB2400Dialect
org.hibernate.dialect.DB2390Dialect
org.hibernate.dialect.SQLServerDialect
org.hibernate.dialect.SybaseDialect
org.hibernate.dialect.SybaseAnywhereDialect
org.hibernate.dialect.PostgreSQLDialect
org.hibernate.dialect.SAPDBDialect
org.hibernate.dialect.InformixDialect
org.hibernate.dialect.HSQLDialect
org.hibernate.dialect.IngresDialect
org.hibernate.dialect.ProgressDialect
org.hibernate.dialect.MckoiDialect
org.hibernate.dialect.InterbaseDialect
org.hibernate.dialect.PointbaseDialect
org.hibernate.dialect.FrontbaseDialect
org.hibernate.dialect.FirebirdDialect

It uses a special sequence generation strategy. It is supported in Oracle 10g drivers only.

Hibernate Logging by Log4j using xml file


Logging enables the programmer to write the log details into a file permanently. Log4j and
Logback frameworks can be used in hibernate framework to support logging.
There are two ways to perform logging using log4j:
By log4j.xml file (or)
By log4j.properties file
51
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Steps to perform Hibernate Logging by Log4j using xml file


There are two ways to perform logging using log4j using xml file:
Load the log4j jar files with hibernate
Create the log4j.xml file inside the src folder (parallel with hibernate.cfg.xml file)

4.Hibernate Log4j
Example of Hibernate Logging by Log4j using xml file
You can enable logging in hibernate by following only two steps in any hibernate example. This
is the first example of hibernate application with logging support using log4j.
Load the required jar files
You need to load the slf4j.jar and log4j.jar files with hibernate jar files.
Create log4j.xml file
Now you need to create log4j.xml file. In this example, all the log details will be written in the
C:/javatpointlog.log file.
log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
debug="false">
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}: %m
%n" />
</layout>
</appender>
<appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</appender>
<appender name="FILE" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="C:/javatpointlog.log" />
<param name="MaxBackupIndex" value="100" />
<layout class="org.apache.log4j.PatternLayout">
52
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}: %m


%n" />
</layout>
</appender>
<category name="org.hibernate">
<priority value="DEBUG" />
</category>
<category name="java.sql">
<priority value="debug" />
</category>
<root>
<priority value="INFO" />
<appender-ref ref="FILE" />
</root>
</log4j:configuration>

53
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

5.Inheritance Mapping
Hibernate Inheritance Mapping Tutorial
We can map the inheritance hierarchy classes with the table of the database. There are three
inheritance mapping strategies defined in the hibernate:
Table Per Hierarchy
Table Per Concrete class
Table Per Subclass
Table Per Hierarchy
In table per hierarchy mapping, single table is required to map the whole hierarchy, an extra
column (known as discriminator column) is added to identify the class. But nullable values are
stored in the table .
Table Per Concrete class
54
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

In case of table per concrete class, tables are created as per class. But duplicate column is added
in subclass tables.
Table Per Subclass
In this strategy, tables are created as per class but related by foreign key. So there are no
duplicate columns.

Hibernate Table Per Hierarchy using Annotation


In the previous page, we have mapped the inheritance hierarchy with one table only using xml
file. Here, we are going to perform this task using annotation. You need to use
@Inheritance(strategy=InheritanceType.SINGLE_TABLE),
@DiscriminatorColumn
and
@DiscriminatorValue annotations for mapping table per hierarchy strategy.
In case of table per hierarchy, only one table is required to map the inheritance hierarchy. Here,
an extra column (also known as discriminator column) is created in the table to identify the class.
Let's see the inheritance hierarchy:

There are three classes in this hierarchy. Employee is the super class for Regular_Employee and
Contract_Employee classes.
The table structure for this hierarchy is as shown below:

Example of Hibernate Table Per Hierarchy using Annotation

55
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

You need to follow following steps to create simple example:


Create the persistent classes
Create the configuration file
Create the class to store the fetch the data
1) Create the Persistent classes
You need to create the persistent classes representing the inheritance. Let's create the three
classes for the above hierarchy:
File: Employee.java
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@Table(name = "employee101")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="employee")
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
//setters and getters
}
File: Regular_Employee.java
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@DiscriminatorValue("regularemployee")
public class Regular_Employee extends Employee{
@Column(name="salary")
private float salary;
@Column(name="bonus")
56
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

private int bonus;


//setters and getters
}
File: Contract_Employee.java
package com.javatpoint.mypackage;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("contractemployee")
public class Contract_Employee extends Employee{
@Column(name="pay_per_hour")
private float pay_per_hour;
@Column(name="contract_duration")
private String contract_duration;
//setters and getters
}
2) Add the persistent classes in configuration file
Open the hibernate.cgf.xml file, and add entries of entity classes like this:
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
</pre></div>
<table >
<tr><td>Now the configuration file will look like this:
</td></tr>
</table>
<span id="filename">File: hibernate.cfg.xml</span>
<div class="codeblock"><pre name="code" class="java">
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.
<hibernate-configuration>
<session-factory>

-->

57
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
3) Create the class that stores the persistent object
In this class, we are simply storing the employee objects in the database.
File: StoreTest.java
package com.javatpoint.mypackage;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class StoreData {
public static void main(String[] args) {
AnnotationConfiguration cfg=new AnnotationConfiguration();
Session session=cfg.configure("hibernate.cfg.xml").buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
Employee e1=new Employee();
e1.setName("sonoo");
Regular_Employee e2=new Regular_Employee();
e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);
Contract_Employee e3=new Contract_Employee();
e3.setName("Arjun Kumar");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
58
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

session.close();
System.out.println("success");
}
Output:

Table Per Concrete class using xml file

In case of Table Per Concrete class, there will be three tables in the database having no relations to
each other. There are two ways to map the table with table per concrete class strategy.
By union-subclass element
By Self creating the table for each class
Let's understand what hierarchy we are going to map.

Let's see how can we map this hierarchy by union-subclass element:


<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp122">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<union-subclass name="com.javatpoint.mypackage.Regular_Employee" table="regemp122">
<property name="salary"></property>
59
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<property name="bonus"></property>
</union-subclass>
<union-subclass name="com.javatpoint.mypackage.Contract_Employee" table="contemp122">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</union-subclass>
</class>
</hibernate-mapping>
In case of table per concrete class, there will be three tables in the database, each representing a
particular class.
The union-subclass subelement of class, specifies the subclass. It adds the columns of parent table
into this table. In other words, it is working as a union.
The table structure for each table will be as follows:
Table structure for Employee class

Table structure for Regular_Employee class:

Table structure for Contract_Employee class:

Example of Table per concrete class


In this example we are creating the three classes and provide mapping of these classes in the
employee.hbm.xml file.
60
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

1) Create the Persistent classes


You need to create the persistent classes representing the inheritance. Let's create the three classes
for the above hierarchy:
File: Employee.java
package com.javatpoint.mypackage;
public class Employee {
private int id;
private String name;
//getters and setters
}
File: Regular_Employee.java
package com.javatpoint.mypackage;
public class Regular_Employee extends Employee{
private float salary;
private int bonus;
//getters and setters
}
File: Contract_Employee.java
package com.javatpoint.mypackage;
public class Contract_Employee extends Employee{
private float pay_per_hour;
private String contract_duration;
//getters and setters
}
2) Create the mapping file for Persistent class
The mapping has been discussed above for the hierarchy.
File: employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp122">
<id name="id">
<generator class="increment"></generator>
</id>
61
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<property name="name"></property>
<union-subclass name="com.javatpoint.mypackage.Regular_Employee" table="regemp122">
<property name="salary"></property>
<property name="bonus"></property>
</union-subclass>
<union-subclass name="com.javatpoint.mypackage.Contract_Employee" table="contemp122">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</union-subclass>
</class>
</hibernate-mapping>
3) Add mapping of hbm file in configuration file
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
<mapping resource="employee.hbm.xml"/>
Now the configuration file will look like this:
File: hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
4) Create the class that stores the persistent object
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
package com.javatpoint.mypackage;
import org.hibernate.*;
62
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

import org.hibernate.cfg.*;
public class StoreData {
public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
Employee e1=new Employee();
e1.setName("sonoo");
Regular_Employee e2=new Regular_Employee();
e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);
Contract_Employee e3=new Contract_Employee();
e3.setName("Arjun Kumar");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}

63
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Table Per Concrete class using Annotation


In case of Table Per Concrete class, tables are created per class. So there are no nullable values
in the table. Disadvantage of this approach is that duplicate columns are created in the subclass
tables.
Here, we need to use @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
annotation in the parent class and @AttributeOverrides annotation in the subclasses.
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) specifies that we are using
table per concrete class strategy. It should be specified in the parent class only.
@AttributeOverrides defines that parent class attributes will be overriden in this class. In table
structure, parent class table columns will be added in the subclass table.
The class hierarchy is given below:

The table structure for each table will be as follows:


Table structure for Employee class

Table structure for Regular_Employee class

Table structure for Contract_Employee class

Example of Table per concrete class


In this example we are creating the three classes and provide mapping
64 of these classes in the
employee.hbm.xml
file.
B-208 Manubhai
Tower , Sayajigunj
MobileNo:9327219987
nd Persistent classes
1) Create2the
Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
You need to create the persistent
classes representing the inheritance. Let's create the three
.MobileNo:9328994901
classes for the above hierarchy:
File: Employee.java

6.Collection Mapping in Hibernate


We can map collection elements of Persistent class in Hibernate. You need to declare the type of
collection in Persistent class from one of the following types:
java.util.List
java.util.Set
java.util.SortedSet
java.util.Map
java.util.SortedMap
java.util.Collection
or write the implementation of org.hibernate.usertype.UserCollectionType
The persistent class should be defined like this for collection element.
package com.javatpoint;
import java.util.List;
public class Question {
private int id;
private String qname;
private List<String> answers;//List can be of any type
//getters and setters
}
Mapping collection in mapping file
There are many subelements of <class> elements to map the collection. They are <list>, <bag>,
<set> and <map>. Let's see how we implement the list for the above class:
<class name="com.javatpoint.Question" table="q100">
<id name="id">
<generator class="increment"></generator>
Mapping
Map in collection mapping using xml file
</id>
Hibernate
allowsname="qname"></property>
you to map Map elements with the RDBMS. As we know, list and map are
<property
index-based collections. In case of map, index column works as the key and element column
works <list
as thename="answers"
value.
table="ans100">
Example
of
Mapping
Map
in
collection mapping using xml file
<key column="qid"></key>
You need
to create
following pages for mapping map elements.
<index
column="type"></index>
Question.java
One to
<element column="answer" type="string"></element>
question.hbm.xml
Many
</list>
hibernate.cfg.xml
</class>
StoreTest.java
FetchTest.java
There are three subelements used in the list:
<key> element is used to define the foreign key in this table based on the Question class
Question.java
identifier.
package
<index> com.javatpoint;
element is used to identify the type. List and Map are indexed collection.
<element> is used to define the element of the collection.
import
This is java.util.Map;
the mapping of collection if collection stores string objects. But if collection stores entity
reference (another class objects), we need to define <one-to-many> or <many-to-many>
65
public
class
Question
{
element.
Now
the Persistent
class will look like:
B-208
MobileNo:9327219987
private
id; Manubhai Tower , Sayajigunj
packageint
com.javatpoint;
nd
2 name,username;
Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
private
String
import java.util.List;
.MobileNo:9328994901
private Map<String,String> answers;
public
{} {
public Question()
class Question
public Question(String name, String username, Map<String, String> answers) {

private String qname;


private List<Answer> answers;//Here, List stores the objects of Answer class
//getters and setters
}
package com.javatpoint;
import
java.util.List;
mapping
in Hibernate by List Example (using xml file)
public
class
Answer
{ has list object that contains the entity reference, we need to use one-to-many
If the persistent class
private
int id;to map the list element.
association
private
String
Here, we
are answer;
using the scenario of Forum where one question has multiple answers.
private String posterName;
//getters and setters
}
Now the mapping file will be:
<class name="com.javatpoint.Question" table="q100">
In such
there can be many answers for a question and each answer may have its own informations
<idcase,
name="id">
that is<generator
why we have
used list in the persistent class (containing the reference of Answer class) to represent
class="increment"></generator>
a collection
</id> of answers.
Let's <property
see the persistent
class that has list objects (containing Answer class objects).
name="qname"></property>
package
<listcom.javatpoint;
name="answers" >
<key column="qid"></key>
import
java.util.List;
<index
column="type"></index>
<one-to-many class="com.javatpoint.Answer" />
public</list>
class Question {
private
int id;
</class>
private
String
qname;by one-to-many relation. In this scenario, there can be many answers for
Here,
List
is mapped
private
List<Answer> answers;
one
question.
//getters and setters
Understanding
key element
} key element is used to define the foreign key in the joined table based on the original
The
The Answer
haskey
its own
informations
such
id, answername,
postedBy etc.
identity.
The class
foreign
element
is nullable
byasdefault.
So for non-nullable
foreign key, we
package
com.javatpoint;
need
to specify
not-null attribute such as:
<key column="qid" not-null="true" ></key>
public
class Answer
The
attributes
of the{key element are column, on-delete, property-ref, not-null, update and
private int id;
unique.
private String answername;
<key
private String postedBy;
column="columnname"
//getters and setters
on-delete="noaction|cascade"
}
not-null="true|false"
}
property-ref="propertyName"
The Question class has list object that have entity reference (i.e. Answer class object). In such case, we
update="true|false"
unique="true|false"
need to use one-to-many of list to map this object. Let's see how we can map it.
/><list name="answers" cascade="all">
Indexed<key
collections
column="qid"></key>
The collection
can be categorized in two forms:
<indexelements
column="type"></index>
indexed <one-to-many
,and
class="com.javatpoint.Answer"/>
non-indexed
The List and Map collection are indexed whereas set and bag collections are
66non-indexed. Here, indexed
collection
B-208
meansManubhai
List and Map requires
Tower
an ,additional
Sayajigunj
element <index>.
MobileNo:9327219987
nd
Collection2Elements
Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
The collection elements can have value
or entity reference (another class object). We can use one of the 4
.MobileNo:9328994901
elements
element

one-to-many, or
many-to-many
The element and component-element are used for normal value such as string, int etc. whereas one-tomany and many-to-many are used to map entity reference.

</list>
Full example of One to Many mapping in Hibernate by List:
In this example, we are going to see full example of mapping list that contains entity reference.
1) create the Persistent class
This persistent class defines properties of the class including List.
Question.java
package com.javatpoint;
import java.util.List;
public class Question {
private int id;
private String qname;
private List<Answer> answers;
//getters and setters
}
Answer.java
package com.javatpoint;
public class Answer {
private int id;
private String answername;
private String postedBy;
//getters and setters
}
}
2) create the Mapping file for the persistent class
Here, we have created the question.hbm.xml file for defining the list.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Question" table="q501">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
67
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<list name="answers" cascade="all">


<key column="qid"></key>
<index column="type"></index>
<one-to-many class="com.javatpoint.Answer"/>
</list>
</class>
<class name="com.javatpoint.Answer" table="ans501">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="answername"></property>
<property name="postedBy"></property>
</class>
</hibernate-mapping>
3) create the configuration file
This file contains information about the database and mapping file.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.
-->
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4) Create the class to store the data
In this class we are storing the data of the question class.
package com.javatpoint;
import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
68
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

public class StoreData {


public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
Answer ans1=new Answer();
ans1.setAnswername("java is a programming language");
ans1.setPostedBy("Ravi Malik");
Answer ans2=new Answer();
ans2.setAnswername("java is a platform");
ans2.setPostedBy("Sudhir Kumar");
Answer ans3=new Answer();
ans3.setAnswername("Servlet is an Interface");
ans3.setPostedBy("Jai Kumar");
Answer ans4=new Answer();
ans4.setAnswername("Servlet is an API");
ans4.setPostedBy("Arun");
ArrayList<Answer> list1=new ArrayList<Answer>();
list1.add(ans1);
list1.add(ans2);
ArrayList<Answer> list2=new ArrayList<Answer>();
list2.add(ans3);
list2.add(ans4);
Question question1=new Question();
question1.setQname("What is Java?");
question1.setAnswers(list1);
Question question2=new Question();
question2.setQname("What is Servlet?");
question2.setAnswers(list2);
session.persist(question1);
session.persist(question2);
t.commit();
session.close();
System.out.println("success");
}
}
OUTPUT

69
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

How to fetch the data of List


Here, we have used HQL to fetch all the records of Question class including answers. In such case, it
fetches the data from two tables that are functional dependent. Here, we are direct printing the object of
answer class, but we have overridden the toString() method in the Answer class returning answername and
poster name. So it prints the answer name and postername rather than reference id.
FetchData.java
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class FetchData {
public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Query query=session.createQuery("from Question");
List<Question> list=query.list();
Iterator<Question> itr=list.iterator();
while(itr.hasNext()){
Question q=itr.next();
System.out.println("Question Name: "+q.getQname());
//printing answers
List<Answer> list2=q.getAnswers();
Iterator<Answer> itr2=list2.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
session.close();
System.out.println("success");
}
}
70
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

OUTPUT

Mapping List in Collection Mapping (using xml file)


If our persistent class has List object, we can map the List easily either by <list> element of class
in mapping file or by annotation.
Here, we are using the scenario of Forum where one question has multiple answers.

Let's see how we can implement the list in the mapping file:
<class name="com.javatpoint.Question" table="q100">
...
<list name="answers" table="ans100">
<key column="qid"></key>
<index column="type"></index>
<element column="answer" type="string"></element>
</list>
...
</class>
Example of mapping list in collection mapping:
In this example, we are going to see full example of collection mapping by list. This is the
example of List that stores string value not entity reference that is why are going to use element
instead of one-to-many within the list element.
1) create the Persistent class
This persistent class defines properties of the class including List.
package com.javatpoint;
import java.util.List;
public class Question {
private int id;
71
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

private String qname;


private List<String> answers;
//getters and setters
}
2) create the Mapping file for the persistent class
Here, we have created the question.hbm.xml file for defining the list.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Question" table="q100">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
<list name="answers" table="ans100">
<key column="qid"></key>
<index column="type"></index>
<element column="answer" type="string"></element>
</list>
</class>
</hibernate-mapping>
3) create the configuration file
This file contains information about the database and mapping file.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.
-->
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
72
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4) Create the class to store the data
In this class we are storing the data of the question class.
package com.javatpoint;
import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class StoreData {
public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
ArrayList<String> list1=new ArrayList<String>();
list1.add("java is a programming language");
list1.add("java is a platform");
ArrayList<String> list2=new ArrayList<String>();
list2.add("Servlet is an Interface");
list2.add("Servlet is an API");
Question question1=new Question();
question1.setQname("What is Java?");
question1.setAnswers(list1);
Question question2=new Question();
question2.setQname("What is Servlet?");
question2.setAnswers(list2);
session.persist(question1);
session.persist(question2);
t.commit();
session.close();
System.out.println("success");
}
}
How to fetch the data of List
73
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Here, we have used HQL to fetch all the records of Question class including answers. In such
case, it fetches the data from two tables that are functional dependent.
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class FetchData {
public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Query query=session.createQuery("from Question");
List<Question> list=query.list();
Iterator<Question> itr=list.iterator();
while(itr.hasNext()){
Question q=itr.next();
System.out.println("Question Name: "+q.getQname());
//printing answers
List<String> list2=q.getAnswers();
Iterator<String> itr2=list2.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
session.close();
System.out.println("success");
}

Mapping Set in Collection Mapping


If our persistent class has Set object, we can map the Set by set element in the mapping file. The set
element doesn't require index element. The one difference between List and Set is that, it stores only
unique values.
Let's see how we can implement the set in the mapping file:
<class name="com.javatpoint.Question" table="q102">
...
<set name="answers" table="ans102">
<key column="qid"></key>
<element column="answer" type="string"></element>
</set>
...
74
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

</class>
Example of mapping set in collection mapping:
In this example, we are going to see full example of collection mapping by set. This is the example of set
that stores value not entity reference that is why are going to use element instead of one-to-many.
1) create the Persistent class
This persistent class defines properties of the class including Set.
package com.javatpoint;
import java.util.Set;
public class Question {
private int id;
private String qname;
private Set<String> answers;
//getters and setters
}
2) create the Mapping file for the persistent class
Here, we have created the question.hbm.xml file for defining the list.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Question" table="q102">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
<set name="answers" table="ans102">
<key column="qid"></key>
<element column="answer" type="string"></element>
</set>
</class>
</hibernate-mapping>
3) create the configuration file
This file contains information about the database and mapping file.
<?xml version='1.0' encoding='UTF-8'?>
75
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<!DOCTYPE hibernate-configuration PUBLIC


"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.
-->
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4) Create the class to store the data
In this class we are storing the data of the question class.
package com.javatpoint;
import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class StoreData {
public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
HashSet<String> set1=new HashSet<String>();
set1.add("java is a programming language");
set1.add("java is a platform");
HashSet<String> set2=new HashSet<String>();
set2.add("Servlet is an Interface");
set2.add("Servlet is an API");
Question question1=new Question();
question1.setQname("What is Java?");
question1.setAnswers(set1);
Question question2=new Question();
question2.setQname("What is Servlet?");
question2.setAnswers(set2);
76
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

session.persist(question1);
session.persist(question2);
t.commit();
session.close();
System.out.println("success");
}
}

How to fetch the data of Set


Here, we have used HQL to fetch all the records of Question class including answers. In such case, it
fetches the data from two tables that are functional dependent.
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class FetchData {
public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Query query=session.createQuery("from Question");
List<Question> list=query.list();
Iterator<Question> itr=list.iterator();
while(itr.hasNext()){
Question q=itr.next();
System.out.println("Question Name: "+q.getQname());
//printing answers
Set<String> set=q.getAnswers();
Iterator<String> itr2=set.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
session.close();
System.out.println("success");
}
}
}
77
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Set One to many


If the persistent class has set object that contains the entity reference, we need to use one-tomany association to map the set element. We can map this list object by either set.
It is non-index based and will not allow duplicate elements.
Let's see the persistent class that has set objects. In this case, there can be many answers for a
question and each answer may have its own informations that is why we have used set element
to represent a collection of answers.
package com.javatpoint;
import java.util.List;
public class Question {
private int id;
private String qname;
private Set<Answer> answers;
//getters and setters
}
The Answer class has its own informations such as id, answername, postedBy etc.
package com.javatpoint;
public class Answer {
private int id;
private String answername;
private String postedBy;
//getters and setters
}
}
The Question class has set object that have entity reference (i.e. Answer class object). In such
case, we need to use one-to-many of set to map this object. Let's see how we can map it.
<set name="answers" cascade="all">
<key column="qid"></key>
<one-to-many class="com.javatpoint.Answer"/>
</set>
Example of mapping set in collection mapping by one to many association:
To understand this example, you may see the bag one-to-many relation example. We have
changed only bag to set in the hbm file and ArrayList to HashSet in the Store class.
Mapping Map in collection mapping using xml file
78
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Hibernate allows you to map Map elements with the RDBMS. As we know, list and map are
index-based collections. In case of map, index column works as the key and element column
works as the value.
Example of Mapping Map in collection mapping using xml file
You need to create following pages for mapping map elements.
Question.java
question.hbm.xml
hibernate.cfg.xml
StoreTest.java
FetchTest.java
Question.java
package com.javatpoint;
import java.util.Map;
public class Question {
private int id;
private String name,username;
private Map<String,String> answers;
public Question() {}
public Question(String name, String username, Map<String, String> answers) {
super();
this.name = name;
this.username = username;
this.answers = answers;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
79
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

public String getUsername() {


return username;
}
public void setUsername(String username) {
this.username = username;
}
public Map<String, String> getAnswers() {
return answers;
}
public void setAnswers(Map<String, String> answers) {
this.answers = answers;
}
}
question.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Question" table="question736">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="username"></property>
<map name="answers" table="answer736" cascade="all">
<key column="questionid"></key>
<index column="answer" type="string"></index>
<element column="username" type="string"></element>
</map>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
80
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<!-- Generated by MyEclipse Hibernate Tools.


<hibernate-configuration>

-->

<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
StoreTest.java
package com.javatpoint;
import java.util.HashMap;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class StoreTest {
public static void main(String[] args) {
Session session=new Configuration().configure().buildSessionFactory().openSession();
Transaction tx=session.beginTransaction();
HashMap<String,String> map1=new HashMap<String,String>();
map1.put("java is a programming language","John Milton");
map1.put("java is a platform","Ashok Kumar");
HashMap<String,String> map2=new HashMap<String,String>();
map2.put("servlet technology is a server side programming","John Milton");
map2.put("Servlet is an Interface","Ashok Kumar");
map2.put("Servlet is a package","Rahul Kumar");
Question question1=new Question("What is java?","Alok",map1);
Question question2=new Question("What is servlet?","Jai Dixit",map2);
session.persist(question1);
session.persist(question2);
tx.commit();
session.close();
System.out.println("successfully stored");
}
}
81
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

FetchTest.java
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class FetchTest {
public static void main(String[] args) {
Session session=new Configuration().configure().buildSessionFactory().openSession();
Query query=session.createQuery("from Question ");
List<Question> list=query.list();
Iterator<Question> iterator=list.iterator();
while(iterator.hasNext()){
Question question=iterator.next();
System.out.println("question id:"+question.getId());
System.out.println("question name:"+question.getName());
System.out.println("question posted by:"+question.getUsername());
System.out.println("answers.....");
Map<String,String> map=question.getAnswers();
Set<Map.Entry<String,String>> set=map.entrySet();
Iterator<Map.Entry<String,String>> iteratoranswer=set.iterator();
while(iteratoranswer.hasNext()){
Map.Entry<String,String> entry=(Map.Entry<String,String>)iteratoranswer.next();
System.out.println("answer name:"+entry.getKey());
System.out.println("answer posted by:"+entry.getValue());
}
}
session.close();
}
}

Mapping Bag in Collection Mapping (using xml file)


If our persistent class has List object, we can map the List by list or bag element in the mapping file. The
bag is just like List but it doesn't require index element.
Here, we are using the scenario of Forum where one question has multiple answers.

82
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Let's see how we can implement the bag in the mapping file:
<class name="com.javatpoint.Question" table="q100">
...
<bag name="answers" table="ans100">
<key column="qid"></key>
<element column="answer" type="string"></element>
</bag>
...
</class>
Example of mapping bag in collection mapping:
In this example, we are going to see full example of collection mapping by bag. This is the example of bag
if it stores value not entity reference that is why are going to use element instead of one-to-many. If you
have seen the example of mapping list, it is same in all cases instead mapping file where we are using bag
instead of list.
1) create the Persistent class
This persistent class defines properties of the class including List.
package com.javatpoint;
import java.util.List;
public class Question {
private int id;
private String qname;
private List<String> answers;
//getters and setters
}
2) create the Mapping file for the persistent class
Here, we have created the question.hbm.xml file for defining the list.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Question" table="q101">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
83
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<bag name="answers" table="ans101">


<key column="qid"></key>
<element column="answer" type="string"></element>
</bag>
</class>
</hibernate-mapping>
3) create the configuration file
This file contains information about the database and mapping file.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.
-->
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4) Create the class to store the data
In this class we are storing the data of the question class.
package com.javatpoint;
import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class StoreData {
public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
ArrayList<String> list1=new ArrayList<String>();
list1.add("java is a programming language");
84
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

list1.add("java is a platform");
ArrayList<String> list2=new ArrayList<String>();
list2.add("Servlet is an Interface");
list2.add("Servlet is an API");
Question question1=new Question();
question1.setQname("What is Java?");
question1.setAnswers(list1);
Question question2=new Question();
question2.setQname("What is Servlet?");
question2.setAnswers(list2);
session.persist(question1);
session.persist(question2);
t.commit();
session.close();
System.out.println("success");
}
}
How to fetch the data
Here, we have used HQL to fetch all the records of Question class including answers. In such case, it
fetches the data from two tables that are functional dependent.
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class FetchData {
public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Query query=session.createQuery("from Question");
List<Question> list=query.list();
Iterator<Question> itr=list.iterator();
while(itr.hasNext()){
Question q=itr.next();
System.out.println("Question Name: "+q.getQname());
//printing answers
List<String> list2=q.getAnswers();
Iterator<String> itr2=list2.iterator();
while(itr2.hasNext()){
85
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

System.out.println(itr2.next());
}
}
session.close();
System.out.println("success");
}
}

86
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

How to fetch the data of List


Here, we have used HQL to fetch all the records of Question class including answers. In such case, it
fetches the data from two tables that are functional dependent. Here, we are direct printing the object of
answer class, but we have overridden the toString() method in the Answer class returning answername and
poster name. So it prints the answer name and postername rather than reference id.
FetchData.java
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class FetchData {
public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Query query=session.createQuery("from Question");
List<Question> list=query.list();
Iterator<Question> itr=list.iterator();
while(itr.hasNext()){
Question q=itr.next();
System.out.println("Question Name: "+q.getQname());
//printing answers
List<Answer> list2=q.getAnswers();
Iterator<Answer> itr2=list2.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
session.close();
System.out.println("success");
}
}
OUTPUT

87
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Mapping Set in Collection Mapping


If our persistent class has Set object, we can map the Set by set element in the mapping file. The set
element doesn't require index element. The one difference between List and Set is that, it stores only
unique values.
Let's see how we can implement the set in the mapping file:
<class name="com.javatpoint.Question" table="q102">
...
<set name="answers" table="ans102">
<key column="qid"></key>
<element column="answer" type="string"></element>
</set>
...
</class>
Example of mapping set in collection mapping
In this example, we are going to see full example of collection mapping by set. This is the example of set
that stores value not entity reference that is why are going to use element instead of one-to-many.
1) create the Persistent class
This persistent class defines properties of the class including Set.
package com.javatpoint;
import java.util.Set;
public class Question {
private int id;
private String qname;
private Set<String> answers;
//getters and setters
}
2) create the Mapping file for the persistent class
Here, we have created the question.hbm.xml file for defining the list.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Question" table="q102">
88
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
<set name="answers" table="ans102">
<key column="qid"></key>
<element column="answer" type="string"></element>
</set>
</class>
</hibernate-mapping>
3) create the configuration file
This file contains information about the database and mapping file.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.
-->
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4) Create the class to store the data
In this class we are storing the data of the question class.
package com.javatpoint;
import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class StoreData {
89
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

public static void main(String[] args) {


Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
HashSet<String> set1=new HashSet<String>();
set1.add("java is a programming language");
set1.add("java is a platform");
HashSet<String> set2=new HashSet<String>();
set2.add("Servlet is an Interface");
set2.add("Servlet is an API");
Question question1=new Question();
question1.setQname("What is Java?");
question1.setAnswers(set1);
Question question2=new Question();
question2.setQname("What is Servlet?");
question2.setAnswers(set2);
session.persist(question1);
session.persist(question2);
t.commit();
session.close();
System.out.println("success");
}
}
How to fetch the data of Set
Here, we have used HQL to fetch all the records of Question class including answers. In such case, it
fetches the data from two tables that are functional dependent.
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class FetchData {
public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Query query=session.createQuery("from Question");
List<Question> list=query.list();
90
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Iterator<Question> itr=list.iterator();
while(itr.hasNext()){
Question q=itr.next();
System.out.println("Question Name: "+q.getQname());
//printing answers
Set<String> set=q.getAnswers();
Iterator<String> itr2=set.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
session.close();
System.out.println("success");
}
}

91
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Many to Many Mapping in hibernate by map Example (using xml file)


We can map many to many relation either using set, bag, map etc. Here, we are going to use map
for many-to-many mapping. In such case, three tables will be created.
Example of Many to Many Mapping
You need to create following pages for mapping map elements.
Question.java
User.java
question.hbm.xml
user.hbm.xml
hibernate.cfg.xml
StoreTest.java
FetchTest.java
Question.java
package com.javatpoint;
import java.util.Map;
public class Question {
private int id;
private String name;
private Map<String,User> answers;
public Question() {}
public Question(String name, Map<String, User> answers) {
super();
this.name = name;
this.answers = answers;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, User> getAnswers() {
return answers;
}
public void setAnswers(Map<String, User> answers) {
this.answers = answers;
92
}
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
}
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
package com.javatpoint;
.MobileNo:9328994901
import java.util.Map;
public class Question {

Component Mapping
In component mapping, we will map the dependent object as a component. An component is an
object that is stored as an value rather than entity reference. This is mainly used if the dependent
object doen't have primary key. It is used in case of composition (HAS-A relation), that is why it
is termed as component. Let's see the class that have HAS-A relationship.
package com.javatpoint;
public class Address {
private String city,country;
private int pincode;
//getters and setters
}
package com.javatpoint;
public class Employee {
private int id;
private String name;
private Address address;//HAS-A
//getters and setters
}
Here, address is a dependent object. Hibernate framework provides the facility to map the
dependent object as a component. Let's see how can we map this dependent object in mapping
file.
...
<class name="com.javatpoint.Employee" table="emp177">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<component name="address" class="com.javatpoint.Address">
<property name="city"></property>
<property name="country"></property>
<property name="pincode"></property>
</component>
</class>
...
Let's see the data of the emp177 table.

93
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

package com.javatpoint;

94
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

7-Association Mapping
One to One Mapping in Hibernate by many-to-one example
We can perform one to one mapping in hibernate by two ways:
By many-to-one element
By one-to-one element
Here, we are going to perform one to one mapping by many-to-one element. In such case, a
foreign key is created in the primary table.
In this example, one employee can have one address and one address belongs to one employee
only. Here, we are using bidirectional association. Let's look at the persistent classes.
1) Persistent classes for one to one mapping
There are two persistent classes Employee.java and Address.java. Employee class contains
Address class reference and vice versa.
Employee.java
package com.javatpoint;
public class Employee {
private int employeeId;
private String name,email;
private Address address;
//setters and getters
}
Address.java
package com.javatpoint;
public class Address {
private int addressId;
private String addressLine1,city,state,country;
private int pincode;
private Employee employee;
//setters and getters
}
2) Mapping files for the persistent classes
The two mapping files are employee.hbm.xml and address.hbm.xml.
employee.hbm.xml
In this mapping file we are using many-to-one element with unique="true" attribute to make the
one to one mapping.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp211">
<id name="employeeId">
95
<generator class="increment"></generator>
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
</id>nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
<property name="name"></property>
.MobileNo:9328994901
<property name="email"></property>
<many-to-one name="address" unique="true" cascade="all"></many-to-one>

One to One Mapping in Hibernate by one-to-one example


As We have discussed in the previous example, there are two ways to perform one to one
mapping in hibernate:
By many-to-one element
By one-to-one element
Here, we are going to perform one to one mapping by one-to-one element. In such case, no
foreign key is created in the primary table.
In this example, one employee can have one address and one address belongs to one employee
only. Here, we are using bidirectional association. Let's look at the persistent classes.
1) Persistent classes for one to one mapping
There are two persistent classes Employee.java and Address.java. Employee class contains
Address class reference and vice versa.
Employee.java
package com.javatpoint;
public class Employee {
private int employeeId;
private String name,email;
private Address address;
//setters and getters
}
Address.java
package com.javatpoint;
public class Address {
private int addressId;
private String addressLine1,city,state,country;
private int pincode;
private Employee employee;
//setters and getters
}
2) Mapping files for the persistent classes
The two mapping files are employee.hbm.xml and address.hbm.xml.
employee.hbm.xml
In this mapping file we are using one-to-one element in both the mapping files to make the one
to one mapping.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
96
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp212">
<id name="employeeId">
<mapping resource="employee.hbm.xml"/>
<mapping resource="address.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Iterator<Employee> itr=list.iterator();
while(itr.hasNext()){
Employee emp=itr.next();
System.out.println(emp.getEmployeeId()+" "+emp.getName()+" "+emp.getEmail());
Address address=emp.getAddress();
System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+
address.getState()+" "+address.getCountry());
}
session.close();
System.out.println("success");
}
<one-to-one name="address" cascade="all"></one-to-one>
</class>
</hibernate-mapping>
address.hbm.xml
<generator class="increment"></generator>
</id>
<property name="name"></property>
<property name="email"></property>
This is the simple mapping file for the Address class. But the important thing is generator class.
Here, we
are using foreign generator class that depends on the Employee class primary key.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Address" table="address212">
<id name="addressId">
<generator class="foreign">
<param name="property">employee</param>
97
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

</generator>

</id>
<property name="addressLine1"></property>
<property name="city"></property>
<property name="state"></property>
<property name="country"></property>
<one-to-one name="employee"></one-to-one>
</class>
</hibernate-mapping>
3) Configuration file
This file contains information about the database and mapping file.
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.
-->
<hibernate-configuration>
4) User classes to store and fetch the data
Store.java
package com.javatpoint;
import org.hibernate.cfg.*;
import org.hibernate.*;
public class Store {
public static void main(String[] args) {
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session session=sf.openSession();
Transaction tx=session.beginTransaction();
Employee e1=new Employee();
e1.setName("Ravi Malik");
e1.setEmail("ravi@gmail.com");
Address address1=new Address();
address1.setAddressLine1("G-21,Lohia nagar");
address1.setCity("Ghaziabad");
address1.setState("UP");
98
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

address1.setCountry("India");
address1.setPincode(201301);

e1.setAddress(address1);
address1.setEmployee(e1);
session.persist(e1);
tx.commit();
session.close();
System.out.println("success");
}
}
Fetch.java
package com.javatpoint;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
Configuration cfg=new Configuration();
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Fetch {
public static void main(String[] args)
{ cfg.configure("hibernate.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session session=sf.openSession();
Query query=session.createQuery("from Employee e");
}

List<Employee> list=query.list();
Iterator<Employee> itr=list.iterator
();
while(itr.hasNext()){
Employee emp=itr.next();
System.out.println(emp.getEmp
loyeeId()+" "+emp.getName()
+" "+emp.getEmail());
Address address=emp.getAddre
ss();
System.out.println(address.getA

ddressLine1()+" "+address.getCity()+" "+


address.getState()+" "+address.getCountry());
}
session.close();
System.out.println("success");
}
}

99
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

8. Transaction Management
Hibernate Transaction Management Example
A transaction simply represents a unit of work. In such case, if one step fails, the whole
transaction fails (which is termed as atomicity). A transaction can be described by ACID
properties (Atomicity, Consistency, Isolation and Durability).

Transaction Interface in Hibernate


In hibernate framework, we have Transaction interface that defines the unit of work. It maintains
abstraction from the transaction implementation (JTA,JDBC).
A transaction is associated with Session and instantiated by calling session.beginTransaction().
The methods of Transaction interface are as follows:
void begin() starts a new transaction.
void commit() ends the unit of work unless we are in FlushMode.NEVER.
void rollback() forces this transaction to rollback.
void setTimeout(int seconds) it sets a transaction timeout for any transaction started by a
subsequent call to begin on this instance.
boolean isAlive() checks if the transaction is still alive.
void registerSynchronization(Synchronization s) registers a user synchronization callback for
this transaction.
boolean wasCommited() checks if the transaction is commited successfully.
boolean wasRolledBack() checks if the transaction is rolledback successfully.
Example of Transaction Management in Hibernate
In hibernate, it is better to rollback the transaction if any exception occurs, so that resources can
be free. Let's see the example of transaction management in hibernate.
Session session = null;
Transaction tx = null;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
100
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

//some action
tx.commit();
}catch (Exception ex) {
ex.printStackTrace();
tx.rollback();
}
finally {session.close();}

101
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

9-Hibernate Query Language

102
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Hibernate Query Language (HQL)


Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't
depends on the table of the database. Instead of table name, we use class name in HQL. So it is
database independent query language.
Advantage of HQL
There are many advantages of HQL. They are as follows:
database independent
supports polymorphic queries
easy to learn for Java Programmer
Query Interface
It is an object oriented representation of Hibernate Query. The object of Query can be obtained
by calling the createQuery() method Session interface.
The query interface provides many methods. There is given commonly used methods:
public int executeUpdate() is used to execute the update or delete query.
public List list() returns the result of the ralation as a list.
public Query setFirstResult(int rowno) specifies the row number from where record will be
retrieved.
public Query setMaxResult(int rowno) specifies the no. of records to be retrieved from the
relation (table).
public Query setParameter(int position, Object value) it sets the value to the JDBC style
query parameter.
public Query setParameter(String name, Object value) it sets the value to a named query
parameter.
Example of HQL to get all the records
Query query=session.createQuery("from Emp");//here persistent class name is Emp
List list=query.list();
Example of HQL to get records with pagination
Query query=session.createQuery("from Emp");
query.setFirstResult(5);
query.setMaxResult(10);
List list=query.list();//will return the records from 5 to 10th number
Example of HQL update query
Transaction tx=session.beginTransaction();
Query q=session.createQuery("update User set name=:n where id=:i");
q.setParameter("n","Udit Kumar");
q.setParameter("i",111);
int status=q.executeUpdate();
System.out.println(status);
tx.commit();
Example of HQL delete query
Query query=session.createQuery("delete from Emp where id=100");
//specifying class name (Emp) not tablename
query.executeUpdate();
HQL with Aggregate functions
You may call avg(), min(), max() etc. aggregate functions by HQL. Let's see some common
examples:
Example to get total salary of all the employees
103
Query q=session.createQuery("select sum(salary) from Emp");
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
List<Emp> nd
list=q.list();
2 Floor,
Ronak Plaza, Tulsidham Char Rasta, Manjalpur
Iterator<Emp>
itr=list.iterator();
.MobileNo:9328994901
while(itr.hasNext()){
System.out.println(itr.next());
}

104
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

10.HCQL (Hibernate Criteria Query Language)


The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the
specific criteria. The Criteria interface provides methods to apply criteria such as retreiving all
the records of table whose salary is greater than 50000 etc.
Advantage of HCQL
The HCQL provides methods to add criteria, so it is easy for the java programmer to add criteria.
The java programmer is able to add many criteria on a query.
Criteria Interface
The Criteria interface provides many methods to specify criteria. The object of Criteria can be
obtained by calling the createCriteria() method of Session interface.
Syntax of createCriteria() method of Session interface
public Criteria createCriteria(Class c)
The commonly used methods of Criteria interface are as follows:
public Criteria add(Criterion c) is used to add restrictions.
public Criteria addOrder(Order o) specifies ordering.
public Criteria setFirstResult(int firstResult) specifies the first number of record to be retreived.
public Criteria setMaxResult(int totalResult) specifies the total number of records to be
retreived.
public List list() returns list containing object.
public Criteria setProjection(Projection projection) specifies the projection.
Restrictions class
Restrictions class provides methods that can be used as Criterion. The commonly used methods
of Restrictions class are as follows:
public static SimpleExpression lt(String propertyName,Object value) sets the less than constraint
to the given property.
public static SimpleExpression le(String propertyName,Object value) sets the less than or equal
constraint to the given property.
public static SimpleExpression gt(String propertyName,Object value) sets the greater than
constraint to the given property.
public static SimpleExpression ge(String propertyName,Object value) sets the greater than or
equal than constraint to the given property.
public static SimpleExpression ne(String propertyName,Object value) sets the not equal
constraint to the given property.
public static SimpleExpression eq(String propertyName,Object value) sets the equal constraint
to the given property.
public static Criterion between(String propertyName, Object low, Object high) sets the between
constraint.
public static SimpleExpression like(String propertyName, Object value) sets the like constraint
to the given property.
Order class
The Order class represents an order. The commonly used methods of Restrictions class are as
follows:
105
public static Order asc(String propertyName) applies the ascending order on the basis of given
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
property. nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
public static Order desc(String propertyName) applies the descending order on the basis of given
.MobileNo:9328994901
property.

106
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

11.Named Query
Hibernate Named Query
The hibernate named query is way to use any query by some meaningful name. It is like using
alias names. The Hibernate framework provides the concept of named queries so that application
programmer need not to scatter queries to all the java code.
There are two ways to define the named query in hibernate:
by annotation
by mapping file.
Hibernate Named Query by annotation
If you want to use named query in hibernate, you need to have knowledge of @NamedQueries
and @NamedQuery annotations.
@NameQueries annotation is used to define the multiple named queries.
@NameQuery annotation is used to define the single named query.
Let's see the example of using the named queries:
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)
Example of Hibernate Named Query by annotation:
In this example, we are using annotations to defined the named query in the persistent class.
There are three files only:
Employee.java
hibernate.cfg.xml
FetchDemo
In this example, we are assuming that there is em table in the database containing 4 columns id,
name, job and salary and there are some records in this table.
Employee.java
It is a persistent class that uses annotations to define named query and marks this class as entity.
package com.javatpoint;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
107
) B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
}
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
)
.MobileNo:9328994901
@Entity
@Table(name="em")

Hibernate and Struts 2 Integration


We can integrate any struts application with hibernate. There is no requirement of extra efforts.
In this example, we going to use struts 2 framework with hibernate. You need to have jar files for
struts 2 and hibernate.
Example of Hibernate and struts2 integration:
In this example, we are creating the registration form using struts2 and storing this data into the
database using Hibernate. Let's see the files that we should create to integrate the struts2
application with hibernate.
index.jsp file to get input from the user.
User.java A action class for handling the request. It uses the dao class to store the data.
RegisterDao.java A java class that uses DAO design pattern to store the data using hibernate.
user.hbm.xml A mapping file that contains information about the persistent class. In this case,
action class works as the persistent class.
hibernate.cfg.xml A configuration file that contains informations about the database and
mapping file.
struts.xml file contains information about the action class and result page to be invoked.
welcome.jsp A jsp file that displays the welcome information with username.
web.xml A web.xml file that contains information about the Controller of Struts framework.
index.jsp
In this page, we have created a form using the struts tags. The action name for this form is
register.
<%@ taglib uri="/struts-tags" prefix="S" %>
<S:form action="register">
<S:textfield name="name" label="Name"></S:textfield>
<S:submit value="register"></S:submit>
</S:form>
User.java
It is a simple POJO class. Here it works as the action class for struts and persistent class for
hibernate. It calls the register method of RegisterDao class and returns success as the string.
package com.javatpoint;
public class User {
private int id;
private String name;
//getters and setters
public String execute(){
RegisterDao.saveUser(this);
return "success";
}
}
RegisterDao.java
It is a java class that saves the object of User class using the Hibernate framework.
package com.javatpoint;
108
import org.hibernate.Session;
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
import org.hibernate.Transaction;
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
import org.hibernate.cfg.Configuration;
.MobileNo:9328994901
public class RegisterDao {
public static int saveUser(User u){

Hibernate and Spring Integration


We can simply integrate hibernate application with spring application.
In hibernate framework, we provide all the database information hibernate.cfg.xml file.
But if we are going to integrate the hibernate application with spring, we don't need to create the
hibernate.cfg.xml file. We can provide all the information in the applicationContext.xml file.
Advantage of Spring framework with hibernate:
The Spring framework provides HibernateTemplate class, so you don't need to follow so many
steps like create Configuration, BuildSessionFactory, Session, beginning and committing
transaction etc.
So it saves a lot of code.
Understanding problem without using spring:
Let's understand it by the code of hibernate given below:
//creating configuration
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
//creating seession factory object
SessionFactory factory=cfg.buildSessionFactory();
109
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

//creating session object


Session session=factory.openSession();
//creating transaction object
Transaction t=session.beginTransaction();
Employee e1=new Employee(111,"arun",40000);
session.persist(e1);//persisting the object
t.commit();//transaction is commited
session.close();
As you can see in the code of sole hibernate, you have to follow so many steps.
Solution by using HibernateTemplate class of Spring Framework:
Now, you don't need to follow so many steps. You can simply write this:
Employee e1=new Employee(111,"arun",40000);
hibernateTemplate.save(e1);
Methods of HibernateTemplate class
Let's see a list of commonly used methods of HibernateTemplate class.
Steps:
Let's see what are the simple steps for hibernate and spring integration:
create table in the database It is optional.
create applicationContext.xml file It contains information of DataSource, SessionFactory etc.
create Employee.java file It is the persistent class
create employee.hbm.xml file It is the mapping file.
create EmployeeDao.java file It is the dao class that uses HibernateTemplate.
create InsertTest.java file It calls methods of EmployeeDao class.
Example of Hibernate and spring integration
In this example, we are going to integrate the hibernate application with spring. Let's see the
directory structure of spring and hibernate example.

110
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

1) create the table in the database


In this example, we are using the Oracle as the database, but you may use any database. Let's
create the table in the oracle database
CREATE TABLE "EMP558"
( "ID" NUMBER(10,0) NOT NULL ENABLE,
"NAME" VARCHAR2(255 CHAR),
"SALARY" FLOAT(126),
PRIMARY KEY ("ID") ENABLE
)
/
2) Employee.java
It is a simple POJO class. Here it works as the persistent class for hibernate.
package com.javatpoint;
public class Employee {
private int id;
private String name;
private float salary;
//getters and setters
}

3) employee.hbm.xml
This mapping file contains all the information of the persistent class.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
111
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp558">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
4) EmployeeDao.java
It is a java class that uses the HibernateTemplate class method to persist the object of Employee
class.
package com.javatpoint;
import org.springframework.orm.hibernate3.HibernateTemplate;
import java.util.*;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
//method to save employee
public void saveEmployee(Employee e){
template.save(e);
}
//method to update employee
public void updateEmployee(Employee e){
template.update(e);
}
//method to delete employee
public void deleteEmployee(Employee e){
template.delete(e);
}
//method to return one employee of given id
public Employee getById(int id){
Employee e=(Employee)template.get(Employee.class,id);
return e;
}
//method to return all employees
112
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

public List<Employee> getEmployees(){


List<Employee> list=new ArrayList<Employee>();
list=template.loadAll(Employee.class);
return list;
}
}
5) applicationContext.xml
In this file, we are providing all the informations of the database in the BasicDataSource object.
This object is used in the LocalSessionFactoryBean class object, containing some other
informations such as mappingResources and hibernateProperties. The object of
LocalSessionFactoryBean class is used in the HibernateTemplate class. Let's see the code of
applicationContext.xml file.

File: applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="system"></property>
113
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<property name="password" value="oracle"></property>


</bean>
<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFacto
ryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="com.javatpoint.EmployeeDao">
<property name="template" ref="template"></property>
</bean>
</beans>
6) InsertTest.java
This class uses the EmployeeDao class object and calls its saveEmployee method by passing the
object of Employee class.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class InsertTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
114
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

EmployeeDao dao=(EmployeeDao)factory.getBean("d");
Employee e=new Employee();
e.setId(114);
e.setName("varun");
e.setSalary(50000);
dao.saveEmployee(e);
}
}
Now, if you see the table in the oracle database, record is inserted successfully.
Enabling automatic table creation, showing sql queries etc.
You can enable many hibernate properties like automatic table creation by hbm2ddl.auto etc. in
applicationContext.xml file. Let's see the code:
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
If you write this code, you don't need to create table because table will be created automatically.
No. Method

Description

1)

void persist(Object entity)

persists the given object.

2)

Serializable save(Object entity)

persists the given object and returns id.

3)

void saveOrUpdate(Object entity)

persists or updates the given object. If id is found, it updates the


record otherwise saves the record.

4)

void update(Object entity)

updates the given object.

5)

void delete(Object entity)

deletes the given object on the basis of id.

6)

Object get(Class entityClass, Serializable returns the persistent object on the basis of given id.
id)

7)

Object
load(Class
Serializable id)

8)

List loadAll(Class entityClass)

entityClass, returns the persistent object on the basis of given id.


returns the all the persistent objects.

115
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

HibernateInterviewQuestions:
1) What is hibernate?
Hibernate is an open-source and lightweight ORM tool that is used to store, manipulate and
retrieve data from the database.
2) What is ORM?
ORM is an acronym for Object/Relational mapping. It is a programming strategy to map object
with the data stored in the database. It simplifies data creation, data manipulation and data
access.
3) Explain hibernate architecture?
Hibernate architecture comprises of many interfaces such as Configuration, SessionFactory,
Session, Transaction etc.

4) What are the core interfaces of Hibernate?


The core interfaces of Hibernate framework are:
Configuration
SessionFactory
Session
Query
Criteria
Transaction
5) What is SessionFactory?
SessionFactory provides the instance of Session. It is a factory of Session. It holds the data of
second level cache that is not enabled by default.
6) Is SessionFactory a thread-safe object?
Yes, SessionFactory is a thread-safe object, many threads can access it simultaneously.
7) What is Session?
It maintains a connection between hibernate application and database.
It provides methods to store, update, delete or fetch data from the database such as persist(),
update(), delete(), load(), get() etc.
It is a factory of Query, Criteria and Transaction i.e. it provides factory methods to return these
instances.
8) Is Session a thread-safe object?
No, Session is not a thread-safe object, many threads can't access it simultaneously. In other
words, you cannot share it between threads.
9) What is the difference between session.save() and session.persist() method?
No. save()
persist()
returns the identifier (Serializable) of the return nothing because its return type is
1)
instance.
void.
116
2) Syn:
publicManubhai
Serializable save(Object
Syn: public
void persist(Object o)
B-208
Tower , o)
Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
10) What is the difference between
get and load method?
.MobileNo:9328994901
The differences between get() and load() methods are given below.
No. get()
load()

4-Spring Tutorial
117
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

118
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

1.Spring Introduction

This spring tutorial provides in-depth concepts of Spring Framework with simplified examples.
It was developed by Rod Johnson in 2003. Spring framework makes the easy development of
JavaEE application.
It is helpful for beginners and experienced persons.
Spring Framework:
Spring is a lightweight framework. It can be thought of as a framework of frameworks because it
provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc. The
framework, in broader sense, can be defined as a structure where we find solution of the various
technical problems.
The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM,
WEB MVC etc. We will learn these modules in next page. Let's understand the IOC and
Dependency Injection first.
Inversion Of Control (IOC) and Dependency Injection:
These are the design patterns that are used to remove dependency from the programming code.
They make the code easier to test and maintain. Let's understand this with the following code:
class Employee{
Address address;
Employee(){
address=new Address();
}
}
In such case, there is dependency between the Employee and Address (tight coupling). In the
Inversion of Control scenario, we do this something like this:
class Employee{
Address address;
Employee(Address address){
this.address=address;
}
}
Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the code if
our logic is moved to new environment.
In Spring framework, IOC container is responsible to inject the dependency. We provide
metadata to the IOC container either by XML file or annotation.
Advantage of Dependency Injection
makes the code loosely coupled so easy to maintain
makes the code easy to test
Advantages of Spring Framework:
There are many advantages of Spring Framework. They are as follows:
1) Predefined Templates
119
SpringB-208
framework
provides
templates
for
JDBC,
Hibernate,
JPA
etc.
technologies. So there is no
Manubhai Tower , Sayajigunj
MobileNo:9327219987
need to write
ndtoo much code. It hides the basic steps of these technologies.
Floor, of
Ronak
Plaza,you
Tulsidham
Rasta,
Let's take 2
the example
JdbcTemplate,
don't need toChar
write the
code forManjalpur
exception handling,
.MobileNo:9328994901
creating connection, creating statement, committing transaction, closing connection etc. You
need to write the code of executing query only. Thus, it save a lot of JDBC code.

2-Spring IDE
Example of spring application in Myeclipse:
Creating spring application in myeclipse IDE is simple. You don't need to be worried about the
jar files required for spring application because myeclipse IDE takes care of it. Let's see the
simple steps to create the spring application in myeclipse IDE.
create the java project
add spring capabilities
create the class
create the xml file to provide the values
create the test class
Steps to create spring application in Myeclipse IDE:
Let's see the 5 steps to create the first spring application using myeclipse IDE.
1) Create the Java Project
Go to File menu - New - project - Java Project. Write the project name e.g. firstspring - Finish.
Now the java project is created.
2) Add spring capabilities
Go to Myeclipse menu - Project Capabilities - Add spring capabilities - Finish. Now the
spring jar files will be added. For the simple application we need only core library i.e. selected
by default. 3) Create Java class
In such case, we are simply creating the Student class have name property. The name of the
student will be provided by the xml file. It is just a simple example not the actual use of spring.
We will see the actual use in Dependency Injection chapter. To create the java class, Right click
on src - New - class - Write the class name e.g. Student - finish. Write the following code:
package com.javatpoint;
public class Student {
private String name;
public String getName() {
return name;
}
120
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

public void setName(Str


ing name) {
this.name = name;
}
public void displayInfo(
){
System.out.println("H
ello: "+name);
}
}
This is simple bean
class, containing
only one property name
with its getters
and setters method. This
class
contains
one
extra
method
named
displayInfo() that prints the student name by the hello message.
4) Create the xml file
In case of myeclipse IDE, you don't need to create the xml file as myeclipse does this for
yourselves. Open the applicationContext.xml file, and write the following code:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="studentbean" class="com.javatpoint.Student">
<property name="name" value="Vimal Jaiswal"></property>
</bean>
</beans>
The bean element is used to define the bean for the given class. The property subelement of
bean specifies the property of the Student class named name. The value specified in the property
element will be set in the Student class object by the IOC container.
5) Create the test class
Create the java class e.g. Test. Here we are getting the object of Student class from the IOC
container using the getBean() method of BeanFactory. Let's see the code of test class.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
121
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Resource resource=new ClassPathResource("applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(resource);
Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}

122
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

The
Constructor
Resource Injection
object represents
with Collection
the information
Example:
of applicationContext.xml file. The Resource is
the
Weinterface
can inject
andcollection
the ClassPathResource
values by constructor
is the implementation
in spring framework.
class ofThere
the Reource
can be interface.
used three
The
elements
BeanFactory
inside theis constructor-arg
responsible to return
element.
the bean. The XmlBeanFactory is the implementation
class
It canofbe:
the BeanFactory. There are many methods in the BeanFactory interface. One method is
getBean(),
list
which returns the object of the associated class.
Now
set run the Test class. You will get the output Hello: Vimal Jaiswal.
map
Each collection
can have string
basedIDE:
and non-string based values.
Creating
spring application
in Eclipse
In thisweexample,
taking
the example
of Forum
where
One question
can have
Here,
are goingwetoare
create
a simple
application
of spring
framework
using eclipse
IDE.multiple
Let's
answers.
There
are to
three
pages:
see
the simple
steps
create
the spring application in Eclipse IDE.
Question.java
create
the java project
applicationContext.xml
add
spring jar files
Test.java
create
the class
In
this
example,
usingthe
listvalues
that can have duplicate elements, you may use set that have
create the
xml filewe
to are
provide
only unique
create
the testelements.
class But, you need to change list to set in the applicationContext.xml file and
List to Set in the Question.java file.
Question.java
Steps
to create spring application in Eclipse IDE:
This see
class
properties,
two constructors
and displayInfo()
Let's
thecontains
5 steps tothree
create
the first spring
application using
eclipse IDE. method that prints the
information.
are using List to contain the multiple answers.
1)
Create theHere,
Java we
Project
package
com.javatpoint;
Go
to File
menu - New - project - Java Project. Write the project name e.g. firstspring Finish. Now the java project is created.
import
java.util.Iterator;
2)
Add spring
jar files
import
java.util.List;
There are mainly three jar files required to run this application.
org.springframework.core-3.0.1.RELEASE-A
public class Question {
com.springsource.org.apache.commons.logging-1.1.1
private int id;
org.springframework.beans-3.0.1.RELEASE-A
private
String
name;you need to load only spring core jar files.
To
run this
example,
private
To
load List<String>
the jar files inanswers;
eclipse IDE, Right click on your project - Build Path - Add external
public Question()
archives
- select all{}the required jar files - finish..
public
Question(int
3)
Create
Java classid, String name, List<String> answers) {
super();
In such
case, we are simply creating the Student class have name property. The name of the
this.id
= id;
student
will
be provided by the xml file. It is just a simple example not the actual use of spring.
= name;
Wethis.name
will see the
actual use in Dependency Injection chapter. To create the java class, Right click
this.answers
= answers;
on src - New - class
- Write the class name e.g. Student - finish. Write the following code:
}
package
com.javatpoint;
public void displayInfo(){
System.out.println(id+"
"+name);
public
class Student {
System.out.println("answers
are:");
private
String name;
Iterator<String>
itr=answers.iterator();
public
String getName()
{
while(itr.hasNext()){
return
name;
System.out.println(itr.next());
}
} void setName(String name) {
public
} this.name = name;
}}
applicationContext.xml
public
void displayInfo(){
The
list element of constructor-arg
is used here to define the list.
System.out.println("Hello:
"+name);
}<?xml version="1.0" encoding="UTF-8"?>
}<beans
Thisxmlns="http://www.springframework.org/schema/beans"
is simple bean class, containing only one property name with its getters and setters method.
Thisxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
class contains one extra method named displayInfo() that prints the student name by the
xmlns:p="http://www.springframework.org/schema/p"
hello
message.
123
xsi:schemaLocation="http://www.springframework.org/schema/beans
4) Create
the
xml
file
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
To
create ndthe xml file click on src - new - file - give the file name such as
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
applicationContext.xml - finish. Open the applicationContext.xml file, and write the following
.MobileNo:9328994901
<bean id="q" class="com.javatpoint.Question">
code:
<constructor-arg
value="111"></constructor-arg>
<?xml
version="1.0"
encoding="UTF-8"?>
<constructor-arg value="What is java?"></constructor-arg>
<beans

<list>
<value>Java is a programming language</value>
<value>Java is a Platform</value>
<value>Java is an Island of Indonasia</value>
</list>
</constructor-arg>
5-Spring
JDBC Template
</bean>
</beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the displayInfo method.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo()
}
}
Constructor Injection with Non-String Collection (having Dependent Object) Example:
If we have dependent object in the collection, we can inject these information by using the ref
element inside the list, set or map.
In this example, we are taking the example of Forum where One question can have multiple
answers. But Answer has its own information such as answerId, answer and postedBy. There are
four pages used in this example:
Question.java
Answer.java
applicationContext.xml
Test.java
In this example, we are using list that can have duplicate elements, you may use set that have
only unique elements. But, you need to change list to set in the applicationContext.xml file and
List to Set in the Question.java file.
Question.java
This class contains three properties, two constructors and displayInfo() method that prints the
information. Here, we are using List to contain the multiple answers.
package com.javatpoint;
import java.util.Iterator;
import java.util.List;
public class Question {
private int id;
private String name;
private List<Answer> answers;
public Question() {}
124
publicB-208
Question(int
id, StringTower
name, List<Answer>
answers) MobileNo:9327219987
{
Manubhai
, Sayajigunj
nd
super();
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
this.id = id;
.MobileNo:9328994901
this.name = name;
this.answers = answers;
}

p
ublic void
displayInfo(){
Spring
JdbcTemplate
Tutorial

System.out.println(id+"
Spring
JdbcTemplate is a"+name);
powerful mechanism to connect to the database and execute SQL
System.out.println("answers
queries.
It internally uses JDBCare:");
api, but eliminates a lot of problems of JDBC API.
Iterator<Answer>
itr=answers.iterator();
Problems of JDBC API
while(itr.hasNext()){
The
problems of JDBC API are as follows:
System.out.println(itr.next());
We need
to write a lot of code before and after executing the query, such as creating connection,
}
statement,
closing resultset, connection etc.
} need to perform exception handling code on the database logic.
We
} need to handle transaction.
We
Answer.java
Repetition of all these codes from one to another database logic is a time consuming task.
This class has
three properties
id, name and by with constructor and toString() method.
Advantage
of Spring
JdbcTemplate
packageJdbcTemplate
com.javatpoint;
Spring
eliminates all the above mentioned problems of JDBC API. It provides you
methods to write the queries directly, so it saves a lot of work and time.
public class Answer {
private Jdbc
int id;Approaches
Spring
private framework
String name;
Spring
provides following approaches for JDBC database access:
private String by;
JdbcTemplate
NamedParameterJdbcTemplate
public Answer() {}
SimpleJdbcTemplate
public Answer(intand
id, String
name, String by) {
SimpleJdbcInsert
SimpleJdbcCall
super();
this.id = id; class:
JdbcTemplate
this.name
= name;
It is
the central
class in the Spring JDBC support classes. It takes care of creation and release of
this.by =such
by; as creating and closing of connection object etc. So it will not lead to any
resources
}
problem
if you forget to close the connection.
public
StringthetoString(){
It
handles
exception and provides the informative exception messages by the help of
return id+"
"+name+"
excepion
classes
defined "+by;
in the org.springframework.dao package.
} can perform all the database operations by the help of JdbcTemplate class such as insertion,
We
}
updation,
deletion and retrieval of the data from the database.
applicationContext.xml
Let's see the methods of spring JdbcTemplate class.
The ref element is used to define the reference of another bean. Here, we are using bean attribute
Noref Method
Description
of
element to specify the reference of another
bean.
.<?xml version="1.0" encoding="UTF-8"?>
<beans
1) public int update(String query)
is used to insert, update and delete records.
xmlns="http://www.springframework.org/schema/beans"
2)xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
public int update(String query,Object... is used to insert, update and delete records
xmlns:p="http://www.springframework.org/schema/p"
args)
using PreparedStatement using given
xsi:schemaLocation="http://www.springframework.org/schema/beans
arguments.
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
3) public
void class="com.javatpoint.Answer">
execute(String query)
is used to execute DDL query.
<bean
id="ans1"
<constructor-arg value="1"></constructor-arg>
4) public
Tvalue="Java
execute(String
sql, executes
the
query
by
using
<constructor-arg
is a programming
language"></constructor-arg>
PreparedStatementCallback
action)
PreparedStatement
callback.
<constructor-arg value="John"></constructor-arg>
</bean>
5) public
T
query(String
sql, is used to fetch records using
<beanResultSetExtractor
id="ans2" class="com.javatpoint.Answer">
rse)
ResultSetExtractor.
<constructor-arg value="2"></constructor-arg>
<constructor-arg
6) public
List
value="Java
query(String
is a Platform"></constructor-arg>
sql, is used to fetch records using RowMapper.
<constructor-arg
RowMappervalue="Ravi"></constructor-arg>
rse)
</bean>
Example of Spring JdbcTemplate:
<bean
class="com.javatpoint.Question">
We areid="q"
assuming
that you have created the following table inside the Oracle10g database.
<constructor-arg
value="111"></constructor-arg>
create table employee(
125
<constructor-arg
value="What
is
java?"></constructor-arg>
id number(10),
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
<constructor-arg>
nd
name varchar2(100),
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
<list>
salary number(10)
.MobileNo:9328994901
<ref
); bean="ans1"/>
<ref bean="ans2"/>
</list>
Employee.java

</bean>
Hibernate
and Spring Integration
</beans>
We
canIntegration
simply
integrate hibernate application with spring application.
Remoting
Spring
andinJMS
Spring
Framework
Test.java
In
hibernate
framework,
we
provide
all
the database
information
Spring
To
integrate
framework
spring
makes
with
JMS,
the
you
developement
need
to create
of remote-enabled
two
applications.
services
easy.
savesthea displayInfo
lot of file.method.
Spring
Integration
Example
This classand
getsJAXB
the
bean
from
the
applicationContext.xml
file
andIthibernate.cfg.xml
calls
But
if
we
are
going
to
integrate
the
hibernate
application
with
spring,
we
don't
to create
code Receiver
JMS
by providing
Application
its is
own
JAXB
an API.
acronym for Java Architecture for XML Binding. It allows javaneed
developers
to the
map
package
com.javatpoint;
hibernate.cfg.xml
file.
We
can
provide
all
the
information
in
the
applicationContext.xml
file.
Advantage
JMS
SenderofApplication
Spring
Remoting
Java class to XML representation. JAXB can be used to marshal java objects into XML and viceThecreate
To
programmer
JMS versa.
application
needs
to concentrate
using spring,onwebusiness
are using
logic
Active
onlyMQ
not Server
plumbing
of Apache
activitiesto such
createas
import
org.springframework.beans.factory.BeanFactory;
Advantage
of
Spring
framework
with
hibernate:
starting
the
Queue.
and stopping
the
server.
It
is an org.springframework.beans.factory.xml.XmlBeanFactory;
OXM (Object XML Mapping) or O/M framework provided by Sun.
import
The
Spring
HibernateTemplate
Spring
Let's
see
framework
the simple
supports
steps
toframework
following
integrationprovides
remoting
spring application
technologies:
with JMS: class, so you don't need to follow so many
import org.springframework.core.io.ClassPathResource;
steps
like
create
Configuration, BuildSessionFactory, Session, beginning and committing
Remote Method
Invocation
(RMI)
Advantage
of
JAXB:
import
org.springframework.core.io.Resource;
transaction
etc.
Spring's HTTP
Required
Jar Files
invoker
No
need to create or use a SAX or DOM parser and write callback methods.
So
it
lot of
code.
Hessian
1)
You need toExample
add
spring
core,
misc,spring
aop,(Marshalling
spring j2eeJava
and Object
spring into
persistence
ofaSpring
and
JAXB
Integration
XML):
publicsaves
class
Test
{ spring
problem
without
using
spring:
Burlap
core
jar files. Understanding
You
need
to create
following files
for {marshalling java object into XML using Spring with JAXB:
public
static
void main(String[]
args)
Let's
understand
it
by
the
code
of
hibernate
given below:
JAX-RPC (J2EE
1.4
API)
Employee.java
Resource r=new ClassPathResource("applicationContext.xml");
JAX-WS
2)
Add activemqall5.9.jar
(Java//creating
EE
5 andconfiguration
Java
file located
EE
6 API)
inside XmlBeanFactory(r);
the activemq directory.
applicationContext.xml
BeanFactory
factory=new
Configuration
cfg=new
Configuration();
JMS a queueClient.java
Create
inQuestion
ActiveMQ
Server
q=(Question)factory.getBean("q");
cfg.configure("hibernate.cfg.xml");
Download the Active
MQ
Server
q.displayInfo(); Double Click on the activemq.bat file located inside apache//creating
seession
factory object
Remote Method
activemq-5.9.1-bin\apache-activemq-5.9.1\bin\win64
(RMI)
or win32 directory.
Required
Jar
files
} Invocation
SessionFactory
factory=cfg.buildSessionFactory();
By the
Now
activemq
help ofTo
server
RmiServiceExporter
console
will
open.
and
RmiProxyFactoryBean
classes, spring framework
run
this
example,
you
need
to
load:
}
//creating
session
object
supportsthe
Access
RMI
admin
provided
console
byof
Sun.
activemq
Spring
Core
jar
files server by http://localhost:8161/admin/ url.
Session
session=factory.openSession();
Spring
Web
jar
files
Constructor Injection with Map Example:
//creating
transaction
object
Spring's HTTP
Ininvoker
this example,
we are
using map as the answer that have answer with posted username. Here,
Transaction
t=session.beginTransaction();
Spring providesEmployee.java
own
remoting
that both
allows
by HTTP. The classes used
weitsare
using
key andservice
value pair
as serialization
a string.
Employee
e1=new
Employee(111,"arun",40000);
in HTTP Invoker
are
HttpInvokerServiceExporter
and
HttpInvokerProxyFactoryBean.
If
defines
three examples,
properties id,
salary.ofWe
have where
used following
annotations
in thismultiple
class:
Like
previous
it isname
the and
example
forum
one question
can have
session.persist(e1);//persisting
the
object
@XmlRootElement
It
specifies
the
root
element
for
the
xml
file.
answers.
t.commit();//transaction
is commited
Hessian
@XmlAttribute
attribute for the property.
Question.java It specifies
session.close();
It also provides@XmlElement
remoting
service
by
using
http
protocol.
is provided and
by Coucho.
The classes
It
specifies
the
element.
This class contains three properties,
two Itconstructors
displayInfo()
method to display the
you
can
see
in
the
code
of
sole
hibernate,
you
have
to
follow
so
many
steps.
used in HessianAs
are
HessianServiceExporter
and
HessianProxyFactoryBean.
package
com.javatpoint;
information.
Solution
by using HibernateTemplate class of Spring Framework:
import
packagejavax.xml.bind.annotation.XmlAttribute;
com.javatpoint;
Now,
don't need to follow so many steps. You can simply write this:
Burlap
import
javax.xml.bind.annotation.XmlElement;
importyou
java.util.Iterator;
Employee
e1=new Employee(111,"arun",40000);
It is same as Hessian
XML-based
implementation provided by Coucho. The classes used in
import
javax.xml.bind.annotation.XmlRootElement;
importbut
java.util.Map;
hibernateTemplate.save(e1);
Burlap are BurlapServiceExporter
and
BurlapProxyFactoryBean.
import java.util.Set;
@XmlRootElement(name="employee")
import java.util.Map.Entry;
Methods
of HibernateTemplate
class:
JAX-RPC
public class
Employee {
see
list
of commonly
used methods
of HibernateTemplate
Spring providesLet's
remoting
support
for{web services
using JAX-RPC.
It uses J2EEclass.
1.4 API.
private
inta id;
public
class
Question
No. Method
Description
private
String
private
int id; name;
JAX-WS
1)
void
persist(Object
entity)
persists the given object.
private
private float
Stringsalary;
name;
It is the successor
of Map<String,String>
JAX-RPC.
It uses Java
EE 5 and
Javathe
EEgiven
6 API.
The and
classes
used
@XmlAttribute(name="id")
2) Serializable
save(Object
entity)
persists
object
returns
id.in
private
answers;
JAX-WS
Now,
click
are SimpleJaxWsServiceExporter
and
JaxWsPortProxyFactoryBean.
on
the
Queues
public
int
getId()
{
3) void saveOrUpdate(Object entity) persists or updates the given object. If id is found, it
link, write myqueue
in
the textfield
button.
return
id;
updates
the record otherwise saves the record.
public
Question()
{} and click on the create
JMS
}public
Question(int
id, String
answers) {
4) void
update(Object
entity)name, Map<String,
updates theString>
given object.
Spring supports
remoting
service
using
JMS.
The
classes
used in JMS are
public
void
setId(int
id)
{
5) super();
void delete(Object entity)
deletes the given object on the basis of id.
JmsInvokerServiceExporter
and JmsInvokerProxyFactoryBean.
this.id =
= id;
id; get(Class
6) this.id
Object
entityClass, returns the persistent object on the basis of given id.
} this.name = name;
Serializable id)
@XmlElement(name="name")
= answers; entityClass, returns the persistent object on the basis of given id.
7) this.answers
Object
load(Class
public
String
getName()
{
}
Spring and RMISerializable
Integration
id)
return
name;
void displayInfo(){
Spring RMI lets8)public
youList
expose
your services
through the returns
RMI infrastructure.
loadAll(Class
entityClass)
the all the persistent objects.
}
System.out.println("question
id:"+id);
Spring provides an easy way to run RMI application by the help of
public
void setName(String name)
{
System.out.println("question
name:"+name);
org.springframework.remoting.rmi.RmiProxyFactoryBean
and
Steps:
this.name
=
name;
System.out.println("Answers....");
org.springframework.remoting.rmi.RmiServiceExporter
classes.
Let's
see what are the simple steps for hibernate
and spring integration:
} Set<Entry<String,
String>> set=answers.entrySet();
create table in the database It is optional.
126
@XmlElement(name="salary")
Iterator<Entry<String, String>> itr=set.iterator();
RmiServiceExporter
create
applicationContext.xml
file
It
contains
information
of
DataSource,
SessionFactory etc.
B-208
Manubhai
, Sayajigunj
MobileNo:9327219987
float getSalary()
{the Tower
while(itr.hasNext()){
It provides thepublic
exportation
service
for
rmi
object.
This
service
can
be
accessed
via
plain
create
Employee.java
file
It
is
the
persistent
class
nd
return
salary;
2
Floor, Ronak
Plaza, Tulsidham Char Rasta, Manjalpur
Entry<String,String>
entry=itr.next();
RMI or RmiProxyFactoryBean.
create
employee.hbm.xml
file It is the mapping file.
}
System.out.println("Answer:"+entry.getKey()+"
Posted By:"+entry.getValue());
create
EmployeeDao.java
file It.MobileNo:9328994901
is{ the dao class that uses HibernateTemplate.
public
void
setSalary(float
salary)
}
RmiProxyFactoryBean
create
InsertTest.java
It calls methods of EmployeeDao class.
this.salary
salary; file
}
It is the factory bean
for Rmi= Proxies.
It exposes the proxied service that can be used as a bean
}

applicationContext.xml
In this
example,
we are spring
going application
to integrate with
the hibernate
application with spring. Let's see the
Let's see the simple
steps
to integration
JMS:and value
The entry
attribute
of map is used
to define the key
information.
Example of Spring
and RMI
Integration:
directory
structure
of
spring
and
hibernate
example.
MyMessageListener.java
applicationContext.xml
<?xmlsteps
version="1.0"
encoding="UTF-8"?>
Let's see the simple
to integration
spring application with RMI:
TestListener.java
It
defines
a
bean
jaxbMarshallerBean
where Employee class is bound with the OXM framework.
<beans
Calculation.java
applicationContext.xml
<?xml
version="1.0" encoding="UTF-8"?>
xmlns="http://www.springframework.org/schema/beans"
CalculationImpl.java
1)
MyMessageListener.java
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
applicationContext.xml
package
com.javatpoint;
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
client-beans.xml
import
javax.jms.Message;
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans
Host.java
Spring
with Xstream Example
import
javax.jms.MessageListener;
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
Client.java
Xstream
is a library to serialize objects to xml and vice-versa without requirement of any
import javax.jms.TextMessage;
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
mapping file. Notice
that castorMessageListener{
requires an mapping file.
public class MyMessageListener
implements
http://www.springframework.org/schema/oxm
<bean
id="q" class="com.javatpoint.Question">
Required
Jar
files
XStreamMarshaller
class
provides
facility to marshal objects into xml and vice-versa.
@Override <constructor-arg
http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
value="11"></constructor-arg>
Topublic
run this
example,
you
need
to
load:
void onMessage(Message
m) {
<constructor-arg
value="What
is Integration
Java?"></constructor-arg>
Spring
Core jar
files
Example
of Spring
and Xstream
(Marshalling Java Object into XML)
TextMessage
message=(TextMessage)m;
<oxm:jaxb2-marshaller
id="jaxbMarshallerBean">
<constructor-arg>
Spring
Remoting
jar
files
You need to create following files for marshalling java object into XML using Spring with
try{
<map>
Spring System.out.println(message.getText());
AOP jar
files <oxm:class-to-be-bound name="com.javatpoint.Employee"/>
Xstream:
</oxm:jaxb2-marshaller>
<entry
key="Java is a Programming Language" value="Ajay Kumar"></entry>
Employee.java
}catch (Exception
e)the
{e.printStackTrace();
}
1)
create
tableisina Platform"
the database
</beans>
<entry
key="Java
value="John
Smith"></entry>
1) }Calculation.java
applicationContext.xml
<entry
key="Java
is
an
Island"
value="Raj
Kumar"></entry>
interface containing one method cube.
Client.java
}It is the simpleClient.java
</map>
package com.javatpoint;
It
gets the instance of Marshaller from the applicationContext.xml file and calls the marshal
</constructor-arg>
Required Jar files
2) TestListener.java
method.
</bean>
public interface
Calculation
{
To
run this example,
you need to load:
package
com.javatpoint;
package
com.javatpoint;
</beans>
int
cube(int
number);
Spring
Core
jar
files
import org.springframework.context.support.GenericXmlApplicationContext;
import
java.io.FileWriter;
Test.java
}
Spring Web
files
public
class TestListener
{getsjar
import
java.io.IOException;
This
class
the bean from the applicationContext.xml file and calls the displayInfo() method.
2)
CalculationImpl.java
xstream-1.3.jar
public static void
main(String[]
args) {
import
package
com.javatpoint;
This
class provides
thejavax.xml.transform.stream.StreamResult;
implementation
of Calculation
interface.
Employee.java
GenericXmlApplicationContext
ctx=new
GenericXmlApplicationContext();
import
org.springframework.context.ApplicationContext;
package
com.javatpoint;
If defines three properties id, name and salary with setters and getters.
ctx.load("classpath:applicationContext.xml");
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import
packageorg.springframework.beans.factory.BeanFactory;
com.javatpoint;
ctx.refresh();import
org.springframework.oxm.Marshaller;
import
org.springframework.beans.factory.xml.XmlBeanFactory;
public class CalculationImpl
implements
public class Employee
{ Calculation{
import
org.springframework.core.io.ClassPathResource;
@Override private int id;
while(true){}
public
class
Client{
import
org.springframework.core.io.Resource;
{ return number*number*number; } }
privatenumber)
String name;
} public int cube(int
public static void main(String[] args)throws IOException{
private float salary;
}
ApplicationContext
public
class Test { context = new ClassPathXmlApplicationContext("applicationContext.xml")
3) applicationContext.xml
;
void {main(String[]
args) {
In applicationContext.xml
this xml filepublic
we arestatic
the bean for CalculationImpl
class and RmiServiceExporter
public
intdefining
getId()
3)
Marshaller
marshaller
=
(Marshaller)context.getBean("jaxbMarshallerBean");
Resource
r=new
ClassPathResource("applicationContext.xml");
class.
We
need
to
provide
values
for
the
following
properties
of
RmiServiceExporter class.
return
id;
<?xml version="1.0"
encoding="UTF-8"?>
Employee
employee=new
Employee();
BeanFactory
factory=new
XmlBeanFactory(r);
service
}
<beans
employee.setId(101);
Question
q=(Question)factory.getBean("q");
serviceInterface
public
void setId(int
id) {
xmlns="http://www.springframework.org/schema/beans"
employee.setName("Sonoo
Jaiswal");
q.displayInfo();
serviceName
this.id = id;
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
}}employee.setSalary(100000);
replaceExistingBinding
xmlns:jms="http://www.springframework.org/schema/jms"
marshaller.marshal(employee, new StreamResult(new FileWriter("employee.xml")));
registryPort }public
String getName() {
System.out.println("XML
Created Sucessfully");
<?xml
version="1.0"
encoding="UTF-8"?>
return
name;
xmlns:p="http://www.springframework.org/schema/p"
}
Inheriting
Bean in Spring
<beans
xmlns="http://www.springframework.org/schema/beans"
}
xsi:schemaLocation="http://www.springframework.org/schema/beans
}
By
using
thesetName(String
parent attributename)
of bean,
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
public
void
{ we can specify the inheritance relation between the beans.
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Output
the parent
example:
In this.name
such of
case,
bean
values
will
be inherited to the current bean.
xsi:schemaLocation="http://www.springframework.org/schema/beans
= name;
http://www.springframework.org/schema/jms
employee.xml
Let's
see
the
simple
example
to
inherit
the bean.
http://www.springframework.org/schema/beans/spring-beans.xsd">
}
http://www.springframework.org/schema/jms/spring-jms-3.0.xsd">
<?xml
version="1.0"
encoding="UTF-8"
standalone="yes"?>
Employee.java
public float getSalary() {
<employee
id="101">
This
classsalary;
contains
three properties, three constructor and show() method to display the values.
<bean id="calculationBean"
class="com.javatpoint.CalculationImpl"></bean>
return
<bean
id="connectionFactory"
class="org.apache.activemq.ActiveMQConnectionFactory"
<name>Sonoo
Jaiswal</name>
package
com.javatpoint;
<bean
class="org.springframework.remoting.rmi.RmiServiceExporter">
}
p:brokerURL="tcp://localhost:61616"
/>
<salary>100000.0</salary>
<property
name="service"
ref="calculationBean"></property>
public
void
setSalary(float
salary) {
<bean id="listener"
class="com.javatpoint.MyMessageListener"></bean>
</employee>
public
class Employee
{value="com.javatpoint.Calculation"></property>
<property
name="serviceInterface"
this.salary
=
salary;
<jms:listener-container container-type="default" connection-factory="connectionFactory"
private
int id;
<property name="serviceName"
value="CalculationService"></property>
}
acknowledge="auto">
private String name;
<property name="replaceExistingBinding"
value="true"></property>
<jms:listener
destination="myqueue" ref="listener"
method="onMessage"></jms:listene>
private Address address;
<property
name="registryPort"
value="1099"></property>
127
</jms:listener-container>
publicB-208
Employee()
{}
</bean>
Manubhai
Tower , Sayajigunj
MobileNo:9327219987
</beans>
nd
public Employee(int
id,
String
name)
{
</beans>
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
super();
.MobileNo:9328994901
2) JMS Sender Application
this.id = id;
4) client-beans.xml
Let's
see the files to create the JMS Sender application:
= name;bean for RmiProxyFactoryBean. You need to define two
In this xml file, this.name
we are defining
MyMessageSender.java
} class.
properties of this

applicationContext.xml
public Employee(int id, String name, Address address) {
serviceInterface
1)
MyMessageListener.java
super();
<?xml version="1.0"
encoding="UTF-8"?>
package
com.javatpoint;
this.id = id;
<beans
xmlns="http://www.springframework.org/schema/beans"
import javax.jms.*;
this.name = name;
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
import
org.springframework.beans.factory.annotation.Autowired;
this.address = address;
xsi:schemaLocation="http://www.springframework.org/schema/beans
import
org.springframework.jms.core.JmsTemplate;
}
http://www.springframework.org/schema/beans/spring-beans.xsd">
}
import
org.springframework.jms.core.MessageCreator;
void show(){
applicationContext.xml
import org.springframework.stereotype.Component;
System.out.println(id+"
"+name);
<bean id="calculationBean"
class="org.springframework.remoting.rmi.RmiProxyFactoryBean
It defines a bean
xstreamMarshallerBean where Employee class is bound with the OXM
System.out.println(address);
">
framework.
@Component("messageSender")
}
<property
name="serviceUrl"
value="rmi://localhost:1099/CalculationService"></property>
<?xml version="1.0"
public class MyMessageSender
{ encoding="UTF-8"?>
}
<property
name="serviceInterface"
value="com.javatpoint.Calculation"></property>
<beans xmlns="http://www.springframework.org/schema/beans"
@Autowired Answer.java
</bean>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
private JmsTemplate
jmsTemplate;
package
com.javatpoint;
</beans>
xsi:schemaLocation="http://www.springframework.org/schema/beans
public void sendMessage(final
String
public class Address
{ message){
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
jmsTemplate.send(new
MessageCreator(){
private String
addressLine1,city,state,country;
5) Host.java
@Override
public
Address(String
addressLine1, String
city,
String
country)
It is simply
getting
instance of ApplicationContext.
But
you
needstate,
to runString
this class
first{to
<beanthe
id="xstreamMarshallerBean"
class="org.springframework.oxm.xstream.XStreamMarshal
public Message
createMessage(Session
session)
throws
JMSException
{
super();
run the return
example.
ler">
session.createTextMessage(message);
this.addressLine1 = addressLine1;
package
<property name="annotatedClasses" value="com.javatpoint.Employee"></property>
} com.javatpoint;
this.city = city;
import
org.springframework.context.ApplicationContext;
</bean>
});
this.state = state;
</beans>
}import org.springframework.context.support.ClassPathXmlApplicationContext;
this.country = country;
}
}
public class Host{
Client.java
public
String toString(){
public
static
void
main(String[]
args){
It gets
the
instance
of Marshaller
from
the applicationContext.xml
file and calls the marshal
2) TestJmsSender.java
return
addressLine1+"
"+city+"
"+state+"
"+country;
ApplicationContext
context
=
new
ClassPathXmlApplicationContext("applicationContext.xml
package com.javatpoint;
}method.
");
import
org.springframework.context.support.GenericXmlApplicationContext;
}package com.javatpoint;
System.out.println("Waiting
import java.io.FileWriter;
public class TestJmsSender
{for requests");
applicationContext.xml
}
import
java.io.IOException;
public static void
main(String[]
args) {
<?xml version="1.0" encoding="UTF-8"?>
} GenericXmlApplicationContext
import javax.xml.transform.stream.StreamResult;
ctx=new GenericXmlApplicationContext();
<beans
import org.springframework.context.ApplicationContext;
ctx.load("classpath:applicationContext.xml");
xmlns="http://www.springframework.org/schema/beans"
6) ctx.refresh();
Client.java import
org.springframework.context.support.ClassPathXmlApplicationContext;
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
This
class
gets
the
instance
of Calculation and calls the method.
import sender=ctx.getBean("messageSender",MyMessageSender.class);
org.springframework.oxm.Marshaller;
MyMessageSender
xmlns:p="http://www.springframework.org/schema/p"
package
com.javatpoint;
sender.sendMessage("hello jms3");
xsi:schemaLocation="http://www.springframework.org/schema/beans
public
class Client{
}import org.springframework.context.ApplicationContext;
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public
static void main(String[] args)throws IOException{
}
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"
<bean
public
class Client
); { id="e1" class="com.javatpoint.Employee">
3)
applicationContext.xml
<constructor-arg
value="101"></constructor-arg>
public static
void
main(String[]
args) {= (Marshaller)context.getBean("xstreamMarshallerBean");
Marshaller
marshaller
<?xml
version="1.0"
encoding="UTF-8"?>
<constructor-arg
value="Sachin"></constructor-arg>
ApplicationContext
contextemployee=new
= new
ClassPathXmlApplicationContext("client-beans.xml");
Employee
Employee();
<beans
</bean>
Calculation
calculation
=
(Calculation)context.getBean("calculationBean");
employee.setId(101);
xmlns="http://www.springframework.org/schema/beans"
<bean
id="address1" class="com.javatpoint.Address">
System.out.println(calculation.cube(7));
employee.setName("Sonoo
Jaiswal");
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<constructor-arg
value="21,Lohianagar"></constructor-arg>
} xmlns:context="http://www.springframework.org/schema/context"
employee.setSalary(100000);
<constructor-arg
value="Ghaziabad"></constructor-arg>
} xmlns:jms="http://www.springframework.org/schema/jms"
marshaller.marshal(employee,
new StreamResult(new FileWriter("employee.xml")));
value="UP"></constructor-arg>
How to run this<constructor-arg
example
<constructor-arg
value="USA"></constructor-arg>
First
Compile and
Runwith
the Host.java
Spring
Castor
Example
xmlns:p="http://www.springframework.org/schema/p"
</bean>
Then,
Compile
and
Run
the
Client.java
By the help of CastorMarshaller class, we can marshal the java objects into xml and vicexsi:schemaLocation="http://www.springframework.org/schema/beans
<bean
id="e2"
class="com.javatpoint.Employee"
versa using
castor.
It is the implementation class parent="e1">
for Marshaller and Unmarshaller interfaces. It
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
<constructor-arg
ref="address1"></constructor-arg>
doesn't require any further configuration bydefault.
http://www.springframework.org/schema/context
</bean>
Spring
Remoting
by HTTP Invoker Example:
http://www.springframework.org/schema/context/spring-context-3.0.xsd
</beans>
Spring
provides
its
own of
implementation
of remoting
service
known as Java
HttpInvoker.
can be
Example
Spring and Castor
Integration
(Marshalling
Object intoIt XML)
http://www.springframework.org/schema/jms
Test.java
used
for http request
than to
RMI
and works
wellfiles
across
firewall. java object into XML using Spring with
You need
create
following
forthe
marshalling
http://www.springframework.org/schema/jms/spring-jms-3.0.xsd">
class gets the bean from the applicationContext.xml
file and calls the
show method.
By the help ofThis
HttpInvokerServiceExporter
and HttpInvokerProxyFactoryBean
classes,
128
package
com.javatpoint;
we canid="connectionFactory"
implement
the
remoting
service provided
by Spring's
Http Invokers.MobileNo:9327219987
<bean
class="org.apache.activemq.ActiveMQConnectionFactory"
B-208
Manubhai
Tower
, Sayajigunj
p:brokerURL="tcp://localhost:61616"
/>
2nd Floor, Ronak
Plaza, Tulsidham Char Rasta, Manjalpur
import
org.springframework.beans.factory.BeanFactory;
Http
Invoker
and
Other
Remoting
techniques:
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
.MobileNo:9328994901
import
org.springframework.beans.factory.xml.XmlBeanFactory;
You can use many
Remoting
techniques, let's see
which one can be best for you.
<constructor-arg
name="connectionFactory"
ref="connectionFactory"></constructor-arg>
import
org.springframework.core.io.ClassPathResource;
Http Invoker
Vs RMI
<property
name="defaultDestinationName"
value="myqueue"></property>
import
org.springframework.core.io.Resource;
RMI
uses
JRMP
protocol
whereas
Http
Invokes
uses HTTP protocol. Since enterprise
</bean>

class Invoker.
Test { HTTP Invoker works well across firewalls.
security issuespublic
than HTTP
</beans>
public
static
void
main(String[] args) {
Http Invoker Vs
Hessian
and
Burlap
Resource
r=new
ClassPathResource("applicationContext.xml");
HTTP Invoker is the part of Spring
framework but Hessian and burlap are proprietary. All
BeanFactory
factory=new
XmlBeanFactory(r);
works well across firewall. Hessian and Burlap
are portable to integrate with other languages
Employee
e1=(Employee)factory.getBean("e2");
such as .Net and PHP but HTTP Invoker cannot be.
e1.show();
Castor:
}
Example of Spring HTTP Invoker:
}Employee.java
To create a simple
spring's HTTP invoker application, you need to create following files.
applicationContext.xml
Calculation.java
mapping.xml
CalculationImpl.java
Client.java
web.xml
Dependency Injection by setter method
httpInvoker-servlet.xml
Required
Jar files
We
can inject
the dependency by setter method also. The <property> subelement of <bean> is
client-beans.xml
To
run
this
example,
youHere
needwe
to load:
are going to inject
Client.java used for setter injection.
Spring
Core
jar
files
primitive
and
String-based
values
1) Calculation.java
Spring
Web
jar files
object
(contained
object)
It is the simpleDependent
interface
containing
one method
cube.
castor-1.3.jar
Collection
values
etc.
package com.javatpoint;
castor-1.3-core.jar
primitive
and string-based values by setter method
public interfaceInjecting
Calculation
{
Let's see the simple example to inject primitive and string-based values by setter method. We
int cube(int number);
Employee.java
have
created three files here:
}
If
defines
three properties id, name and salary with setters and getters.
Employee.java
2) CalculationImpl.java
package
com.javatpoint; of Calculation interface.
applicationContext.xml
This class provides
the implementation
public
class
Employee {
Test.java
package com.javatpoint;
private int id; implements Calculation{
Employee.java
public class CalculationImpl
private
String name;
It
is a number)
simple
class
public int cube(int
{ containing three fields id, name and city with its setters and getters and a
private
float
salary;
method to display these informations.
return number*number*number;
package com.javatpoint;
}
public class
int getId()
{
public
Employee
{
}
return
id;
private
int
id;
3) web.xml
} we are
private
String
name;DispatcherServlet as the front controller. If any request is
In this xml file,
defining
public
void
setId(int
id)forwarded
{
private
String
followed by .http extension, itcity;
will be
to DispatcherServlet.
this.id
=
id;
public int
getId() {
<?xml version="1.0"
encoding="UTF-8"?>
} return id;
<web-app version="2.5"
public String getName() {
}
xmlns="http://java.sun.com/xml/ns/javaee"
return
name;
public
void
setId(int id) {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
}
this.id = id;
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
public
void setName(String name) {
}
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
this.name
= name;
public
String
getName() {
}
return name;
<servlet>
public float getSalary() {
}
<servlet-name>httpInvoker</servlet-name>
return
salary;
public
void
setName(String name) {
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
}
this.name = name;
<load-on-startup>1</load-on-startup>
public void setSalary(float salary) {
}
</servlet>
this.salary
salary;
public
String= getCity()
{
}
<servlet-mapping>
return city;
}
<servlet-name>httpInvoker</servlet-name>
<url-pattern>*.http</url-pattern>
applicationContext.xml
</servlet-mapping>
</web-app> It defines a bean castorMarshallerBean where Employee class is bound with the OXM
framework.
4) httpInvoker-servlet.xml
It must be created inside the WEB-INF folder. Its name must be servletname-servlet.xml. It
129
defines bean for CalculationImpl and HttpInvokerServiceExporter.
Manubhai Tower , Sayajigunj
MobileNo:9327219987
<?xml version="1.0"B-208
encoding="UTF-8"?>
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
.MobileNo:9328994901
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="calculationBean" class="com.javatpoint.CalculationImpl"></bean>


<bean name="/Calculation.http"
class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="calculationBean"></property>
<property name="serviceInterface" value="com.javatpoint.Calculation"></property>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
5) client-beans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
In this xml file, we
are defining bean for HttpInvokerProxyFactoryBean. You need to define
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
two properties of xsi:schemaLocation="http://www.springframework.org/schema/beans
this class.
serviceUrl
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
serviceInterface<bean id="castorMarshallerBean" class="org.springframework.oxm.castor.CastorMarshaller">
<?xml version="1.0"<property
encoding="UTF-8"?>
name="targetClass" value="com.javatpoint.Employee"></property>
<beans xmlns="http://www.springframework.org/schema/beans"
<property name="mappingLocation" value="mapping.xml"></property>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
</bean>
xsi:schemaLocation="http://www.springframework.org/schema/beans
</beans>
http://www.springframework.org/schema/beans/spring-beans.xsd">
mapping.xml
<bean id="calculationBean"
<?xml version="1.0"?>
class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN"
<property name="serviceUrl"
"http://castor.org/mapping.dtd">
value="http://localhost:8888/httpinvoker/Calculation.http"></property>
<mapping>
<property name="serviceInterface"
value="com.javatpoint.Calculation"></property>
<class name="com.javatpoint.Employee"
auto-complete="true" >
</bean>
<map-to xml="Employee" ns-uri="http://www.javatpoint.com" ns-prefix="dp"/>
</beans>
<field name="id" type="integer">
<bind-xml name="id" node="attribute"></bind-xml>
6) Client.java
</field>
This class gets the instance
of Calculation and calls the method.
<field name="name">
package com.javatpoint;
<bind-xml name="name"></bind-xml>
import org.springframework.context.ApplicationContext;
</field>
import org.springframework.context.support.ClassPathXmlApplicationContext;
<field name="salary">
<bind-xml name="salary" type="float"></bind-xml>
public class Client {</field>
public static void</class>
main(String[] args){
ApplicationContext
context = new ClassPathXmlApplicationContext("client-beans.xml");
</mapping>
Calculation calculation = (Calculation)context.getBean("calculationBean");
System.out.println(calculation.cube(5));
Client.java
}
It gets the instance of Marshaller from the applicationContext.xml file and calls the marshal
}
method.
Output
package com.javatpoint;
Output: 125 import java.io.FileWriter;
How to run thisimport
example
java.io.IOException;
Start and deploy
the project,
here we are assuming that server is running on 8888 port number.
import
javax.xml.transform.stream.StreamResult;
If the port number
is
different,
change the serviceURL in client-beans.xml.
import org.springframework.context.ApplicationContext;
Then, Compileimport
and Run
the Client.java file.
org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
Web-based Client
In the examplepublic
given class
above,
we used console based client. We can also use web based client.
Client{
You need to create
3 additional
Here, we are
using following
files:
public
static voidfiles.
main(String[]
args)throws
IOException{
ClientInvoker.java
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml
index.jsp
process.jsp
130
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
ClientInvoker.java 2nd Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
It defines only one method getCube() that returns cube of the given number
.MobileNo:9328994901
package com.javatpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ClientInvoker {


public static int getCube(int number){
ApplicationContext context = new ClassPathXmlApplicationContext("clientbeans.xml");
Calculation calculation = (Calculation)context.getBean("calculationBean");
return calculation.cube(number);
");
}
Marshaller marshaller = (Marshaller)context.getBean("castorMarshallerBean");
}
index.jsp
Employee employee=new Employee();
It creates a form to get number.
employee.setId(101);
<form action="process.jsp">
employee.setName("Sonoo Jaiswal");
Enter Number:<input type="text" name="number"/>
employee.setSalary(100000);
<input type="submit" value="cube" />
</form>
marshaller.marshal(employee, new StreamResult(new FileWriter("employee.xml")));
process.jsp
It creates a form to get number.
System.out.println("XML Created Sucessfully");
<jsp:include page="index.jsp"></jsp:include>
}
<hr/>
}
<%@page import="com.javatpoint.ClientInvoker"%>
Output of the example
<%
employee.xml
int number=Integer.parseInt(request.getParameter("number"));
<?xml version="1.0" encoding="UTF-8"?>
out.print("cube of "+number+" is: "+ClientInvoker.getCube(number));
<dp:Employee xmlns:dp="http://www.javatpoint.com" id="101">
%>
<dp:name>Sonoo Jaiswal</dp:name>
Output:
<dp:salary>100000.0</dp:salary>
</dp:Employee>
System.out.println("XML Created Sucessfully");
}
}
Output of the example
employee.xml
<com.javatpoint.Employee>
<id>101</id>
<name>Sonoo Jaiswal</name>
<salary>100000.0</salary>
</com.javatpoint.Employee>

131
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
Spring Remoting by Burlap Example
Both, Hessian and Burlap are provided by Coucho. Burlap is the xml-based alternative of

By the help of BurlapServiceExporter and BurlapProxyFactoryBean classes, we can


implement the remoting service provided by burlap.
Example of Burlap is same as Hessian, you need to change Hessian to Burlap only.
Example of Remoting by Burlap
You need to create following files for creating a simple burlap application:
Calculation.java
CalculationImpl.java
web.xml
burlap-servlet.xml
client-beans.xml
Client.java
1) Calculation.java
It is the simple interface containing one method cube.
package com.javatpoint;
public interface Calculation {
int cube(int number);
}
2) CalculationImpl.java
This class provides the implementation of Calculation interface.
package com.javatpoint;
public class CalculationImpl implements Calculation{
public int cube(int number) {
return number*number*number;
}
}
3) web.xml
In this xml file, we are defining DispatcherServlet as the front controller. If any request is
followed by .http extension, it will be forwarded to DispatcherServlet.
11-Spring
Java Mail
<?xml version="1.0"
encoding="UTF-8"?>
<web-app version="2.5"
Spring Java Mail Tutorial
xmlns="http://java.sun.com/xml/ns/javaee"
Spring framework provides many useful interfaces and classes for sending and receiving mails.
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
The org.springframework.mail package is the root package that provides mail support in
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
Spring framework.
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet> Spring Java Mail API:
The interfaces and classes for java mail support in spring framework are as follows:
<servlet-name>burlap</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>burlap</servlet-name>
<url-pattern>*.http</url-pattern>
</servlet-mapping>
</web-app>
4) burlap-servlet.xml
It must be created inside the WEB-INF folder. Its name must be servletname-servlet.xml. It
defines bean for CalculationImpl and BurlapServiceExporter.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
132
xsi:schemaLocation="http://www.springframework.org/schema/beans
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
http://www.springframework.org/schema/beans/spring-beans.xsd">
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
<bean id="calculationBean" class="com.javatpoint.CalculationImpl"></bean>
<bean name="/Calculation.http"
class="org.springframework.remoting.caucho.BurlapServiceExporter">

<property name="serviceInterface" value="com.javatpoint.Calculation"></property>


</bean>
</beans>
5) client-beans.xml
In this xml file, we are defining bean for BurlapProxyFactoryBean. You need to define two
properties of this class.
serviceUrl
serviceInterface
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="calculationBean"
class="org.springframework.remoting.caucho.BurlapProxyFactoryBean">
<property name="serviceUrl"
value="http://localhost:8888/burlap/Calculation.http"></property>
<property name="serviceInterface" value="com.javatpoint.Calculation"></property>
</bean>
MailSender interface: It is the root interface. It provides basic functionality for sending simple
</beans>
mails.
In this example,
our project nameinterface:
is burlap, Iti.e.
as the context
root in the serviceURL.
JavaMailSender
is used
the subinterface
of MailSender.
It supports MIME messages. It
6) Client.java is mostly used with MimeMessageHelper class for the creation of JavaMail MimeMessage,
This class gets with
the instance
of Calculation
and calls
the cube
method. MimeMessagePreparator mechanism
attachment
etc. The spring
framework
recommends
package com.javatpoint;
for using this interface.
import org.springframework.context.ApplicationContext;
JavaMailSenderImpl class: It provides the implementation of JavaMailSender interface. It
import org.springframework.context.support.ClassPathXmlApplicationContext;
supports JavaMail MimeMessages and Spring SimpleMailMessages.
SimpleMailMessage class: It is used to create a simple mail message including from, to, cc,
public class Client
{ and text messages.
subject
public static void
main(String[] args){ interface: It is the callback interface for the preparation of JavaMail
MimeMessagePreparator
ApplicationContext
= new ClassPathXmlApplicationContext("client-beans.xml");
MIME context
messages.
Calculation calculation
= (Calculation)context.getBean("calculationBean");
MimeMessageHelper
class: It is the helper class for creating a MIME message. It offers
System.out.println(calculation.cube(3));
support for inline elements such as images, typical mail attachments and HTML text content.
}
}
Example of Sending mail in Spring by Gmail Server:
How to run thisInexample
this example, we are using two spring mail classes:
Start and deploy
the project, here for
we creating
are assuming
that server is running on 8888 port
SimpleMailMessage
message.
number. If the SimpleMailSenderImpl
port number is different, change
the serviceURL
for sending
message. in client-beans.xml.
Then, CompileYou
and need
Run the
Client.java
file.
to create following files for sending email through Spring framework.
MailMail.java
applicationContext.xml
Test.java
You need to load mail.jar and activation.jar files to run this example.
download mail.jar and activation.jar or go to the Oracle site to download the latest version.
1) MailMail.java
It is the simple class that defines mailSender property. An object of MailSender will be provided
to this property at runtime.
In the sendMail() method, we are creating the instance of SimpleMailMessage and storing the
information into this object such as from, to, subject and message.
133
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

The send() method of MailSender interface is used here to send the simple mail.
package com.javatpoint;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
public class MailMail{
private MailSender mailSender;

10-Spring

public void setMailSender(MailSender mailSender) {


this.mailSender = mailSender;
}
public void sendMail(String from, String to, String subject, String msg) {
OXM
//creating message
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(msg);
//sending message
mailSender.send(message);
}
}
2) applicationContext.xml
In this xml file, we are creating a bean for JavaMailSenderImpl class. We need to define values
of following properties:
host
username
password
javaMailProperties
We are also creating the bean for MailMail class with mailSender property. Now, the instance of
JavaMailSenderImpl class will be set in the mailSender property of MailMail class.
<?xml version="1.0" encoding="UTF-8"?>

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="username" value="yourgmailid@gmail.com" />
<property name="password" value="yourgmailpassword" />
<property name="javaMailProperties">
134
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.socketFactory.port">465</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.smtp.port">465</prop>
</props>
</property>
</bean>
<bean id="mailMail" class="com.javatpoint.MailMail">
<property name="mailSender" ref="mailSender" />
</bean>
</beans>
3) Test.java
This class gets the bean of mailMail from the applicationContext.xml file and calls the sendMail
method of MailMail class.
package com.javatpoint;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory b=new XmlBeanFactory(r);
MailMail m=(MailMail)b.getBean("mailMail");
String sender="sendergmailid@gmail.com";//write here sender gmail id
String receiver="receiveremailid@gmail.com";//write here receiver id
m.sendMail(sender,receiver,"hi","welcome");
System.out.println("success");
}
}

How to run this example


Load the spring jar files for core and java mail
Load the mail.jar and activation.jar
Change the username and password property in the applicationContext.xml file, specifying your
gmail id and password.
Change the sender gmail id and receivermail id in the Test.java file.
Compile and Run the Test class
Example of Sending mail in Spring by Server provided by host provider
If you have your own site, you can use your mail server. The MailMail.java and Test class will
be same. You need to change only Sender email id in the Test.java file. Some changes are
required in the applicationContext.xml file.
In the applicationContext.xml file, we are using:
135
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

mail.unitedsquaad.com for the host name. Change it.


a@unitedsquaad.com for the username. Change it.
xxxxx for the password. Change it.
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.unitedsquaad.com" />
<property name="username" value="a@unitedsquaad.com" />
<property name="password" value="xxxxx" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="mailMail" class="MailMail">
<property name="mailSender" ref="mailSender" />
</bean>
</beans>
Sending mails to multiple receivers
You can send mails to multiple receivers by the help of SimpleMailMessage class. The
setTo(String[] receivers) method of SimpleMailMessage class is used to send message to
multiple receivers. Let's see the simple code.
....
public void sendMail(String from, String[] to, String subject, String msg) {
//creating message
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);//passing array of recipients
message.setSubject(subject);
message.setText(msg);
//sending message
mailSender.send(message);
}
...
Spring MimeMessagePreparator Example
We can send the mime message by the help of MimeMessagePreparator interface. It has one
136
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

method prepare(MimeMessage message).


Let's see the simple code to send mime message.
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
public class MailMail{
private JavaMailSender mailSender;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(final String from, final String to,final String subject,final String msg)
{
MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
mimeMessage.setFrom(new InternetAddress(from));
mimeMessage.setSubject(subject);
mimeMessage.setText(msg);
}
};
mailSender.send(messagePreparator);
}
}
The applicationContext.xml and Test.java files are same as given above.
Sending Attachment by Spring MimeMessageHelper Example:
We can send the mime message with attachment in spring by the help of MimeMessageHelper
class. It is recommended to use than MimeMessagePreparator.
Let's see the simple code to send mime message with attachment(image).
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailMail{
private JavaMailSender mailSender;
public void setMailSender(JavaMailSender mailSender) {
137
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

this.mailSender = mailSender;
}
public void sendMail(final String from, final String to,final String subject,final String msg)
{
try{
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(msg);
// attach the file
FileSystemResource file = new FileSystemResource(new File("c:/rr.jpg"));
helper.addAttachment("mybrothermage.jpg", file);//image will be sent by this name
mailSender.send(message);
}catch(MessagingException e){e.printStackTrace();}
}
}
The applicationContext.xml and Test.java files are same as given above.

12-Spring Web
Spring and Struts 2 Integration
Spring framework provides an easy way to manage the dependency. It can be easily integrated
with struts 2 framework.
138
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

The ContextLoaderListener class is used to communicate spring application with struts 2. It


must be specified in the web.xml file.
You need to follow following steps:
Create struts2 application and add spring jar files.
In web.xml file, define ContextLoaderListener class.
In struts.xml file, define bean name for the action class.
In applicationContext.xml file, create the bean. Its class name should be action class name e.g.
com.javatpoint.Login and id should match with the action class of struts.xml file (e.g. login).
In the action class, define extra property e.g. message.
Example of Spring and Struts 2 Integration:
You need to create following files for simple spring and struts 2 application:
index.jsp
web.xml
struts.xml
applicationContext.xml
Login.java
welcome.jsp
error.jsp
1) index.jsp
This page gets the name from the user.
<%@ taglib uri="/struts-tags" prefix="s"%>
<s:form action="login">
<s:textfield name="userName" label="UserName"></s:textfield>
<s:submit></s:submit>
</s:form>
2) web.xml
It defines controller class for struts 2 and ContextLoaderListener listener class to make
connection between struts2 and spring application.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
139
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3) struts.xml
It defines the package with action and result. Here, the action class name is login which will be
searched in the applicationContext.xml file.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//E
N"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="abc" extends="struts-default">
<action name="login" class="login">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>
4) applicationContext.xml
It defines a bean with id login. This beans corresponds to the mypack.Login class. It will be
considered as the action class here.
It should be located inside the WEB-INF directory.
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="login" class="mypack.Login">
<property name="message" value="Welcome Spring"></property> </bean> </beans>
5) Login.java
It defines two property userName and message with execute method where success is returned.
package mypack;
public class Login {
private String userName,message;
public String getMessage() {
return message;
}
140
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

public void setMessage(String message) {


this.message = message;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String execute(){
return "success";
}
}
6) welcome.jsp
It prints values of userName and message properties.
<%@ taglib uri="/struts-tags" prefix="s"%>
Welcome, <s:property value="userName"/><br/>
${message}
7) error.jsp
It is the error page. But it is not required in this example because we are not defining any logic in
the execute method of action class.
Sorry!
Output:

Login Example with Spring and Struts 2 Integration:


In the previous example, we have simply integrated the spring application with struts 2. Now
let's develop a login application with struts 2 and spring frameworks.
141
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

It is the simple example of login application without database and session management. If you
need to apply the database interactivity and session management with this example, visit this
link Login and Logout example in struts 2.
Example of Login application Spring and Struts2 Integration
You need to create following files for simple login application using spring and struts 2
application:
index.jsp
web.xml
struts.xml
applicationContext.xml
Login.java
login_success.jsp
login_error.jsp
1) index.jsp
This page gets the name and password from the user.
<%@ taglib uri="/struts-tags" prefix="s"%>
<s:form action="login">
<s:textfield name="name" label="Username"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:submit value="login"></s:submit>
</s:form>
2) web.xml
It defines controller class for struts 2 and ContextLoaderListener listener class to make
connection between struts2 and spring application.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
142
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

</filter-mapping>
</web-app>
3) struts.xml
It defines the package with action and result. Here, the action class name is login which will be
searched in the applicationContext.xml file.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//E
N"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="abc" extends="struts-default">
<action name="login" class="login">
<result name="success">login_success.jsp</result>
<result name="error">login_error.jsp</result>
</action>
</package>
</struts>
4) applicationContext.xml
It defines a bean with id login. This beans corresponds to the com.javatpoint.Login class. It will
be considered as the action class here.
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="login" class="com.javatpoint.Login">
<property name="successmessage" value="You are successfully logged in!"></property>
<property name="errormessage" value="Sorry, username or password error!"></property>
</bean>
</beans>
5) Login.java
It defines four properties name, password, successmessage and errormessage; with execute
method where success is returned if password is javatpoint.
package com.javatpoint;
public class Login {
private String name,password,successmessage,errormessage;
//setters and getters
public String execute(){
if(password.equals("javatpoint")){
return "success";
}
143
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

else{
return "error";
}
}
}
6) login_success.jsp
It prints values of userName and message properties.
<%@ taglib uri="/struts-tags" prefix="s"%>
${successmessage}
<br/>
Welcome, <s:property value="name"/><br/>
7) login_error.jsp
It is the error page. But it is not required in this example because we are not defining any logic in
the execute method of action class.
${errormessage}
<jsp:include page="index.jsp"></jsp:include>

Spring Interview Question

144
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Spring interview questions and answers are frequently asked because it is now widely used
framework to develop enterprise application in java. There are given a list of top 40 frequently
asked spring interview questions.
1) What is Spring?
It is a lightweight, loosely coupled and integrated framework for developing enterprise
applications in java.
2) What are the advantages of spring framework?
Predefined Templates
Loose Coupling
Easy to test
Lightweight
Fast Development
Powerful Abstraction
Declarative support
3) What are the modules of spring framework?
Test
Spring Core Container
AOP, Aspects and Instrumentation
Data Access/Integration
Web
4) What is IOC and DI?
IOC (Inversion of Control) and DI (Dependency Injection) is a design pattern to provide loose
coupling. It removes the dependency from the program.
Let's write a code without following IOC and DI.
public class Employee{
Address address;
Employee(){
address=new Address();//creating instance
}
}
Now, there is dependency between Employee and Address because Employee is forced to use
the same address instance.
Let's write the IOC or DI code.
public class Employee{
Address address;
Employee(Address address){
this.address=address;//not creating instance
}
}
Now, there is no dependency between Employee and Address because Employee is not forced to
use the same address instance. It can use any address instance.
5) What is the role of IOC container in spring?
IOC container is responsible to:
create the instance
configure the instance, and
assemble the dependencies
6) What are the types of IOC container in spring?
There are two types of IOC containers in spring framework.
BeanFactory
145
ApplicationContext
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
7) What is nd
the difference between BeanFactory and ApplicationContext?
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
BeanFactory is the basic container whereas ApplicationContext is the advanced container.
ApplicationContext extends the.MobileNo:9328994901
BeanFactory interface. ApplicationContext provides more
facilities than BeanFactory such as integration with spring AOP, message resource handling for
i18n etc.

5-Struts 2 Tutorial

146
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

147
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

The struts 2 framework is used to develop MVC-based web application.


The struts framework was initially created by Craig McClanahan and donated to Apache
Foundation in May, 2000 and Struts 1.0 was released in June 2001.
The current stable release of Struts is Struts 2.3.16.1 in March 2, 2014.
This struts 2 tutorial covers all the topics of Struts 2 Framework with simplified examples for
beginners and experienced persons.
Struts 2 Framework
The Struts 2 framework is used to develop MVC (Model View Controller) based web
applications. Struts 2 is the combination of webwork framework of opensymphony and struts
1.
struts2 = webwork + struts1
The Struts 2 provides supports to POJO based actions, Validation Support, AJAX Support,
Integration support to various frameworks such as Hibernate, Spring, Tiles etc, support to
various result types such as Freemarker, Velocity, JSP etc.

Struts 2 Features Tutorial


Struts 2 Features Tutorial
Struts 2 provides many features that were not in struts 1. The important features of struts 2
framework are as follows:
Configurable MVC components
POJO based actions
AJAX support
Integration support
Various Result Types
Various Tag support
Theme and Template support
1) Configurable MVC components
In struts 2 framework, we provide all the components (view components and action) information
in struts.xml file. If we need to change any information, we can simply change it in the xml file.
2) POJO based actions
In struts 2, action class is POJO (Plain Old Java Object) i.e. a simple java class. Here, you are
not forced to implement any interface or inherit any class.
3) AJAX support
Struts 2 provides support to ajax technology. It is used to make asynchronous request i.e. it
doesn't block the user. It sends only required field data to the server side not all. So it makes the
performance fast.
4) Integration Support
We can simply integrate the struts 2 application with hibernate, spring, tiles etc. frameworks.
5) Various Result Types
We can use JSP, freemarker, velocity etc. technologies as the result in struts 2.
6) Various Tag support
Struts 2 provides various types of tags such as UI tags, Data tags,148
control tags etc to ease the
B-208 of
Manubhai
Tower , Sayajigunj
MobileNo:9327219987
development
struts 2 application.
7) Theme2nd
andFloor,
Template
Ronak
support
Plaza, Tulsidham Char Rasta, Manjalpur
Struts 2 provides three types of.MobileNo:9328994901
theme support: xhtml, simple and css_xhtml. The xhtml is
default theme of struts 2. Themes and templates can be used for common look and feel.

2-Core Component of Struts

149
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Struts 2 Interceptors Tutorial


Interceptor is an object that is invoked at the preprocessing and postprocessing of a request. In
Struts 2, interceptor is used to perform operations such as validation, exception handling,
internationalization, displaying intermediate result etc.
Advantage of interceptors:
Pluggable If we need to remove any concern such as validation, exception handling, logging etc.
from the application, we don't need to redeploy the application. We only need to remove the
entry from the struts.xml file.
Struts 2 default interceptors:
There are many interceptors provided by struts 2 framework. We have option to create our own
interceptors. The struts 2 default interceptors are as follows:
1) alias It converts similar parameters that have different names between requests.
2) autowiring
3) chain If it is used with chain result type, it makes the properties of previous action available
in the current action.
4) checkbox It is used to handle the check boxes in the form. By this, we can detect the
unchecked checkboxes.
5) cookie It adds a cookie to the current action.
6) conversionError It adds conversion errors to the action's field errors.
7) createSession It creates and HttpSession object if it doesn't exists.
8) clearSession It unbinds the HttpSession object.
9) debugging It provides support of debugging.
10) externalRef
11) execAndWait It sends an intermediate waiting page for the result.
12) exception It maps exception to a result.
13) fileUpload It provides support to file upload in struts 2.
14) i18n It provides support to internationalization and localization.
15) jsonValidation It provides support to asynchronous validation.
16) logger It outputs the action name.
17) store It stores and retrieves action messages, action errors or field errors for action that
implements ValidationAware interface.
18) modelDriven It makes other model object as the default object of valuestack.
19) scopedModelDriven It is similar to ModelDriven but works for action that implements
ScopedModelDriven.
20) params It populates the action properties with the request parameters.

Struts 2 ValueStack Tutorial


A valueStack is simply a stack that contains application specific objects such as action objects and other model
object.
At the execution time, action is placed on the top of the stack.
We can put objects in the valuestack, query it and delete it.
ValueStack Interface:
The struts 2 framework provides an interface to deal with valuestack. It provides many useful methods.
Methods of ValueStack interface
There are many methods in ValueStack interface. The commonly used methods are as follows:
public String findString(String expr) finds the string by evaluating the given expression.
public Object findValue(String expr) finds the value by evaluating the specified expression.
public Object findValue(String expr, Class c) finds the value by evaluating the specified expression.
public Object peek() It returns the object located on the top of the stack.
150
publicB-208
Object Manubhai
pop() It returnsTower
the object
located
on
the
top
of
the
stack
and removes it.
, Sayajigunj
MobileNo:9327219987
public void
o) It puts
the object
on the top ofChar
the stack.
2ndpush(Object
Floor, Ronak
Plaza,
Tulsidham
Rasta, Manjalpur
public void set(String key, Object
value)
It
sets
the
object
on
.MobileNo:9328994901 the stack with the given key. It can be get by
calling the findValue(key) method.
public int size() It returns the number of objects from the stack.

Struts 2 ActionContext Tutorial


The ActionContext is a container of objects in which action is executed. The values stored in the
ActionContext are unique per thread (i.e. ThreadLocal). So we don't need to make our action
thread safe.
We can get the reference of ActionContext by calling the getContext() method of ActionContext
The ActionInvocation represents the execution state of an action. It holds the action and
interceptors objects.
ActionInvocation Interface
The struts framework provides ActionInvocation interface to deal with ActionInvocation. It
provides many methods, some of them can be used to get the instance of ValueStack, ActionProxy,
ActionContext, Result etc.
Methods of ActionInvocation Interface The commonly used methods of ActionInvocation interface
are as follows:
class. It is a static factory method. For example:
ActionContext context = ActionContext.getContext();
No Method
.

Description

1)

public
ActionContext returns the ActionContext object associated
getInvocationContext()
with the ActionInvocation.

2)

public ActionProxy getProxy()

returns the ActionProxy instance holding this


ActionInvocation.

3)

public ValueStack getStack()

returns the instance of ValueStack.

4)

public Action getAction()

returns the instance of Action associated with


this ActionInvocation.

5)

public void invoke()

invokes the next resource in processing this


ActionInvocation.

Struts 2 OGNL Tutorial

6) Object
public Result
returns
the instance
of Result.language. It simplifies the
The
GraphgetResult()
Navigation Language
(OGNL)
is an expression
accessibility of data stored in the ActionContext.
The struts framework sets the ValueStack as the root object of OGNL. Notice that action object
is pushed into the ValueStack. We can direct access the action property.
<s:property value="username"/>
Here, username is the property key.
The struts framework places other objects in ActionContext also e.g. map representing the
request, session, application scopes.
To get these values i.e. not the action property, we need to use # notation. For example to get the
data from session scope, we need to use #session as given in the following example:
<s:property name="#session.username"/>
(or)
<s:property name="#session['username']"/>
151
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

3-Struts Architecture

152
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Struts 2 Architecture and Flow


The architecture and flow of struts 2 application, is combined with many components such as
Controller, ActionProxy, ActionMapper, Configuration Manager, ActionInvocation, Inerceptor,
Action, Result etc.
Here, we are going to understand the struts flow by 2 ways:
struts 2 basic flow
struts 2 standard architecture and flow provided by apache struts
Struts 2 basic flow
Let's try to understand the basic flow of struts 2 application by this simple figure:

User sends a request for the action


Controller invokes the ActionInvocation
ActionInvocation invokes each interceptors and action
A result is generated
The result is sent back to the ActionInvocation
A HttpServletResponse is generated
Response is sent to the user

Struts 2 standard flow (Struts 2 architecture)


Let's try to understand the standard architecture of struts 2 application by this simple figure:

User sends a request for the action


Container maps the request in the web.xml file and gets the class name of controller.
Container invokes the controller (StrutsPrepareAndExecuteFilter or FilterDispatcher). Since
struts2.1, it is StrutsPrepareAndExecuteFilter. Before 2.1 it was FilterDispatcher.
Controller gets the information for the action from the ActionMapper
Controller invokes the ActionProxy
ActionProxy gets the information of action and interceptor stack from the configuration manager
which gets the information from the struts.xml file.
ActionProxy forwards the request to the ActionInvocation
153
ActionInvocation invokes each interceptors and action
B-208
Manubhai Tower , Sayajigunj
MobileNo:9327219987
A result
is generated
nd
Floor,
Plaza, Tulsidham Char Rasta, Manjalpur
The result2is sent
backRonak
to the ActionInvocation
A HttpServletResponse is generated
.MobileNo:9328994901
Response is sent to the user

4-Struts2 Action

154
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Struts 2 Action
In struts 2, action class is POJO (Plain Old Java Object).
POJO means you are not forced to implement any interface or extend any class.
Generally, execute method should be specified that represents the business logic. The simple
action class may look like:
Welcome.java
package com.javatpoint;
public class Welcome {
public String execute(){
return "success";
}
}
Action Interface
A convenient approach is to implement the com.opensymphony.xwork2.Action interface that
defines 5 constants and one execute method.
5 Constants of Action Interface
Action interface provides 5 constants that can be returned form the action class. They are:
SUCCESS indicates that action execution is successful and a success result should be shown to
the user.
ERROR indicates that action execution is failed and a error result should be shown to the user.
LOGIN indicates that user is not logged-in and a login result should be shown to the user.
INPUT indicates that validation is failed and a input result should be shown to the user again.
NONE indicates that action execution is successful but no result should be shown to the user.
Let's see what values are assigned to these constants:
public static final String SUCCESS = "success";
public static final String ERROR = "error";
public static final String LOGIN = "login";
public static final String INPUT = "input";
public static final String NONE = "none";
Method of Action Interface:
Action interface contains only one method execute that should be implemented overridden by
the action class even if you are not forced.
public String execute();
Example of Struts Action that implements Action interface:
If we implement the Action interface, we can directly use the constants instead of values.
Welcome.java
package com.javatpoint;
import com.opensymphony.xwork2.Action;
public class Welcome implements Action{
public String execute(){
return SUCCESS;
}
}
ActionSupport class
It is a convenient class that implements many interfaces such as Action, Validateable,
ValidationAware, TextProvider, LocaleProvider and Serializable . So it is mostly used instead of
Action.
Example of Struts Action that extends ActionSupport class
Let's see the example of Action class that extends the ActionSupport155
class.
Welcome.java
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
package 2
com.javatpoint;
nd
Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
import com.opensymphony.xwork2.ActionSupport;
.MobileNo:9328994901
public class Welcome extends ActionSupport{
public String execute(){
return SUCCESS;

5-Structs2 Configration

156
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Struts 2 Configuration File


The struts application contains two main configuration files struts.xml file and
struts.properties file.
The struts.properties file is used to override the default values of default.xml file provided by
struts framework. So it is not mandatory. Mostly, you will not use struts.properties file. We will
learn about it later.
Here, we are going to learn all about struts.xml file. First of all let us see the simple example of
struts.xml file
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="product" class="com.javatpoint.Product">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>
1) package element
We can easily divide our struts application into sub modules. The package element specifies a
module. You can have one or more packages in the struts.xml file.
Attributes of package element
name name is must for defining any package.
namespace It is an optional attribute of package. If namespace is not present, / is assumed as the
default namespace. In such case, to invoke the action class, you need this URI:
/actionName.action
If you specify any namespace, you need this URI:
/namespacename/actionName.action
extends The package element mostly extends the struts-default package where interceptors and
result types are defined. If you extend struts-default, all the actions of this package can use the
interceptors and result-types defined in the struts-default.xml file.
2) action element
The action is the subelement of package and represents an action.
Attributes of action element
name name is must for defining any action.
class class is the optional attribute of action. If you omit the class attribute, ActionSupport will
be considered as the default action. A simple action may be as:
<action name="product">
method It is an optional attribute. If you don't specify method attribute, execute method will be
considered as the method of action class. So this code:
<action name="product" class="com.javatpoint.Product">
will be same as:
<action name="product" class="com.javatpoint.Product" method="execute">
If you want to invoke a particular method of the action, you need to use method attribute.
3) result element
It is the sub element of action that specifies where to forward the request for this action.
Attributes of result element
157
nameB-208
is the optional
attribute.
If
you
omit
the
name
attribute,
success
is assumed as the default
Manubhai Tower , Sayajigunj
MobileNo:9327219987
result name.
2nd Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
type is the optional attribute. If you
omit the type attribute, dispatcher is assumed as the default
.MobileNo:9328994901
result type.
Other elements
There are many other elements also such as global-exception-mappings, global-results,

6-Interceptor

158
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Struts 2 Validation Tutorial


To
avoid 2the
wrong values,
we needExample
to performTutorial
validation on forms where user submits some
Struts
Custom
Interceptor

values.
For2,example,
if userthe
writes
his/her
email idbyasimplementing
abc, we need the
to give
error message
to in
thea
In struts
we can create
custom
interceptor
Interceptor
interface
user
that
the
given
email
id
is
not
correct.
So
that
we
can
have
only
valuable
informations.
class and overriding its three life cycle method.
There
are threethe
ways
to perform
validation
in struts 2.
For creating
custom
interceptor,
Interceptor
interface must be implemented. It has three
1)methods:
By Custom Validation Here, we must implement the Validateable interface (or extend
ActionSupport
class)
and
provideonly
the once
implementation
validatethe
method.
public void init()
It is
invoked
and used toof
initialize
interceptor.
2)public
By Input
Validation
(built-in
validators)
Struts
2
provides
a
lot
of predefined
that
can the
be
void intercept(ActionInvocation ai) It is invoked at each request,
it is used to
define
used
in struts
2 application
to itperform
request
processing
logic. If
returnsvalidation.
string, result page will be invoked, if it returns invoke()
Struts
2
provides
following
bundled
validators.
method of ActionInvocation interface, next interceptor or action will be invoked.
requiredstring
validator It is invoked only once and used to destroy the interceptor.
public void destroy()
stringlength
Interceptor validator
can change the flow of the application by returning the string.
email validator
date
validator
Example
to create custom interceptor in struts 2
int
validator
In this example, we are going to create custom interceptor that converts request processing data
double
validatorletter.
into uppercase
url
validator
You need to follow 2 steps to create custom interceptor
regex
validator
Create
an interceptor (must implement Interceptor interface)
3)Define
By Ajax
(built-in validators
with ajax)
the Validation
entry of interceptor
in the struts.xml
file If we don't want to refresh the page, we
can
use jsonValidation
interceptor
to perform validation
with
ajax.
1) Create
an interceptor
(must implement
Interceptor
interface)
By this interceptor, we are converting the name property of action class into uppercase letter.
Struts
The getStack()
2 Custommethod
Validation
of ActionInvocation
- Workflow Interceptor
returns the reference of ValueStack.
We
Wecan
are getting
define our
the value
own validation
set in the name
logicproperty
(custombyvalidation)
findStringinmethod
struts 2ofby
ValueStack.
implementing the
Validateable
The set method
interface
of ValueStack
in the action
setsclass.
the name property by the specified value. In such case, we
The
are converting
workflow interceptor
the value of name
is used
property
to get information
into uppercase
about
letterthe
and
error
storing
messages
it into defined
the valuestack.
in the
action
The invoke
class. method of ActionInvocation returns the information of next resource.
Workflow
MyInterceptor.java
Interceptor
The
package
workflow
com; interceptor checks if there is any validation errors or not. It doesn't perform any
validation.
import com.opensymphony.xwork2.ActionInvocation;
Itimport
is applied
com.opensymphony.xwork2.interceptor.Interceptor;
when action class implements the Validateable interface. The input is the default
parameter
import com.opensymphony.xwork2.util.ValueStack;
for this interceptor that determines the result to be invoked for the action or field error.
It is found in the defaultStack so we don't need to define it explicitly.
Parameters
public class
ofMyInterceptor
workflow interceptor
implements Interceptor{
There
public
is only
void
1 parameter
init() {} defined for workflow interceptor.
public String intercept(ActionInvocation
ai) throws Exception {
Parameter
Description
ValueStack
stack=ai.getStack();
inputResultName specifies the result name to be returned if field error or action error is found.
String s=stack.findString("name");
It is set to input bydefault.
stack.set("name",s.toUpperCase());
return ai.invoke();
Validateabale
interface:
}
The Validateable interface must be implemented to perform validation logic in the action class.
public void
{} validate() that must be overridden in the action class to define the
It contains
only destroy()
one method
}
validation
logic. Signature of the validate method is:
2) Define
entry of interceptor in the struts.xml file
public
voidthe
validate();
To define the interceptor, we need to declare an interceptor first. The interceptors element of
package is used to specify interceptors. The interceptor element of interceptors is used to define
the custom interceptor. Here, we are defining the custom interceptor by upper.
The interceptor-ref subelement of action specifies the interceptor that will be applied for this
action. Here, we are specifying the defaultstack interceptors and upper interceptor.
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD159
Struts
Configuration
2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
<struts> 2nd Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
<package name="abc" extends="struts-default">
.MobileNo:9328994901
<interceptors>
<interceptor name="upper" class="com.MyInterceptor"></interceptor>
</interceptors>

<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="upper"></interceptor-ref>
<result>welcome.jsp</result>
</action>
</package>
</struts>
Struts 2 Validation by Bundled Validators
Struts 2 validation framework provides many built-in validators also known as bundled
Other
Required
Resources
validators
for email,
string, int, double, url, date etc
The
other
required
resources
areexplicit logic for email, double, url etc. For providing specific
So, we don't need to provide
index.jsp
validation logic, we can use regex, which we will see later.
Login.java
validation interceptor
welcome.jsp
It performs validation against the specified validation rules and adds the field-level and action1)
Create
to get input (index.jsp)
level
error form
messages.
index.jsp
It works in conjunction with the workflow interceptor to display the error messages.
This
creates adefined
form using
struts
UI tags. It receives name from the user.
Therejsp
is page
no parameter
for this
interceptor.
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:form
action="login">
Advantage
of Bundled validators:
<s:textfield
name="name"
fast development
becauselabel="Name"></s:textfield>
we don't need to specify the common validators such as email date,
<s:submit
value="login"></s:submit>
string length etc.
</s:form>
Bundled validators:
2)
Create
the action
class bundled validators.
Struts
2 provides
following
It
is
the
simple
action
class containing name property with its setter and getter methods.
requiredstring validator
Login.java
stringlength validator
package
com;
email validator
public
class Login {
date validator
private
String name;
int validator
public
getName() {
double String
validator
return
name;
url validator
}regex validator
public void setName(String name) {
this.name
name;
Two
ways to =use
bundled validators:
}There are two ways to use bundled validators:
public
String execute(){
Plain-Validator
(non-field validator) Syntax
return
"success";
Field-Validator Syntax
}In the next page we will see the full example of bundled validators. Let's now understand the
}difference between plain-validator syntax and field-validator syntax.
3) Create view component
This
jsp page displays
the validator)
name inputSyntax:
by the user.
Plain-Validator
(non-field
welcome.jsp
Plain-validator syntax can be used for action level validator. In such case, a single validator can
<%@
taglibtouri="/struts-tags"
prefix="s" %>
be applied
many fields.
Welcome,
<s:property
value="name"/>
But disadvantage of this approach is we can't apply many validators to single field.
Let's see simple example of plain-validator.
Struts 2 params interceptor example
<validators>
The
params
interceptor
also-->
known as parameters interceptor is used to set all parameters on
<!-Plain-Validator
Syntax
the<validator
valuestack.type="requiredstring">
It is found
in the
default stack bydefault. So you don't need to specify it explicitely.
<param
name="fieldName">username</param>
Internal
working
of params interceptor
<param
name="trim">true</param>
It gets
all
parameters
by calling
the getParameters() method of ActionContext and sets it on
<message>username
is required</message>
the</validator>
valuestack by calling the setValue() method of ValueStack.
Parameters
of params interceptor
</validators>
There are 4 parameters defined for params interceptor.
160
Parameter
Description
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak ItPlaza,
Tulsidham
Char
Rasta,
Manjalpur
Ordered
is true bydefault
but can
be used
to top-down
the
.MobileNo:9328994901
property
setter behaviour.
paramNameMaxLengt
h

specifies the maximum length for the parameter. The


default length is 100 characters bydefault. The

excludeParams

specifies the unallowed parameter names. You can


specify multiple names separated with comma.

acceptParamNames

specifies the accepted parameter names.

Example of params interceptor:


Let's see the simple example of params interceptor.
<action name="login" class="com.javatpoint.Login">
<interceptor-ref name="params"/>
<result name="success">login-success.jsp</result>
</action>
Note: If you specify any interceptor for the action explicitely, default interceptors will not be
available for the action class.

Struts 2 defaultStack interceptors


The params interceptor is found in the default stack. You don't need to specify interceptors
found in the default-stack. The defaultStack interceptors are as follows:
<interceptor-stack name="defaultStack">
<interceptor-ref name="exception"/>
<interceptor-ref name="alias"/>
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="prepare"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name="chain"/>
<interceptor-ref name="debugging"/>
<interceptor-ref name="profiling"/>
<interceptor-ref name="scopedModelDriven"/>
<interceptor-ref name="modelDriven"/>
<interceptor-ref name="fileUpload"/>
<interceptor-ref name="checkbox"/>
<interceptor-ref name="staticParams"/>
<interceptor-ref name="actionMappingParams"/>
<interceptor-ref name="params">
<param name="excludeParams">dojo\..*,^struts\..*</param>
</interceptor-ref>
<interceptor-ref name="conversionError"/>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
</interceptor-stack>

Struts 2 execAndWait interceptor example


The execAndWait interceptor also known as execute and wait interceptor is used to display
the intermediate result.
It is recommended to use for long running action.
It is not found in the default stack bydefault. So you need to specify it explicitely.
161
If you don't specify "wait" result, struts framework displays an intermediate result until your
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
request is completed.
nd
2 Floor,
Ronakresult,
Plaza,
Tulsidham
Char result
Rasta,
Manjalpur
For the custom
intermediate
you need
to define "wait"
in struts.xml
file. In your
page, you can display processing.MobileNo:9328994901
image etc. So, it is better to specify the custom result.
Parameters of execAndWait interceptor
There are 3 parameters defined for execAndWait interceptor.

Parameter
delay

Description
specifies the initial delay time. Bydefault, no
initial delay is set.

delaySleepInterval used only with delay. It specifies the time interval


Field-Validator Syntax in milliseconds to check that background process
The field-validator syntax is
cancompleted.
be used for It
field
such case, multiple validator
is level
set validator.
to 100 In
milliseconds
can be applied to one field.bydefault.
For example, we can apply required and email validators on email
field. Moreover, each field can display different messages.
threadPriority
specifiesisthe
of the
thread. validator
The default
is field like plainBut disadvantage
of this approach
wepriority
can't apply
common
to many
Thread.NORM_PRIORITY.
validator.
Let's
see simple
example ofinterceptor
field-validator.
Example
of execAndWait
without wait result:
<validators>
Let's see the simple example of execAndWait interceptor without wait result. In such case,
<!-- Field-Validator
Syntax
struts
framework provides
an-->
intermediate result.
<field
name="username">
<action name="login" class="com.javatpoint.Login">
<field-validator
type="requiredstring">
<interceptor-ref
name="params"/>
<param name="trim">true</param>
<interceptor-ref
name="execAndWait"/>
<message>username
is required</message>
<result
name="success">login-success.jsp</result>
</field-validator>
</action>
</field>
</validators>
Example of execAndWait interceptor with wait result:
Which
validator
syntaxexample
is better?of execAndWait interceptor with wait result. In such case, your
Let's see
the simple
Itintermediate
is recommended
field validator by apache struts because it provides more flexibility.
page to
is use
invoked.
<action name="login" class="com.javatpoint.Login">
Struts
2 requiredstring
validation example
<interceptor-ref
name="params"/>
The<interceptor-ref
requiredstring validator
specifies that string can't be null or blank.
name="execAndWait"/>
It trims
the
string
bydefault
then
checks if its length is greater that 0.
<result name="success">login-success.jsp</result>
Parameters
requiredstring validator
<result of
name="wait">myintermediatepage.jsp</result>
There
are
two
</action> parameters defined for requiredstring validator.
Parameter Description
fieldName
specifies the field name that is to be validated. It is required in Plain-Validator only.
myintermediatepage.jsp
Trim
Let's write trims
the code
the field
for intermediate
values. It is bydefault
result. Thetrue
s:url
means
tag will
it is forward
enabled bydefault.
the request to specified
url.
Example
of requiredstring validator
<%@ taglib uri="/struts-tags" prefix="s" %>
<validators>
<html>
<!-- Plain-Validator Syntax -->
<head>
<validator type="requiredstring">
<title>wait</title>
<param name="fieldName">username</param>
<meta
http-equiv="refresh"
content="0.5;url='<s:url includeParams="all" />'">
<param
name="trim">true</param>
</head>
<message>username is required</message>
<body>
</validator>
<p>your request is processing...</p>
</validators>
<img src="processing.gif"/>
<validators>
</body>
<!-Plain-Validator Syntax -->
</html> type="requiredstring">
<validator
It will be
refreshed at 0.5 seconds.
<param
name="fieldName">username</param>
Output:name="trim">true</param>
<param
<message>username is required</message>
</validator>
162
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

</validators>
<validators>
<!-- Field-Validator Syntax -->
<field name="username">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>username is required</message>
</field-validator>
</field>
</validators>
<validators>
<!-- Field-Validator Syntax -->
<field name="username">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>username is required</message>
</field-validator>
</field>
</validators>
Full example of requiredstring validator
1) Create index.jsp for input
This jsp page creates a form using struts UI tags. It receives name, password and email id from
the user.
index.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<STYLE type="text/css">
.errorMessage{color:red;}
</STYLE>
</head>
<body>
<s:form action="register">
<s:textfield name="username" label="Username"></s:textfield>
<s:password name="userpass" label="Password"></s:password>
<s:submit value="register"></s:submit>
</s:form>
</body>
</html>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<STYLE type="text/css">
.errorMessage{color:red;}
</STYLE>
163
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

</head>
<body>
<s:form action="register">
<s:textfield name="username" label="Username"></s:textfield>
<s:password name="userpass" label="Password"></s:password>
<s:submit value="register"></s:submit>
</s:form>
</body>
</html>
2) Create the action class
This action class inherits the ActionSupport class and overrides the execute method.
RegisterAction.java
package com.javatpoint;
import com.opensymphony.xwork2.ActionSupport;
public class Register extends ActionSupport{
private String username,userpass;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpass() {
return userpass;
}
public void setUserpass(String userpass) {
this.userpass = userpass;
}
public String execute(){
return "success";
}
}
package com.javatpoint;
import com.opensymphony.xwork2.ActionSupport;
public class Register extends ActionSupport{
private String username,userpass;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
164
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

public String getUserpass() {


return userpass;
}
public void setUserpass(String userpass) {
this.userpass = userpass;
}
public String execute(){
return "success";
}
}
3) Create the validation file
Here, we are using bundled validators to perform the validation.
Register-validation.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="username">
<field-validator type="requiredstring">
<message>Name can't be blank</message>
</field-validator>
</field>
</validators>
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE validators PUBLIC


"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="username">
<field-validator type="requiredstring">
<message>Name can't be blank</message>
</field-validator>
</field>
</validators>
4) Create struts.xml
This xml file defines an extra result by the name input, and an interceptor jsonValidatorWorkflowStack.
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts
.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
165
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<action name="register" class="com.javatpoint.Register">


<result name="input">index.jsp</result>
<result>welcome.jsp</result>
</action>
</package>
</struts>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//ApacheSoftware Foundation//DTD
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="register" class="com.javatpoint.Register">
<result name="input">index.jsp</result>
<result>welcome.jsp</result>
</action>
</package>
</struts>
5) Create view component
It is the simple jsp file displaying the information of the user.
welcome.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
Welcome,<s:property value="username"/>
<%@ taglib uri="/struts-tags" prefix="s" %>
Welcome,<s:property value="username"/>

Struts

Configuration

166
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

2.1//EN"

Struts 2 Zero Configuration by convention


We can create struts 2 application without the configuration file struts.xml. There are two ways to
create zero configuration file:
By convention
By annotation
The steps to create zero configuration file using convention is as follows:
Create input page (optional)
Create the action class
Create view components
Example to create zero configuration file by convention.
In this example, we are creating 4 pages :
index.jsp
LoginAction.java
login-success.jsp
login-error.jsp
1) Create index.jsp for input (optional)
This jsp page creates a form using struts UI tags. It receives name and password from the user.
index.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:form action="login">
<s:textfield name="name" label="Name"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:submit value="login"></s:submit>
</s:form>
2) Create the action class
The action class name must be suffixed by action following the request name or it must
implement the Action interface (or extend ActionSupport). Suppose that request name is login,
action class name should be LoginAction if you don't want to implement Action interface.
The action class must be located inside the action or actions or struts or struts2 package.
LoginAction.java
package action;
public class LoginAction {
private String name,password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute(){
if(password.equals("struts")){
return "success";
}
else
167
return
"error";
B-208
Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
}
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
}
.MobileNo:9328994901
3) Create view components
The view components must be located inside the WEB-INF/content folder.
The view components must be named with request name - (hyphen) string returned by action

file name must be login-success.jsp and login-error.jsp.


login-success.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
Welcome,<s:property value="name"/>
login-error.jsp
Sorry
username
or password error!
Struts
2 Zero Configuration
by convention
<jsp:include
page="/index.jsp"></jsp:include>
We can create struts 2 application without the configuration file struts.xml. There are two ways
to create zero configuration file:
By convention
By annotation
The steps to create zero configuration file using convention is as follows:
Create input page (optional)
Create the action class
Create view components
Example to create zero configuration file by convention.
In this example, we are creating 4 pages :
index.jsp
LoginAction.java
login-success.jsp
login-error.jsp
1) Create index.jsp for input (optional)
This jsp page creates a form using struts UI tags. It receives name and password from the user.
index.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:form action="login">
<s:textfield name="name" label="Name"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:submit value="login"></s:submit>
</s:form>
2) Create the action class
The action class name must be suffixed by action following the request name or it must
implement the Action interface (or extend ActionSupport). Suppose that request name is login,
action class name should be LoginAction if you don't want to implement Action interface.
The action class must be located inside the action or actions or struts or struts2 package.
LoginAction.java

168
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

private String name,password;


public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute(){
if(password.equals("struts")){
return "success";
}
else
return "error";
}
}
3) Create view components
The view components must be located inside the WEB-INF/content folder.
The view components must be named with request name - (hyphen) string returned by action
class. Suppose that request name is login and string returned by action class is success and error,
file name must be login-success.jsp and login-error.jsp.
login-success.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
Welcome,<s:property value="name"/>
login-error.jsp
Sorry username or password error!
<jsp:include page="/index.jsp"></jsp:include>
package action;
public class LoginAction {

Struts 2 Tiles Framework Integration Tutorial Example


We can customize the layout of the struts 2 application by integrating with tiles framework.
A web page can contain many parts (known as tile) such as header, left pane, right pane, body
part, footer etc. In tiles framework, we manage all the tile by our Layout Manager page.
169
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Advantage of tiles framework:


here are following advantages of tiles framework:
Customization by centralized page We can customize the layout of all the pages by single page (centralized
page) only.
Code reusability A single part e.g. header or footer can be used in many pages. So it saves coding.
Easy to modify If any part (tile) is modified, we don't need to change many pages.
Easy to remove If any part (tile) of the page is removed, we don't need to remove the code from all the pages.
We can remove the tile from our layout manager page.

Steps to create tiles application


The steps are as follows:
Add tiles library in your application
Define Struts2TilesListener in web.xml file
Create the input page (index.jsp)
Create the Action class
Extend the tiles-default package in your package and define all the result type as tiles in struts.xml file
Create the tiles.xml file and define all the tiles definitions
Create the LayoutManager page
Create the View components
1) Add tiles library in your application
If you are using myeclipse IDE, you can add tiles library by right click on the project -> Build Path -> Add
Library -> Add Myeclipse Library -> Select the Struts 2 tiles library -> ok.
If you are using eclipse or Netbeans IDE, you need to add the required tiles library in your project.
2) Define Struts2TilesListener in web.xml file
Provide entry of listener class Struts2TilesListener in the web.xml file.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
170
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>
</web-app>
3) Create the input page (index.jsp)
index.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:form action="login">
<s:textfield name="name" label="Name"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:submit value="login"></s:submit>
</s:form>
4) Create the action class
This action class contains one field name and defines the execute method.
Login.java
package com.javatpoint;
public class Login {
private String name,password;
//getters and setters
public String execute(){
if(password.equals("admin")){
return "success";
}
else{
return "error";
}
}
}
5) Inherit the tiles-default package and define all the result type as tiles in struts.xml
This xml file defines one package with one action and two results.
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
171
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"


"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="abc" extends="tiles-default" >
<action name="login" class="com.javatpoint.Login">
<result name="success" type="tiles">login-success</result>
<result name="error" type="tiles">login-error</result>
</action>
</package>
</struts>
6)Create the tiles.xml file and define all the tiles definitions
The tiles.xml file must be located inside the WEB-INF directory.
tiles.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="login-success" template="/layoutmanager.jsp">
<put-attribute name="title" value="Welcome Page"/>
<put-attribute name="body" value="/login-success.jsp"/>
</definition>
<definition name="login-error" template="/layoutmanager.jsp">
<put-attribute name="title" value="Login Error"/>
<put-attribute name="body" value="/login-error.jsp"/>
</definition>
</tiles-definitions>
7) Create the LayoutManager page
It is the layout manager page. It used getAsString tag of tiles to include the string resource and insertAttribute
tag of tiles to include the page resource.
layoutmanager.jsp
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title><tiles:getAsString name="title" /></title>
</head>
<body>
<%@ include file="header.jsp" %>
<tiles:insertAttribute name="body" />
<%@ include file="footer.jsp" %>
</body>
</html>
8)Create View components
172
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

There are many view components such as header.jsp, footer.jsp, welcome.jsp etc.
header.jsp
<h2 style="background-color:pink;text-align:center;">It is header tile</h2>
<hr/>
footer.jsp
<hr>
<h2 style="background-color:pink;text-align:center;">It is footer tile</h2>
login-success.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
Welcome, <s:property value="name"/>
</textrea></div>
<hr/>
<strong>login-error.jsp</strong>
<div class="codeblock"><textarea name="code" class="xml" >
Sorry, username or password error!
<jsp:include page="index.jsp"></jsp:include>
Output:

Password is not admin, so error page will be displayed.

If password is admin, success page will be displayed.


173
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

How to define multiple tiles files in struts 2 applicaiton


To define multiple tiles, you need to add following entry in your web.xml file.
<context-param id="struts_tiles">
<param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/tiles1.xml,/WEB-INF/tiles2.xml</param-value>
</context-param>
Hibernate and Struts 2 Integration
We can integrate any struts application with hibernate. There is no requirement of extra efforts.
In this example, we going to use struts 2 framework with hibernate. You need to have jar files for struts 2 and
hibernate.
Example of Hibernate and struts2 integration:
In this example, we are creating the registration form using struts2 and storing this data into the database using
Hibernate. Let's see the files that we should create to integrate the struts2 application with hibernate.
index.jsp file to get input from the user.
User.java A action class for handling the request. It uses the dao class to store the data.
RegisterDao.java A java class that uses DAO design pattern to store the data using hibernate.
user.hbm.xml A mapping file that contains information about the persistent class. In this case, action class
works as the persistent class.
hibernate.cfg.xml A configuration file that contains informations about the database and mapping file.
struts.xml file contains information about the action class and result page to be invoked.
welcome.jsp A jsp file that displays the welcome information with username.
web.xml A web.xml file that contains information about the Controller of Struts framework.
index.jsp
In this page, we have created a form using the struts tags. The action name for this form is register.
<%@ taglib uri="/struts-tags" prefix="S" %>
<S:form action="register">
<S:textfield name="name" label="Name"></S:textfield>
<S:submit value="register"></S:submit>
</S:form>
User.java
It is a simple POJO class. Here it works as the action class for struts and persistent class for hibernate. It calls
174
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

the register method of RegisterDao class and returns success as the string.
package com.javatpoint;
public class User {
private int id;
private String name;
//getters and setters
public String execute(){
RegisterDao.saveUser(this);
return "success";
}
}
RegisterDao.java
It is a java class that saves the object of User class using the Hibernate framework.
package com.javatpoint;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class RegisterDao {
public static int saveUser(User u){
Session session=new Configuration().
configure("hibernate.cfg.xml").buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
int i=(Integer)session.save(u);
t.commit();
session.close();
return i;
}
}
user.hbm.xml
This mapping file contains all the information of the persitent class.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.User" table="user451">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
</class>
</hibernate-mapping>
175
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

hibernate.cfg.xml
This configuration file contains informations about the database and mapping file. Here, we are using the
hb2ddl.auto property, so you don't need to create the table in the database.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
struts.xml
This files contains information about the action class to be invoked. Here the action class is User.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation
//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="abc" extends="struts-default">
<action name="register" class="com.javatpoint.User">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>
welcome.jsp
It is the welcome file, that displays the welcome message with username.
<%@ taglib uri="/struts-tags" prefix="S" %>
Welcome: <S:property value="name"/>
<%@ taglib uri="/struts-tags" prefix="S" %
Welcome: <S:property value="name"/>
web.xml
It is web.xml file that contains the information about the controller. In case of Struts2,
StrutsPrepareAndExecuteFilter class works as the controller.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
176
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping></web-app>
Hibernate and Spring Integration
We can simply integrate hibernate application with spring application.
In hibernate framework, we provide all the database information hibernate.cfg.xml file.
But if we are going to integrate the hibernate application with spring, we don't need to create the
hibernate.cfg.xml file. We can provide all the information in the applicationContext.xml file.
Advantage of Spring framework with hibernate:
The Spring framework provides HibernateTemplate class, so you don't need to follow so many steps like create
Configuration, BuildSessionFactory, Session, beginning and committing transaction etc.
So it saves a lot of code.
Understanding problem without using spring:
Let's understand it by the code of hibernate given below:
//creating configuration
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
//creating seession factory object
SessionFactory factory=cfg.buildSessionFactory();
//creating session object
Session session=factory.openSession();
//creating transaction object
Transaction t=session.beginTransaction();
Employee e1=new Employee(111,"arun",40000);
session.persist(e1);//persisting the object
t.commit();//transaction is commited
session.close();
As you can see in the code of sole hibernate, you have to follow so many steps.
Solution by using HibernateTemplate class of Spring Framework:
177
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Now, you don't need to follow so many steps. You can simply write this:
Employee e1=new Employee(111,"arun",40000);
hibernateTemplate.save(e1);
Methods of HibernateTemplate class:
Let's see a list of commonly used methods of HibernateTemplate class.
No.
Method
Description
1)void persist(Object entity)
persists the given object.
2)Serializable save(Object entity)
persists the given object and returns id.
3)void saveOrUpdate(Object entity) persists or updates the given object. If id is found, it updates the record
otherwise saves the record.
4)void update(Object entity)
updates the given object.
5)void delete(Object entity)
deletes the given object on the basis of id.
6)Object get(Class entityClass, Serializable id)
returns the persistent object on the basis of given id.
7)Object load(Class entityClass, Serializable id)
returns the persistent object on the basis of given id.
8)List loadAll(Class entityClass)
returns the all the persistent objects.
Steps:
Let's see what are the simple steps for hibernate and spring integration:
create table in the database It is optional.
create applicationContext.xml file It contains information of DataSource, SessionFactory etc.
create Employee.java file It is the persistent class
create employee.hbm.xml file It is the mapping file.
create EmployeeDao.java file It is the dao class that uses HibernateTemplate.
create InsertTest.java file It calls methods of EmployeeDao class.
Example of Hibernate and spring integration:
In this example, we are going to integrate the hibernate application with spring. Let's see the directory structure
of spring and hibernate example.
1) create the table in the database
In this example, we are using the Oracle as the database, but you may use any database. Let's create the table
in the oracle database
CREATE TABLE "EMP558"
( "ID" NUMBER(10,0) NOT NULL ENABLE,
"NAME" VARCHAR2(255 CHAR),
"SALARY" FLOAT(126),
PRIMARY KEY ("ID") ENABLE
)
/
2) Employee.java
It is a simple POJO class. Here it works as the persistent class for hibernate.
package com.javatpoint;
public class Employee {
178
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

private int id;


private String name;
private float salary;
//getters and setters
}
3) employee.hbm.xml
This mapping file contains all the information of the persistent class.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp558">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
4) EmployeeDao.java
It is a java class that uses the HibernateTemplate class method to persist the object of Employee class.
package com.javatpoint;
import org.springframework.orm.hibernate3.HibernateTemplate;
import java.util.*;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
//method to save employee
public void saveEmployee(Employee e){
template.save(e);
}
//method to update employee
public void updateEmployee(Employee e){
template.update(e);
}
//method to delete employee
public void deleteEmployee(Employee e){
template.delete(e);
}
//method to return one employee of given id
public Employee getById(int id){
179
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Employee e=(Employee)template.get(Employee.class,id);
return e;
}
//method to return all employees
public List<Employee> getEmployees(){
List<Employee> list=new ArrayList<Employee>();
list=template.loadAll(Employee.class);
return list;
}
}
5) applicationContext.xml
In this file, we are providing all the informations of the database in the BasicDataSource object. This object is
used in the LocalSessionFactoryBean class object, containing some other informations such as
mappingResources and hibernateProperties. The object of LocalSessionFactoryBean class is used in the
HibernateTemplate class. Let's see the code of applicationContext.xml file.
File: applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="system"></property>
<property name="password" value="oracle"></property>
</bean>
<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
180
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">


<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="com.javatpoint.EmployeeDao">
<property name="template" ref="template"></property>
</bean>
</beans>
6) InsertTest.java
This class uses the EmployeeDao class object and calls its saveEmployee method by passing the object of
Employee class.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class InsertTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
EmployeeDao dao=(EmployeeDao)factory.getBean("d");
Employee e=new Employee();
e.setId(114);
e.setName("varun");
e.setSalary(50000);
dao.saveEmployee(e);
}
}
Now, if you see the table in the oracle database, record is inserted successfully.
Enabling automatic table creation, showing sql queries etc.
You can enable many hibernate properties like automatic table creation by hbm2ddl.auto etc. in
applicationContext.xml file. Let's see the code:
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
If you write this code, you don't need to create table because table will be created automatically.

Spring Data JPA Tutorial


181
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

Spring Data JPA API provides JpaTemplate class to integrate spring application with JPA.
JPA (Java Persistent API) is the sun specification for persisting objects in the enterprise application. It is
currently used as the replacement for complex entity beans.
The implementation of JPA specification are provided by many vendors such as:
Hibernate
Toplink
iBatis
OpenJPA etc.
Advantage of Spring JpaTemplate:
You don't need to write the before and after code for persisting, updating, deleting or searching object such as
creating Persistence instance, creating EntityManagerFactory instance, creating EntityTransaction instance,
creating EntityManager instance, commiting EntityTransaction instance and closing EntityManager.
So, it save a lot of code.
In this example, we are going to use hibernate for the implementation of JPA.
Example of Spring and JPA Integration:
Let's see the simple steps to integration spring application with JPA:
create Account.java file
create Account.xml file
create AccountDao.java file
create persistence.xml file
create applicationContext.xml file
create AccountsClient.java file
In this example, we are going to integrate the hibernate application with spring. Let's see the directory structure
of jpa example with spring.
1) Account.java
It is a simple POJO class.
package com.javatpoint;
public class Account {
private int accountNumber;
private String owner;
private double balance;
//no-arg and parameterized constructor
//getters and setters
}
2) Account.xml
This mapping file contains all the information of the persistent class.
<entity-mappings version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd ">
182
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<entity class="com.javatpoint.Account">
<table name="account100"></table>
<attributes>
<id name="accountNumber">
<column name="accountnumber"/>
</id>
<basic name="owner">
<column name="owner"/>
</basic>
<basic name="balance">
<column name="balance"/>
</basic>
</attributes>
</entity>
</entity-mappings>
3) AccountDao.java
package com.javatpoint;
import java.util.List;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class AccountsDao{
JpaTemplate template;
public void setTemplate(JpaTemplate template) {
this.template = template;
}
public void createAccount(int accountNumber,String owner,double balance){
Account account = new Account(accountNumber,owner,balance);
template.persist(account);
}
public void updateBalance(int accountNumber,double newBalance){
Account account = template.find(Account.class, accountNumber);
if(account != null){
account.setBalance(newBalance);
}
template.merge(account);
}
public void deleteAccount(int accountNumber){
Account account = template.find(Account.class, accountNumber);
if(account != null)
template.remove(account);
}
public List<Account> getAllAccounts(){
List<Account> accounts =template.find("select acc from Account acc");
183
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

return accounts;
}
}
4) persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="ForAccountsDB">
<mapping-file>com/javatpoint/Account.xml</mapping-file>
<class>com.javatpoint.Account</class>
</persistence-unit>
</persistence>
5) applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<tx:annotation-driven transaction-manager="jpaTxnManagerBean" proxy-target-class="true"/>
<bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="system"></property>
<property name="password" value="oracle"></property>
</bean>
<bean id="hbAdapterBean" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"></property>
<property name="generateDdl" value="true"></property>
<property name="databasePlatform" value="org.hibernate.dialect.OracleDialect"></property>
</bean>
<bean id="emfBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSourceBean"></property>
<property name="jpaVendorAdapter" ref="hbAdapterBean"></property>
</bean>
<bean id="jpaTemplateBean" class="org.springframework.orm.jpa.JpaTemplate">
<property name="entityManagerFactory" ref="emfBean"></property>
</bean>
<bean id="accountsDaoBean" class="com.javatpoint.AccountsDao">
184
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<property name="template" ref="jpaTemplateBean"></property>


</bean>
<bean id="jpaTxnManagerBean" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emfBean"></property>
</bean>
</beans>
The generateDdl property will create the table automatically.
The showSql property will show the sql query on console
6) Accountsclient.java
package com.javatpoint;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class AccountsClient{
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountsDao accountsDao = context.getBean("accountsDaoBean",AccountsDao.class);
accountsDao.createAccount(15, "Jai Kumar", 41000);
accountsDao.createAccount(20, "Rishi ", 35000);
System.out.println("Accounts created");
//accountsDao.updateBalance(20, 50000);
//System.out.println("Account balance updated");
/*List<Account> accounts = accountsDao.getAllAccounts();
for (int i = 0; i < accounts.size(); i++) {
Account acc = accounts.get(i);
System.out.println(acc.getAccountNumber() + " : " + acc.getOwner() + " (" + acc.getBalance() + ")");
}*/
//accountsDao.deleteAccount(111);
//System.out.println("Account deleted");
}
}
Output:
Hibernate: insert into account100 (balance, owner, accountnumber) values (?, ?, ?)
Hibernate: insert into account100 (balance, owner, accountnumber) values (?, ?, ?)
Accounts created

12-Development
Struts 2 Registration Form Example
In this example, we are going to create a registration form using struts UI tags and store these
information into the oracle database. You may use other database also such as mysql, DB2 etc.
according to your requirement.
Let's see the table first that we need to create in the oracle database.
185
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

CREATE TABLE "STRUTSUSER"


( "NAME" VARCHAR2(4000),
"PASSWORD" VARCHAR2(4000),
"EMAIL" VARCHAR2(4000),
"GENDER" VARCHAR2(4000),
"COUNTRY" VARCHAR2(4000)
)
/
It will be better for you to create an id for each user. To simply the example, we have not alloted
any id with primary key enabled. But you can do it.
The steps to create the registration application in struts2 are as follows:
Create input page (index.jsp)
Create the action class (RegisterAction.java)
Create the class to store data (RegisterDao.java)
Map the request in (struts.xml) file and define the view components
Create view components
1) Create input page (index.jsp)
It is the simple jsp page that uses struts 2 UI tags to create a form to get input from the user.
index.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:form action="register">
<s:textfield name="name" label="UserName"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:textfield name="email" label="Email"></s:textfield>
<s:radio list="{'male','female'}" name="gender"></s:radio>
<s:select cssStyle="width:155px;"list="{'india','pakistan','other',}"
name="country" label="Country"></s:select>
<s:submit value="register"></s:submit>
</s:form>
2) Create the action class (RegisterAction.java)
This Action class has five fields and one execute method. As we know, struts framework creates
instance of the action class per request, we are passing this object in the save method of
RegisterDao class.
RegisterAction.java
package com.javatpoint;
public class RegisterAction {
private String name,password,email,gender,country;
//setters and getters
public String execute(){
int i=RegisterDao.save(this);
if(i>0){
return "success";
186
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

}
return "error";
}
}
3) Create the class to store data (RegisterDao.java)
This class gets information from the object of RegisterAction class and stores these information
in the strutsuser table.
RegisterDao.java
package com.javatpoint;
import java.sql.*;
public class RegisterDao {
public static int save(RegisterAction r){
int status=0;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("insert into strutsuser values(?,?,?,?,?)");
ps.setString(1,r.getName());
ps.setString(2,r.getPassword());
ps.setString(3,r.getEmail());
ps.setString(4,r.getGender());
ps.setString(5,r.getCountry());
status=ps.executeUpdate();
}catch(Exception e){e.printStackTrace();}
return status;
}
}
4) Map the request in (struts.xml) file and define the view components
This xml file contains information about the package, action class and view components.
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD
Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="register" class="com.javatpoint.RegisterAction">
<result name="success">register-success.jsp</result>
<result name="error">register-error.jsp</result>
</action>
</package>
</struts>
5) Create view components
Here, we are creating two view components register-success.jsp and register-error.jsp.
register-success.jsp
187
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<%@ taglib uri="/struts-tags" prefix="s" %>


Welcome, <s:property value="name"></s:property>
register-error.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
Sorry, some error occured!
<s:include value="index.jsp"></s:include>

Struts 2 Login and Logout Example


Before creating the login and logout application using struts 2, you must clear the concepts of
aware interfaces in struts 2. In this example, we have used the SessionAware interface to put the
information in the session scope and ServletActionContext class to get the information from
the session scope.
This example contains three links login, logout and profile. The end user cannot click on the
profile page until he/she is logged in. After getting logged in, he/she may go the profile page. If
the end user clicks on the logout page, he will not be able to access the profile page.
Here, we assume that you have a table in oracle database named user3333 that contains records.
The table query is:
CREATE TABLE "USER3333"
( "ID" NUMBER,
"NAME" VARCHAR2(4000),
"PASSWORD" VARCHAR2(4000),
"EMAIL" VARCHAR2(4000),
CONSTRAINT "USER3333_PK" PRIMARY KEY ("ID") ENABLE
)
/
Example of creating login and logout application using struts 2
In this example, we are need following pages
index.jsp for providing links to the login, logout and profile.
struts.xml for defining the result and action.
Login.java for defining login and logout logic.
LoginDao.java for matching username and password in the database.
Profile.java for checking if the user is logged in or not.
View components for the displaying results.
1) Create index.jsp for input
This jsp page creates three links for login, logout and profile.
index.jsp
<hr/>
<a href="login">login</a>|
<a href="logout">logout</a>|
<a href="profile">profile</a>
2) Define action and result in struts.xml
This xml file defines one package and 4 actions. Each action defines at least one result page.
For the loginprocess and logout actions, we are using the same action class but there invocation
methods are different.
188
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD
Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="abc" extends="struts-default">
<action name="login">
<result >login.jsp</result>
</action>
<action name="loginprocess" class="com.javatpoint.Login">
<result name="success" >loginsuccess.jsp</result>
<result name="error" >loginerror.jsp</result>
</action>
<action name="logout" class="com.javatpoint.Login" method="logout">
<result name="success" >logoutsuccess.jsp</result>
</action>
<action name="profile" class="com.javatpoint.Profile">
<result name="success" >profilesuccess.jsp</result>
<result name="error" >profileerror.jsp</result>
</action>
</package>
</struts>
3) Create the action class for login and logout
This action class implements the SessionAware interface and overrides the setSession method to
store the information in the session scope.
For logout, we are simply calling the invalidate() method of SessionMap.
Login.java
package com.javatpoint;
import java.util.Map;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
public class Login implements SessionAware{
private String username,userpass;
SessionMap<String,String> sessionmap;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
189
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

}
public String getUserpass() {
return userpass;
}
public void setUserpass(String userpass) {
this.userpass = userpass;
}
public String execute(){
if(LoginDao.validate(username, userpass)){
return "success";
}
else{
return "error";
}
}
public void setSession(Map map) {
sessionmap=(SessionMap)map;
sessionmap.put("login","true");
}
public String logout(){
sessionmap.invalidate();
return "success";
}
}
4) Create the Dao class to authenticate user
This class simply validates the user from the table stored in the oracle database.
LoginDao.java
package com.javatpoint;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class LoginDao {
public static boolean validate(String username,String userpass){
boolean status=false;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement(
"select * from user3333 where name=? and password=?");
ps.setString(1,username);
190
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

ps.setString(2,userpass);
ResultSet rs=ps.executeQuery();
status=rs.next();
}catch(Exception e){e.printStackTrace();}
return status;
}
}
5) Create the Profile class
This class gets the information from the session scope, if any information is found in the session
scope with login name, it returns success otherwise false.
Profile.java
package com.javatpoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
public class Profile {
public String execute(){
HttpServletRequest request=ServletActionContext.getRequest();
HttpSession session=request.getSession();
String s=(String)session.getAttribute("login");
if(s!=null && !s.equals("")){
return "success";
}
else{
return "error";
}
}
}
6) Create view components
There are many view components:
login.jsp
loginsuccess.jsp
loginerror.jsp
logoutsuccess.jsp
profilesuccess.jsp
profileerror.jsp
view components for login
login.jsp
This page creates the login form.
<jsp:include page="index.jsp"></jsp:include>
<hr/>
<%@ taglib uri="/struts-tags" prefix="s" %>
191
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

<s:form action="loginprocess">
<s:textfield name="username" label="Name"></s:textfield>
<s:password name="userpass" label="Password"></s:password>
<s:submit value="login"></s:submit>
</s:form>
loginsuccess.jsp
This page prints the welcome message with the username.
<jsp:include page="index.jsp"></jsp:include>
<hr/>
<%@ taglib uri="/struts-tags" prefix="s" %>
<br/>Welcome, <s:property value="username"/>
loginerror.jsp
This page displays the error message.
Sorry username or password error!
<jsp:include page="login.jsp"></jsp:include>
view components for logout
logoutsuccess.jsp
This page simply displays the successfully logged out message.
<jsp:include page="index.jsp"></jsp:include>
<hr/>
You are successfully logged out!
view components for profile
profilesuccess.jsp
This page prints the welcome to profile message.
<jsp:include page="index.jsp"></jsp:include>
<hr/>
<br/>Welcome to profile
profileerror.jsp
This page prints the message to login first and includes the login.jsp page.
Please login first to see profile
<jsp:include page="login.jsp"></jsp:include>
<s:property value="email"/><br/>
</fieldset>
</s:iterator>

Struts Interview Questions


192
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

There is given frequently asked struts interview questions and answers that has been asked in
many companies. Let's see the list of top Struts2 interview questions.
1) What is Struts?
Struts is a framework for developing MVC-based framework. Struts2 is the combination of
Webwork and struts1 frameworks.
2) What is the difference between struts1 and struts2?
No. Struts1
Struts2
Action class is not POJO. You need to Action class is POJO. You don't need to inherit
1)
inherit abstract class.
any class or implement any interface.
Front
Controller
is
2) Front controller is ActionServlet.
StrutsPrepareAndExecuteFilter.
It uses the concept of RequestProcessor It uses the concept of Interceptors while
3)
class while processing request.
processing the request.
It has JSP, Freemarker, Valocity etc. for the view
It has only JSP for the view component.
4)
component.
Configuration file name can be
Configuration file must be struts.xml and placed
5) [anyname].xml and placed inside WEBinside classes directory.
INF directory.
Action and Model are combined within action
6) Action and Model are separate.
class.
3) What are the features of Struts?
Configuration MVC components
POJO based action
AJAX Support
Various Tag Support
Various Result Types
Integration Support
4) What is MVC?
MVC is a design pattern. MVC stands for Model, View and Controller. Model represents data,
view represents presentation and controller acts as an interface between model and view.
5) What is interceptor?
Interceptor is an object i.e. invoked at preprocessing and postprocessing of a request. It is
pluggable.
6) What are the life cycle methods of interceptor?
public void init()
public void intercept(ActionInvocation ai)
public void destroy()
7) What is ValueStack?
ValueStack is a stack that contains application specific object such as action and other model.
8) What is ActionContext?
ActionContext is a container in which action is executed. It is unique per thread.
9) What is ActionInvocation?
193
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

ActionInvocation is responsible to invoke action. It holds action and interceptor objects.


10) What is OGNL?
OGNL is an expression language of struts2. It stands for Object Graph Navigation Language.
11) What are the 5 constants of Action interface?
SUCCESS
ERROR
INPUT
LOGIN
NONE
12) What does params interceptor?
The params (also known as parameters) interceptor sets all parameters on the ValueStack.
13) What does execAndWait interceptor?
The execAndWait (also known as ExecuteAndWait) interceptor is used to display intermediate or
wait result.
14) What does modelDriven interceptor?
The modelDriven interceptor makes other model as the default object of ValueStack. By default,
action is the default object of ValueStack.
15) What does validation interceptor?
The validation interceptor performs validation checks and adds field-level and action-level error
messages.
16) What are the bundled validators?
requiredstring
stringlength
email
date
int
double
url
regex
17) What is the difference between plain-validator and field-validator?
In plain-validator one validator can be applied to many fields. In field-validator many validators
can be applied to single field.

194
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

18) What is the use of jsonValidation?


The jsonValidation interceptor is used to perform asynchronous validation. It works with
validation and workflow interceptors.
19) What are the aware interfaces in struts2?
Aware interfaces are used to store information in request, session, application and response
objects. The 4 aware interfaces are given below:
ServletRequestAware
ServletResponseAware
SessionAware
ServletContextAware
20) What does i18n interceptor?
The i18n interceptor is used to provide multi lingual support for struts application.

195
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901

S-ar putea să vă placă și