Final Advance Java
Final Advance 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
<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:
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
4-JSP Directive
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" %>
5-JSP Exception
9
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
<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
Action Description
jsp:forward
jsp:include
jsp:useBean
jsp:setProperty
jsp:param
jsp:fallback
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development. So we
will see these tags in bean developement.
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
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
7-Expression Language
15
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
requestScope
sessionScope
applicationScop it maps the given attribute name with the value set in
e
the application scope
Param
paramValues
Header
headerValues
Cookie
initParam
pageContext
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
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)
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()
IterationTag interface
The IterationTag interface is the sub interface of the Tag interface. It provides an
additional method to reevaluate the body.
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.
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.
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
Output:
24
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
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
<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
Description
public
void
_jspService(ServletRequest It is invoked at each request,
request,ServletResponse)throws
same as service() method of
ServletException,IOException
servlet.
public void jspDestroy()
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
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
39
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
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;
<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
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.
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
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.
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:
55
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
-->
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:
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.
<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
<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
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
69
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
OUTPUT
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
<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");
}
</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
session.persist(question1);
session.persist(question2);
t.commit();
session.close();
System.out.println("success");
}
}
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
-->
<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();
}
}
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
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
87
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
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
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>
"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("[email protected]");
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
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).
//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
102
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
104
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
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")
110
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
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
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
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)
2)
3)
4)
5)
6)
Object get(Class entityClass, Serializable returns the persistent object on the basis of given id.
id)
7)
Object
load(Class
Serializable id)
8)
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-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
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">
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
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
<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="[email protected]" />
<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="[email protected]";//write here sender gmail id
String receiver="[email protected]";//write here receiver id
m.sendMail(sender,receiver,"hi","welcome");
System.out.println("success");
}
}
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
<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
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>
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
149
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
Description
1)
public
ActionContext returns the ActionContext object associated
getInvocationContext()
with the ActionInvocation.
2)
3)
4)
5)
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
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
6-Interceptor
158
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
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
excludeParams
acceptParamNames
Parameter
delay
Description
specifies the initial delay time. Bydefault, no
initial delay is set.
</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
Struts
Configuration
166
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
2.1//EN"
168
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
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:
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
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
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
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
}
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
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>
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
194
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901
195
B-208 Manubhai Tower , Sayajigunj
MobileNo:9327219987
nd
2 Floor, Ronak Plaza, Tulsidham Char Rasta, Manjalpur
.MobileNo:9328994901