Unit 5
Unit 5
E-Content
UNIT-I:Servlet
Overview – the Java web server – your first servlet – servlet chaining – server
side includes- Session management – security – HTML forms – using JDBC in
servlets – Applet to Servlet communication.
Servlet
OverviewofServlets
Java Servlets are programs that run on a Web or Application server and act as a middle
layer between a requests coming from a Web browser or other HTTP client and
databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically.
JavaServletsoftenservethesamepurposeasprogramsimplementedusingthe Common
Gateway Interface (CGI).
ButServletsofferseveraladvantagesincomparisonwiththeCGI.
• Performanceissignificantlybetter.
• Servlets execute within the address space of a Web server. It is not necessary to
create a separate process to handle each client request.
• Servletsareplatform-independentbecausetheyarewritteninJava.
• Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine. So servlets are trusted.
• The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.
LifeCycleofaServlet
Three methods are central to the life cycle of a servlet. These are init( ), service( ), and
destroy( ). They are implemented by every servlet and are invoked at specific times by
the server.
init()method:
The server invokes the init( ) method of the servlet. This method is invoked only when
the servlet is first loaded into memory. It is possible to pass initialization parameters to
the servlet so it may configure itself.
AJAVA_UNIT_I_SERVLETS
service()method:
The server invokes the service( ) method to process the HTTP request.It may also
formulateanHTTP responsefor theclient.Theservice()methodiscalledforeachHTTP
request.
destroy()method:
The server calls the destroy( ) method to relinquish any resources such as file
handlesthat are allocated for the servlet.
ServletAPIorServletArchitecture
Two packages contain the classes and interfaces that are required to build servlets.
These are javax.servlet and javax.servlet.http. They constitute the Servlet API.
Thejavax.servletpackagecontainsanumberofinterfacesandclassesthatestablishthe
framework in which servlets operate.
Interface Description
Servlet Declares life cycle methods fora
servlet.
ServletRequest Usedtoreaddatafromaclient
request.
ServletResponse Usedtowritedatatoaclientresponse.
Class/Interface Description
Thebaseclassthatrepresentsa HTTP
HttpServlet
Servlet
The class that encapsulates allthe
HttpServletRequest
HTTP request details
TheclassusedforsendingHTTP
HttpServletResponse
response back to the browser.
Class used for dynamically
ServletConfig
initializing the servlet
HttpSession Classusedforsessionmanagement
Class used by the servlet to
RequestDispatcher dispatch the request to various
resources.
AJAVA_UNIT_I_SERVLETS
ExampleProgram:Asimpleservletthatdisplaysagreeting
package myservlets;import
javax.servlet.*; import
javax.servlet.http.*; import
java.io.*;
publicclassGreetingServletextendsHttpServlet
{
publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriterpw=res.getWriter();
pw.println("<h1>WelcometoServlets</h1>");
}}
DeploymentDescriptor
ThisfiledefinesthefollowingimportantinformationpertainingtoaServlet:
<servlet>
<servlet-name>FormProcessingServlet</servlet-name>
<servlet-class>myservlets.FormProcessingServlet</servlet-class>
</servlet>
The second thing is to define the URL mapping which identifies how the servlet can
receive HTTP requests from the browser. For the above servlet, the url mapping will be
as shown below:
<servlet-mapping>
<servlet-name>FormProcessingServlet</servlet-name>
<url-pattern>/FormProcessingServlet</url-pattern>
</servlet-mapping>
ServletInitialialization
Servlet initialization is done in the init() method of the servlet. The web container while
loading the servlet, invokes the init() method of the servlet as part of the life cycle and
passestheparametersdefinedintheweb.xmltoit.Theotheradvantagewiththisis
AJAVA_UNIT_I_SERVLETS
approach is that if the initialization values need to be changed, it is only to change the
web.xml without having to recompile the entire web application.
Initialization parameters to a servlet are defined in the web.xml using the <init-param>
element as shown below:
<init-param>
<param-name>driver</param-name>
</param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
TheJavawebserver
The Web Server is the software responsible for accepting browser requests, retrieving
the specified file(executing the specified CGI,PHP,ASP Script),and returning its
contents(or the script’s results).Most Web servers on the Internet today run on UNIX
machines, although the percentage of servers on other platforms(such as Windows
95,Windows NT,and Macintosh are steadily increasing.
Web servers first retrieve the request using sockets, a mechanism for communicating
over a network. The Web server listens for requests on a particular port on the server
machine, generally port 80. By default, Web browsers use port 80 for their requests.
Once the server receives the request, it locates the document being requested. It looks
for the file under document root directory.
The server sends the contents of the file back to the client, along with some HTTP
responseheaders.Amongthedataintheresponseheaderisthemediatype(alsoknown as
content type or MIME type), i.e. the format that the file is in. The way it determines
theformatdependsontheserver,butusuallyitcomesfromthesuffixofthedocument
.html is taken to be an HTML document, .pdf is assumed to be an Adobe Acrobat
document, etc.
AWebserverisalsocalledaHypertextTransferProtocol(HTTP)becauseitusesHTTPto
communicate with its clients, which are usually browsers. A Java web based server uses
two important classes, java.net.Socket and java.net.ServerSocket, and communicates
through HTTP messages.
TheHypertextTransferProtocol(HTTP)
HTTPusesreliableTCPconnections,bydefaultonTCPport80.ThefirstversionofHTTP was
HTTP/0.9, which was then overriddenby HTTP/1.1, which is defined byRFC 2616.
callback connection to the client. Either the client or the server can prematurely
terminate a connection. For example, when using a web browser, clicking the Stop
button on the browser to stop the download process of a file, effectively closing the
HTTP connecting with the server.
HTTPRequests
AnHTTPrequestconsistsofthreecomponents:
Method-URI-Protocol/Version
Request headers
EntityBody
HTTPResponses
Similartorequests,anHTTPresponsealsoconsistsofthreeparts.
Protocol-Status code-Description
Responseheaders
Entity Body
TheSocketClass
YOURFIRSTJAVASERVLET
Servlets are basically developed forserver side applications anddesigned tohandle http
requests.The servlet-programminginterface (Java Servlet API) isa standard part of the
J2EE platform and has the following advantages over other common server extension
mechanisms:
• They are faster than other server extensions, like, CGI scripts because they usea
different process model.
• TheyuseastandardAPIthatissupportedbymanyWebservers.
• Since Servlets are written in Java, Servlets are portable between servers and
operatingsystems.TheyhavealloftheadvantagesoftheJavalanguage,includingease of
development.
TheycanaccessthelargesetofAPIsavailablefortheJavaplatform.
AJAVA_UNIT_I_SERVLETS
Now,afterinstallingtheTomcatServer,followingarethestepstocreateafirstJava Servlet.
• Createanewtextfileandsaveitas‘HelloWorld.java’inthe
• 'C:\jakarta-tomcat-4.0-b5\webapps\newcollege\WEB-
INF\classes\com\stardeveloper\servlets’ folder.
• '\WEB-INF\classes'isthefoldertokeepServletclasses.
• '\com\stardeveloper\servlets'isthepackagepathtotheServletclassthatto create.
• Nowtypethefollowingtextintothe'HelloWorld.java'filethatcreatedearlier.
//YourFirstServletprogram
import java.io.*;
import javax.servlet.*;
importjavax.servlet.http.*;
publicclassHelloWorldextendsHttpServlet
{
publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriterout=res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello, Welcome to the World of Servlet
Programming</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>Hello World</BIG>");
out.println("</BODY></HTML>");
}
}
ServletChaining
Servlet Chaining means the output of one servlet act as a input to another servlet.
Servlet Aliasing allows us to invoke more than one servlet in sequence when the URL is
opened with a common servlet alias. The output from first Servlet is sent as input to
other Servlet and so on. The Output from the last Servlet is sent back to the browser.
The entire process is called Servlet Chaining.
AJAVA_UNIT_I_SERVLETS
ServletChaining
RequestDispatching.:
MethodsofRequestDispatcherinterface
TheRequestDispatcherinterfaceprovidestwomethods.Theyare:
Includesthecontentofaresource(servlet,JSPpage,orHTMLfile)intheresponse
ExampleProgram:
web.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/java
ee/web-app_3_1.xsd">
<servlet>
<servlet-name>Test1</servlet-name>
<servlet-class>Test1</servlet-class>
</servlet>
<servlet>
<servlet-name>Test2</servlet-name>
<servlet-class>Test2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test1</servlet-name>
<url-pattern>/source</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Test2</servlet-name>
<url-pattern>/target</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>serchain.html</welcome-file>
</welcome-file-list>
<session-config>
<session-
timeout>30
</session-timeout>
</session-config>
</web-app>
serchain.html
<html>
<body>
AJAVA_UNIT_I_SERVLETS
<center>
<formaction="./source">
<b>EnteryourName:</b>
<inputtype="text"name="name1"> <br><br>
<inputtype="submit"value="submit">
</form>
</center>
</body>
</html>
Test1.java
import java.io.*;
import javax.servlet.*;
importjavax.servlet.http.*;
publicclassTest1extendsHttpServlet
{
publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriterout=res.getWriter();
String sname = req.getParameter("name1");
RequestDispatcherrd=req.getRequestDispatcher("/target");
if(sname!=null)
{
req.setAttribute("MyName",sname);
rd.forward(req,res);//ForwardthisvaluetoanotherServlet
}
else
{
res.sendError(res.SC_BAD_REQUEST,"MyNameRequired");
}
}
}
Test2.java
import java.io.*;
import javax.servlet.*;
importjavax.servlet.http.*;
publicclassTest2extendsHttpServlet
{
publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)throws ServletException ,
IOException
{
res.setContentType("text/html");
PrintWriterout=res.getWriter();
Stringmyname= (String)req.getAttribute("MyName");
AJAVA_UNIT_I_SERVLETS
out.println("MyNameis"+myname);
}
}
Server-SideIncludes
Servlets are not confined to handling entire requests. Some web servers allow servlets
toaddsmallamountsofdynamiccontenttootherwise staticHTMLpages.E.g.aserver- side
include to add a randomly selected advertisement to a page. A page that uses the
advertisementservletiswrittenlikeanormalHTMLpage,exceptthatitcontainsa
<SERVLET>tagandissaved with the .shtmlextension.Whenaclientrequestsa.shtml page,
the server finds all the <SERVLET> tags and replaces them with the output from the
appropriate servlets.
When using a <SERVLET> tag, you must include a CODE parameter that identifies the
servletto beloaded.Thiscanbeaclass nameoraservletaliasset upwithintheserver.
ExampleProgram
Here’sasample.shtmlfilethatusesaservletwithserver-sideinclude.
index.shtml
<HTML>
<HEAD><TITLE>Times!</TITLE></HEAD>
<BODY>
Thecurrenttimehereis:
<!--here thessiservletclasshasbeencalled-->
<SERVLETCODE=CurrentTime>
</SERVLET>
</BODY>
</HTML>
CurrentTime.javaim
port java.io.*; import
java.text.*; import
java.util.*; import
javax.servlet.*;
importjavax.servlet.http.*;
publicclassCurrentTimeextendsHttpServlet{ private
static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
PrintWriterout=res.getWriter();
Date date = new Date();
DateFormat df = DateFormat.getInstance();
out.println("Thecurrenttimehereis:");
out.println(df.format(date));
}
}
AJAVA_UNIT_I_SERVLETS
web.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<web-
appversion="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/javaeehttp://java.s
un.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>CurrentTime</servlet-name>
<servlet-class>CurrentTime</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CurrentTime</servlet-name>
<url-pattern>/index.shtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.shtml</welcome-file>
</welcome-file-list>
</web-app>
Server-side includes can bea powerful tool but are not part of the standard Servlet API,
and therefore some servlet implementations may not support them.
SessionManagement
A web container provides a common storage area called assession to store the state
and provides access to this session to all the servlets within the web application. For
instance, servlet A can create some state (information) and store it in the session.
Servlet B can then get hold of the session and read the state.
Since the state (data or information) in the session is user specific, the web container
maintains a separate session for each and every user.
Aservletcandothefollowingfourmostimportantoperationstoworkwithsessions.
AJAVA_UNIT_I_SERVLETS
Createthesession
Store the data in the session
Readthedatafromthesession
Destroythesessionorinvalidatethesession.
CreatingaSession
TheservletAPIprovidesaclasscalledHttpSessiontoworkwithsessions.Tocreatea session, the
following session object is created:
HttpSessionsession=request.getSession(true);
StoringthedatainSession
Data in session is stored as key-valuepairjust likein HashMap orHashtable.Tostore the
data we use the setAttribute() method as shown below:
session.setAttribute(“price”,newDouble(“12.45”));
ReadingthedatafromtheSession
Toreadthedata,weneedtousethegetAttribute()methodbypassinginthekeyas shown below
which then returns the value object:
Doubled=(Double)session.getAttribute(“price”);
DestroyingtheSession
Asessionisusuallydestroyedbythelastpageorservletinthewebapplication.A session is
destroyed by invoking the invalidate() method as shown below:
session.invalidate();
Example:
import java.io.*;
import java.util.*;
import javax.servlet.*;
importjavax.servlet.http.*;
publicclassSessionServletextendsHttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
HttpSessionhs=req.getSession(true);
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.print("<B>");
Datedate=(Date)hs.getAttribute("date");
if(date!=null)
{
pw.println("Lastaccess:"+date);
AJAVA_UNIT_I_SERVLETS
}
date=new Date();
hs.setAttribute("date",date);
pw.println("currentdate:"+date);
}
}
Security
A servlet can originate from several sources. A webmaster may have written it; a user
may have written it; it may have been bought as part of a third-party package or
downloaded from another web site.
Basedonthe sourceoftheservlet,acertainleveloftrustshouldbeassociatedwiththat servlet.
Some web servers provide a means to associate different levels of trust with different
servlets. This concept is similar to how web browsers control applets, and is known as
"sandboxing".
TheServletSandbox
A servlet sandbox is an area where servlets are given restricted authority on the server.
Theymaynothaveaccesstothefilesystemornetwork,ortheymayhave beengranteda more
trusted status. It is up to the web server administrator to decide which servlets are
granted this status. Note that a fully trusted servlet has full access to
theserver'sfilesystemandnetworkingcapabilities.Itcouldevenperform a System.exit(),
stopping the web server...
HTMLForms
HTMLisjustamarkuplanguage,ithassomebasicelementsandGUIcomponents,such as
buttons, text fields, check boxes, and dropdownlists, that allow users to enter data,
make some selections, and submit requests to a remote server.
Forexample,theHTML<FORM>tagenablesuserstoenterandsubmitdatafromaWeb page.
A<FORM>taghasimportantattributessuchasactionandmethod.Theactionattribute
containstheuniformresourcelocator(URL)oftheserverprogramtowhichthebrowser should
send the user’s input. The method attribute tells the browser how to send the data; this
attribute is usually either Get or Post, as shown in the following example:
<formaction=“http://www.mymagpublisher.com/servlet/LoginServlet”method=Get> A
text field can be created as follows:
<inputtype=Textname=”id”>
Thenameofthetextfieldwillbepassedbythebrowsertotheservletasaparameter name.
ThebuttonthatsendsthedataisoftypeSubmit,andthebuttonthatclearsallfieldsis of type
Reset:
<inputtype=”Submit”><inputtype=”Reset”>
AJAVA_UNIT_I_SERVLETS
UsingJDBCinservlets
JDBCisanapplicationprogramminginterface(JDBCAPI)thatdefinesasetofstandard
operations for interacting with relational database management systems (DBMSs).
JDBCDriversTypes:JDBCdriver implementationsvarybecauseofthewidevarietyof
operating systems andhardware platforms inwhich Java operates. Sunhas divided the
implementation types into four categories, Types 1, 2, 3, and 4.
Type1:JDBC-ODBCBridgeDriver:InaType1driver,aJDBCbridgeisusedtoaccess ODBC
drivers installed on each client machine.
Type2:JDBC-NativeAPI:
InaType2driver,JDBCAPIcallsareconvertedintonativeC/C++APIcalls,whichare unique to
the database. These drivers are typically provided by the database vendors and used
in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be
installed on each client machine.
AJAVA_UNIT_I_SERVLETS
Type3:JDBC-NetpureJava:
InaType3driver,athree-tierapproachisusedtoaccessdatabases.TheJDBCclients use
standard network sockets to communicate with a middleware application server.
Thesocketinformationisthentranslatedbythemiddlewareapplicationserverintothe call
format required by the DBMS, and forwarded to the database server.
Type4:100%PureJava
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's
database through socket connection. This is the highest performance driver available
for the database and is usually provided by the vendor itself.
AJAVA_UNIT_I_SERVLETS
UsingJDBCtoAccessDatabases
UsingJDBCtoaccessdatabasescanbedescribedinsixsteps.
i) loadtheJDBCdriverfortheDBMS
ii) toconnecttothedatabase;
iii) tocreateastatement
iv) toquerythedatabaseusingSQLSelectstatements;
v) toinsert/delete/updatedatainthedatabase.
vi) Closealltheresources,includingResultSet,Statement,andConnection,which
should be the last step of using JDBC.
Step1:LoadtheJDBCdrivers
AJavaprogramcanloadseveralJDBCdriversattime.Thisallowstheprogramtointeract with more
one database runningunder differentDBMSs. The following line of code
loads the JDBC driver for PostgreSQL,
Class.forName("org.postgresql.Driver");
Step2:Connecttothedatabase
Aconnectiontoadatabasecan beestablished viathegetConnectionmethodof
theDriverManagerclass.ThegetConnectionmethodacceptsthreeparameters--the
database, user name, and password.
Connectiondb=DriverManager.getConnection(url+dbname,usernm,passwd);
Here,theurlvariablecontainswhichJDBCdriveristousedforthisconnectionandalso which
machine, by IP address, hosts the DBMS and the database.
Step3:Createastatement
AStatementobjecthastheabilitytoparseSQLstatements,sendtheSQLstatements to the
DBMS, and accept the results returned from the DBMS.
Statementst= db.createStatement();
Step4and5:Interactwiththedatabase
Normally,twooperationsofStatementareneededtointeractwithadatabase.One
isexecuteQuery(sql_select),whichtakesaSQLSelectstatementasitsargument,
sendstheSelecttotheDBMS,andreturnstheresultsasanobjectofResultSet.The
otheroperationisexecuteUpdate(sql_insert_delete_update),whichtakesaSQLstatemen
t (Insert, Delete, or Update), sends it to the DBMS. Both operations throw
aSQLExceptionifthestatementcannotbeexecutedbytheDBMSsuccessfully.
Stringsql="SELECTname,title"+"FROMfacultyf,coursec"+"WHEREf.id=
AJAVA_UNIT_I_SERVLETS
c.instructor";
ResultSetrs=st.executeQuery(sql);
String faculty = '123456';
Stringsql="INSERTINTOfacultyVALUES("+'"+faculty+ "',
'Dave Letterman', 'Estate 1942', '941-6108')";
st.executeUpdate(sql);
Step6:Disconnectfromthedatabase
Whentheapplicationcompletesornofurtherdatabaseinteractionisneeded,youshould return
JDBC resources back to the system, which include, objects of Statement, ResultSet, and
Connection.
rs.close();
st.close();
Applet-servletcommunication
publicclassAppsextendsAppletimplementsActionListener
{
Button b;
TextField tf;
publicvoidinit()
{
b=newButton("callServlet");
b.addActionListener(this);
add(b);tf=newTextField(25);
add(tf);
}
publicvoidactionPerformed(ActionEventae)
{
try
{
URLu=newURL("http://localhost:8080/WebApplication11/Serv");
URLConnection urlc=u.openConnection();
InputStreamisr=urlc.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(isr));
tf.setText(br.readLine());
}
catch(Exceptione)
{
showStatus(e.toString());
}
}
}
Serv.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
importjavax.servlet.http.*;
publicclassServextendsHttpServlet
{
publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)throws
IOException,ServletException
{
Dated=newDate();
PrintWriterout=res.getWriter();
out.println(d.toString());
}
}
ReferenceBooks:
1. JEE1.4Bible,J.McGovern,R.Adatia,Y.Fain,Wiley-dreamtechPublication,2003
2. K.Moss,1999,JavaServlets,Secondedition,TataMcGrawHill,NewDelhi.
WebResources:
1. https://www.javatpoint.com/servlet-tutorial
2. https://www.geeksforgeeks.org/introduction-java-servlets/
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
ADVANCEJAVAPROGRAMMING
UNIT-II:JSP
Introduction-ExaminingMVCandJSP-JSPscriptingelements&directives-Workingwithvariables
scopes-Error Pages - using Java Beans in JSP -Working with Java Mail- Understanding Protocols in
JavaMail-Components-JavaMail API-Integrating into JEE-Understanding Java Messaging Services-
Transactions.
JAVASERVERPAGES
Introduction
JavaServerPage(JSP)—JavaServerPagesare“HTML-like”documentsthatcontainJavacode. A JSP
container compiles a JSP into a Servlet the first time the page is requested.
ExaminingMVCandJSP
• TheModel(Abstraction)representstheunderlyingapplicationobjectsthataccessthedatabase,
representbusinesslogic,etc.TheseobjectsaretypicallyJavaBeans,EJBs,orregularJavaclasses.
• TheControllerisresponsibleforcontrollingapplicationflowandmediatingbetweenthe
abstraction and presentation layers. The controller is typically a Servlet.
The client accesses the controller (Servlet) as the main page, or as the target action of a form
submission. The controller in turn accesses the underlying business logic and database code of the
abstraction layer and sets various data and helper objects into scoped attributes on the Servlet
(JavaBeans,EJBs,Javaclasses).Finally,therequestisredirectedtotheappropriateview(JSP)using
RequestDispatcher.forward().
JSPScriptingElementsandDirectives
JSPelements(tags)canbygroupedaccordingtothefunctionstheyperform.Forexample,theycanbe referred
to as variable declarations, expressions, page attributes, and so on. The tags are surrounded
byanglebrackets(<>),andlikeHTMLandXMLtagscanhaveattributes.Everythingelsethatcanbe
containedintheJSP page butthat cannotbe knownto the JSPtranslators(plaintext,HTML tags,and so on)
is called template data.
ThefollowingarethevariousscriptingelementsusedinJSP.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
✦Declarations
✦Expressions
✦Directives
✦Scriptlets
✦Comments
✦Actions
✦ImplicitJSPobjects
✦Errorpages
✦JavaBeans
Declarations
JSP declarations are equivalent to member variables and functions of a class. The declared variables
andmethodsareaccessiblethroughouttheJSP.Thesedeclarationsareidentifiedbyusing<%!%>or the XML
equivalent <jsp:declaration></jsp:declaration> tags.
Example:
<%!intbalance=0;%>
<%!publicintgetAccountBalance(){ return
balance;
}%>
<jsp:declaration>intbalance=0;</jsp:declaration>
<jsp:declaration>
publicintgetAccountBalance()
{
returnbalance;
}
</jsp:declaration>
Expressions
An expression is an instruction to the web container to execute the code within the expression and
replaceitwiththeresultsintheoutputtedcontent.Anythingplacedinsideofthe<%=and%>tagsis first
evaluated and then inserted in the final output. It’s XML equivalent is <jsp:expression>
</jsp:expression>tags.
Example:
<%doublesalary=50000;%>
YourNewSalaryis<%=salary*1.2%>
Scriptlets
A Scriptlet is a piece of Java code embedded in HTML that represents processing logic to generate
anddisplaythedynamiccontentwhereeverneededinthepage.Scriptletsaredeclaredusingthe<%
%>scripttags,orthe<jsp:scriptlet></jsp:scriptlet>XMLequivalents.
Example:
<%for(intn=0;n<10;n++)
{
out.println(n);
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
}
%>
Directives
DirectivesareinstructionsfromtheJSPtothe containerthatcanbeusedtosetthepageproperties,to import
Java classes and packages, and to include external web pages and custom tag libraries. The three
directives are:
• page—thepagedirectivesetstheattributesofthepageandprovidesthefunctionalityforimporting Java
classes. The page directive has eleven different attributes that control everything from the scripting
language to the classes and packages imported into the page.
Thegeneralsyntaxforusingapagedirective is
<%@pageattribute1="value1"attribute2="value2"...%>
Example:
<%@pageimport="java.util.Date,java.io.*"extends="myJSPpage"buffer="32k"autoflush="false"
%>
• include—ThisdirectiveenablestoimportthecontentsofanotherfileintothecurrentJSP page.
<%@includefile="/legal/disclaimer.html">
• Taglib—theTaglib directiveisusedforCustomTagLibraries.ThisdirectiveallowstheJSPpage
tousecustomtagswritteninJava.Customtagdefinitionsareusuallydefinedinaseparatefilecalled as Tag
Library Descriptor. For the current JSP to use a custom tag, it needs to import the tag library file
which is why this directive is used.
Followingishowtaglibdirectiveisused.
<%@tagliburi=”locationofdefinitionfile”prefix=”prefixname”%>
Actions
Actions instruct the container to perform specific tasks at runtime. These actions range from
forwardingcontroltoanotherpagetogeneratinganewJavaBeanfor useinthepage.Thefourtypes of actions
are:
• forward—Thisactiontransferscontroltoanewweb page.
• Beans—Beanactionsallowcreationanduseof JavaBeansinsideaJSP.Thebeanactionsare
explained in the Forms, JavaBeans, and JSP topic.
• Plug-in—The<jsp:plugin>actionisusedforworkingwithJavaapplets.Appletsareclient-side
programs that run on a browser.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
<%@includefile="myFile.html"%>
IncludingFilesatRuntime
Sometimes, to include some content that may change more frequently than a static page header. One
problem with using the include directive to include frequently changing files is that some servlet
engineswillfailtorecognizewhenanincludedfilehasbeenmodifiedandwillnotrecompiletheJSP. The
solutiontothisproblemisto includethefile atruntime instead. Here'sanexample of includinga file at
runtime:
<jsp:includepage="myContent.jsp"flush="true"/>
Theflushattributetellstheservletenginetoflushtheoutputbufferbeforeincludingthefile.
ImplicitObjects
The JSP container provides access to a set of implicit objects. These objects are extensions of
commonServletcomponentsandprovidesomeofthebasictoolsnecessarytobuildrealapplications with
JSP.
✦request—ThisvariablepointsatHttpServletRequest.Thefollowingexamplegetstheflight destination
entered by the user on the HTML page: <% String dest= request.getParameter(“destination”); %>
✦response—UsethisvariabletoaccesstheHttpServletResponseobject.Forexample:<%
response.setContentType(“text/html”); %>
✦out—This variable represents the JspWriter class, which has the same functionality as the
PrintWriterclassinservlets.Here’sanexample:<%out.println(“Enterflightdestination”);%>
✦session—ThisvariablerepresentstheinstanceoftheHTTPSessionobject.
✦exception—This variable represents an instance of the uncaught Throwable object and contains
errorinformation.ThisvariableisonlyavailablefromtheJSPerrorpagethatcontainsthedirective
isErrorPage=true.
✦page—ThisvariablerepresentstheinstanceoftheJSP’sJavaclassprocessingthecurrentrequest.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
✦application—ThisvariablegivesaccesstotheServletContextobjectwithouthavingtocall
getServletConfig().getContext().
✦config—ThisvariableprovidesaccesstotheServletConfigobject.
WorkingwithVariableScopes
TheScopeofanobjectinJSPdescribeshowwidelyitisavailableandwhohasaccess it.
<jsp:useBeanid=“employee”class=”classname”scope=”page”/>
(ii) Requestscope:Objectswithrequestscopeareaccessiblefrompagesprocessingthesamerequest in
which they are created.
<jsp:useBeanid=“employee”class=”classname”scope=”request”/>
<jsp:useBeanid=“employee”class=”classname”scope=”session”/>
<jsp:useBeanid=“employee”class=”classname”scope=”application”/>
2.5ErrorPages
InJavaServerPages(JSP),therearetwotypesof errors.Thefirsttypeoferrorcomesattranslationor
compilation time when JSP page is translated from JSP source file to Java Servlet class file. The
second type of JSP error which is called a request time error occurs during run time or request time.
Theseruntimeerrorsresultintheformofexception.ExceptionHandlingistheprocesstohandle runtime errors.
OnewaytoperformexceptionhandlinginJSPistheuseoferrorPageandisErrorPageattributesof page
directive
errorPageattribute
TheerrorPageattributeofpagedirectiveisusedtospecifythename oferrorpagethathandlesthe exception. The
error page contains the exception handling code description for a particular page.
Thesyntaxofthisattributeisasfollows:
<%@pageerrorPage=”relativeURL”%>
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
index.html
<formaction="process.jsp">
Enter the first Number:<input type="text" name="n1">
EnterthesecondNumber:<inputtype="text"name="n2">
<inputtype="submit"value="Calculate">
</form>
process.jsp
<%@pageerrorPage="error.jsp"%>
<%Stringnum1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
intb=Integer.parseInt(num2);
int c=a/b;
out.println("Divisionofnumberis:"+c);
%>
isErrorPageattribute
TheisErrorPageattributeindicateswhetherornotthecurrentpagecanactastheerrorpageforanother JSP page.
UseofisErrorPagetakesoneofthefollowingtwoforms:
<%@pageisErrorPage="true"%>
<%@pageisErrorPage="false"%>
<%!--Default--%>
error.jsp
<formaction="index.jsp">
<%@pageisErrorPage="true"%>
Sorry,anExceptionhasoccured!
Exceptionis <%=exception %>
<inputtype="submit"value="Re-Compute">
</form>
JavaBeansinJSP
Javabeansusedin JSPofferlotofflexibilityandavoidduplicatebusinesslogic.JSPtechnologyuses standard
actions for working with beans.
FollowingarethethreestandardactionsforworkingwithJavabeans:
a. <jsp:useBean>
b. <jsp:setProperty>
c. <jsp:getProperty>
a. jsp:useBean
ThisactionisusedbythewebcontainertoinstantiateaJavaBeanorlocateanexistingbean.Theweb container
then assigns the bean to an id which the JSP can use to work with it. The Java Bean is usually stored
or retrieved in and from the specified scope.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
Thesyntaxforthisactionisshownbelow:
<jsp:useBeanid=“employee”class=”classname”scope=”scopename”/>
If the scope is session, then the bean will be available to all the requests made by the client in the
samesession.Ifthescopeisrequest,thenthebeanwillonlybeavailableforthecurrentrequestonly.
b. jsp:setProperty
Thisactionasthenamesuggestsisusedtopopulatethebeanpropertiesinthespecifiedscope. Following is the
syntax for this action.
<jsp:setPropertyname=“employee”property="propertyname"value="data"/>
<jsp:setPropertyname"cus"property="firstName"value="John"/>
c. jsp:getProperty
Thisstandardactionis usedtoretrieveaspecifiedpropertyfroma beaninaspecifiedscope.
FollowingishowwecanusethisactiontoretrievethevalueoffirstNamepropertyinabean identified
by cus in the session scope.
<jsp:getPropertyname=”cus”property=”firstName”scope=”session”/>
JavaMail
TheJavaMailisanAPIthatisusedtocompose,writeandreadelectronicmessages(emails).
• TheJavaMailAPIprovidesprotocol-independentandplatform-independentframework for
sending and receiving mails.
• Thejavax.mailandjavax.mail.activationpackagescontainsthecoreclassesofJavaMail API.
• The JavaMail facility can be applied to many events. It can be used at the time of
registeringtheuser(sendingnotificationsuchasthanksforyourinteresttomysite), forgot
password (sending password to the users email id), sending notifications for
important updates etc. So there can be various usage of java mail api.
UnderstandingProtocolsinJavaMail
The protocols that underpin the workings of electronic mail are well established and very mature.
ThefollowingarethecoreprotocolimplementationsarebundledaspartoftheJavaMaildistribution.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
SMTP
SMTPisanacronymforSimpleMailTransferProtocol.Itwasfirstproposedbackin1982andwas designed for the
delivery of mail messages to servers.
POP
POP is an acronym for Post Office Protocol, also known as POP3. It provides a mechanism the
mechanismbywhichthemajorityofpeoplecollecttheire-mail.Itisthentheresponsibilityof theuser to take
care of the e-mail by filing it in some logical storage. It provides support for single mail box for each
user. The POP server does not offer any storage facilities beyond the mailbox that new mailis
delivered to.
IMAP
IMAP is an acronym for Internet Message Access Protocol. IMAP is an advanced protocol for
receivingmessages.Itprovidessupportformultiplemailboxforeachuser,inadditionto,mailbox can be
shared by multiple users. It is defined in RFC 2060.
MIME
MultipleInternetMailExtension(MIME)tellsthebrowserwhatisbeingsente.g.attachment,format of the
messages etc. It is not known as mail transfer protocol but it is used by the mail program.
NNTPandOthers
Therearemanyprotocolsthatareprovidedbythird-partyproviders.SomeofthemareNetworkNews Transfer
Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc.
JavaMailComponents
TheJavaMailAPIcontainsfourmajorcomponents:
✦Messagemanipulation—.Thisabstractclassjavax.mail.Messageprovidesthebasiccontainerfor the
representation of a mail message. A mail message is made up of two major components, a header and
some content.
TheMessageclassimplementsthejavax.mail.Partinterface,whichdealswiththefunctionality associated
with constructing the header and the content.
✦Mailstorageandretrieval—JavaMailprovidesthemanagementofmessagesandalsousedfor the
handling of groups of messages. If a message isn’t being sent or received, it is in storage.
Messagesarestoredinhierarchiesthatarenotunlikethoseoffilesanddirectories.TheJavaMailAPI has a suite
of classes for managing this storage, including classes for adding, deleting, and moving
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
messages.
✦Transportation—javax.mail.Transportistheclassresponsibleforthedeliveryofmessages.In the
majority of instances, SMTP protocol is used for delivery.
TheTransportclassoffersthefollowingstaticmethodforsendingmessages Transport.send(
msg );
JavaMailAPI
Sendinge-mailandattachments
Probablythefirstthing todoissendsomee-mail.Itisalreadydemonstratedhowtosend abasic plain-
text e-mail using the SMTP protocol, but have a look at an application that is a little more
functional.
Theclassjavamail_send,takesthefourfollowingparameters:
✦SMTPhost
✦toe-mail
✦frome-mail
✦e-mailbody
The e-mail message is created in the usual way with the MimeMessage class, using as little
informationaspossible.Afterallthenecessarypropertiesofthemessageareset,thestaticmethod
Transport.send(...)is used to the deliver the message.
Receivinge-mail
Receivinge-mailisassimpleassendinge-mail.Themajorityof theconceptsofdealingwithmailby
buildingasimplecommand-lineaccesstooltoPOP3mail.Thiswillbeaverysimpletool,anditmost certainly
will not replace Outlook or Eudora client!
Deletingmail
The POP client can be extended to include the abilityto delete a message in the folder. It can simply
addedtothe messagelooptheabilitytohandlethedelete<id>command,whichdeletioninturncalls the
deleteSingleMethod(...) shown next.
Receivingattachments
Thefinalpieceoffunctionalityisoughttoaddistheabilitytosaveattachmentstodisk.Addthesave
<id>command,whichwilllookupagiven message,seeif anyattachmentsareassociatedwithit,and then save it
into the current directory.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
IntegratingJavaMailintoJ2EE
ThemailSessionobjectisusedtocommunicatewithtransportlayertosende-mailwouldhavethe
hostname/ipaddressandmightevenincludesomeauthenticationtogaintherighttorelaye-mail.
J2EEenablestodeclarearesourceatruntimeunderthecomp/env/mailJNDIcontextname,towhich
canattachthe propertiesforSMTP.Manyof the J2EEapplication serverswillprovide accessto this
informationthroughtheirownadministration tools.Failingthat, look attheapplicationserver’sown
documentation for declaring JavaMail resource contexts.
InsteadofcreatingthePropertiesobjectasbefore,theSessionobjectusingJNDIwiththecontext name of
mail/mySMTP can be used.
LookinguptheSessionobject
This allows the component to remain completely generic and enables the administrator to decide
whichmaildevicesheorshewishestoconnectto.Inthisrespect,theJavaMailAPIisverymuchlike the JDBC
driver.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
UnderstandingJavaMessagingServices
Thekeyconceptsthatsurroundmessaging—thedifferentmessagingmodels,point-to-pointand
publish-subscribe, message-oriented middleware, and the various classes implemented in any
application that uses messaging.
ExplainingMessaging
Thebasicconceptbehindmessagingisthatdistributedapplicationscancommunicateusingaself- contained
package of business data and routing headers. These packages are messages.
IncontrasttoRemoteMethodInvocation(RMI)orHypertextTransferProtocol(HTTP),withwhich a client
contacts a server directly and conducts a two-way conversation, messaging-based apps
communicateasynchronouslythrougha messagingserver. Thatis,whena messageissentto another
application the sender does not wait for a response.
The software services that support message-based applications are referred to as message-oriented
middleware.Messagingistypicallyusedinsituationslikeenterprise-applicationintegration(EAI)and
business-to-business (B2B) communications.
IntroducingJMS
JMS is the Java Messaging Service. It is a wrapper API that does not provide any services directly,
butinsteadservestostandardizethemessagingfunctionalityprovidedbysomeotherserviceprovider, like
IBM’s MQSeries (now WebSphere MQ) or Sonic Software’s SonicMQ.
JMS provides a single API that can be used to access the messaging facilities provided by any
messaging-serviceprovider,muchasJavaDatabaseConnectivity(JDBC)isusedtoaccessany
relational database that provides a JDBC driver.
Messagestructure
ThefirstelementofJMStounderstandishowmessagesarestructured.A messageconsistsof the three
following parts:
✦Headers
✦Properties
✦Body
Thepropertiesareasetofkey-valuepairsusedforapplication-specificpurposes,usually to help
filter messages quickly when they’ve been received.
Finally, the body contains whatever data is being sent in the message. The contents of the bodyvary
dependingonthetypeofthemessage:Thejavax.jms.Messageinterfacehasseveralsubinterfacesfor different
types of messages.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
MessagingModels
JMSsupportstwodifferentmessagingmodels: point-to-point(p2p)andpublish-and-subscribe
(pub/sub).
Point-to-pointmessaging
Inthepoint-to-pointmodelmessagesaresentfromproducerstoconsumersvia queues.Agivenqueue may have
multiple receivers but only one receiver may consume each message.
Publish-and-subscribemessaging
Inthepublish-and-subscribemessagingmodel,messagesaresent(published)toconsumersviatopics.
Messages published on a specific topic are sent to all message consumers that have registered
(subscribed) to receive messages on that topic.
MajorJMSComponents
Thissectiondiscussesthefollowingcomponents:
✦Destinations
✦Connections
✦Connectionfactories
✦Sessions
✦Producers
✦Consumers
(i) Destinations
Adestinationis,asitsnameimplies,somewhereyou’resendingamessage.Specifictypesof destinations are
queues (in point-to-point systems) or topics (in publish/
subscribesystems).
(ii) Connections
JMSConnections aresimilartotheConnectionclassinJDBC—itrepresentsaconnectionbetween the
application and the messaging server over which messages can be sent.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
(iii) Connectionfactories
As in JDBC, connections in JMS are not directly instantiated. Instead, a connection factory creates
connections.ConnectionfactoriesanddestinationsaretheonlytypesofobjectsinJMSthatneedtobe obtained via
JNDI.
(iv) Sessions
Messagescannotsendandreceivemessagesdirectlythroughaconnection.Instead,aSessionis needed. A
session serves as a factory for message objects, message producers and consumers,
TemporaryTopics, and TemporaryQueues. It also does the following:
• Providestransactionalbehaviorfortheworkdonebyitsproducersandconsumers
• Definesaserialorderforthemessagesitconsumesandthemessagesitproduces
• Retainsmessagesitconsumesuntiltheyhavebeenacknowledged.
SessionsarecreatedusingaConnectionobject.Thesessioninterfaceisjavax.jms.Session.
(v) Producers
A message producer is an object created by a session and is used for sending messages to a
destination.ThePointToPointformofamessageproducerimplementstheQueueSenderinterface. The
pub/sub form implements the TopicPublisher interface.
(vi) Consumers
A message consumer is an object created by a session and is used for receiving messages sent to a
destination.AmessageconsumerallowsaJMSclienttoregisterinterestinadestinationwithaJMS provider. The
JMS provider manages the delivery of messages from a destination to the registered consumers of the
destination. The PTP form of message consumer implements the QueueReceiver interface. The pub/sub
form implements the TopicSubscriber interface.
ReliableMessaging
JMShasanumberof featuresthathelpensurereliability.
Autonomousmessages
Firstofallmessagesare autonomous—theyaregeneratedbyaproducer,receivedbyaconsumer,and may then
be retransmitted to another consumer.
Persistentmessages
Messages marked as persistent are guaranteed to be delivered by the messaging server. Once a
messageissuccessfullyreceiveditwillbestoredinapersistentdatastorelikeadatabaseorafile until it can be
delivered to a consumer.
Synchronousacknowledgments
Finally,avarietyofsynchronousacknowledgementsexistintheotherwiseasynchronous
message-transmissionprocess.WhenaJMSclientattemptstosendamessage,itfirstgoestotheJMS server, which
acknowledges successful receipt of the message.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_II_JSP_E_CONTENT
Transactions
Whenatomicdeliveryofseveralmessagesisneeded—thatis,eitherallthemessagesaredeliveredor none
is—a transaction is needed. JMS supports transactions in two ways—via the JMS transaction support
in the Session interface and via the distributed-transaction support in the Java Transaction API.
Tocreateasessionwithtransactionalbehavior,simplyspecifytrueasthefirstparameterpassedto createSession().
The new session object is now transacted.
All messages sent through anyproducer created using that session are part of the transaction until
eitherrollback()orcommit()isinvokedonthesession.Onceatransactioniscompletedbyeithera commit or
rollback a new transaction is started automatically.
Thefollowingcodefragmentshowshowasetofmessagescanbehandledinsideatransaction.
Sessionsession=connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(Destination);
//sendsomemessagesviaproducer
if(successful)
session.commit();
else
session.rollback();
Transactionsareaverypowerfultoolandanecessityinanyenvironmentwheredataintegrityisthe primary
concern.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_III_RMI_E_CONTENT
ADVANCEJAVA PROGRAMMING
UNIT-III:RMI
Overview – Developing applications with RMI: Declaring & Implementing remote
interfaces-stubs & skeletons, registering remote objects, writing RMI clients –
Pushing data from RMI Servlet – RMI over Inter-ORB Protocol.
REMOTEMETHODINVOCATION
RMI allows a java object that executes on one machine to invoke a method of a java that
executes on another machine.
ProvidinganOverviewofRMI
RMI is the action of invoking a method of a remote interface on a remote object. It enables
java clients to invoke methods on java objects living on the remote computer’s Java Virtual
Machine (JVM).
AnyRMIapplicationconsistsofthefollowing components:
o Client-AclientsidemachinewithaJVM
o Server-AserversidemachinewithaJVM
o Registry - The registry is the naming service. The RMI components usually run on separate
networkedcomputers.Theservercreatessomejavaobjects,registersthemwiththenaming
service, and waits for remote clients to invoke methods on these objects.
RMI technology is useful for many business applications written in java. Some of the typical
applications are listed here:
*Gettingstock-marketpricequotes
*Obtainingflightinformation
*Requestinganddownloadingmusicfiles
*Performinginventorymaintenance
DevelopingApplicationswithRMI
WritingdistributedRMIapplicationsusuallyconsistsofthefollowingsteps:
1. Declaringaremoteinterfacefortheclient.
2. Implementingaremoteinterfaceontheserver.
3. Writingaclientprogramthatusesthisremoteinterfacetoconnecttoaserverandcallsits
methods.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_III_RMI_E_CONTENT
4. Generatingstubs(clientproxies)andskeletons(serverentities).
5. Startingtheregistryontheserverandregisteringremoteobjectswithit.
6. Startingtheserverapplicationontheremotemachine.
7. Startingthe Javaapplication thatiseitherlocated ontheclientmachine ordownloaded as a
java applet.
DeclaringRemoteInterfaces
Aremoteinterfacedefinesmethod(s)thatcanbeinvokedremotelybyaclient. The
• An application’s remote interface must declare business methods having public access that
will enable clients to communicate with the server.
• An application’s remote interface must extend the java.rmi.Remote interface. The
Remoteinterface does not have any methods-just declare the required methods there.
• Eachmethodmustdeclareajava.rmi.RemoteExceptionoroneofitsancestors.
• Methodargumentsandreturndatatypesmustbe serializable.
Example:AdderInterface
importjava.rmi.*;
publicinterfaceAdderextendsRemote
{
publicintadd(intx,inty)throwsRemoteException;
}
The method add() constitute the only API that is available for the client. The class that
implements this method may have other methods as well, but those are hidden from the
client.
ImplementingRemoteInterfaces
In RMI, the interface and implementations are completely separated. While the remote
interface just declares the methods used by the client, the actual class that provides the
implementation for these methods will run on the server side in a separate JVM. These
methods must have exactly the same signatures as their proxies on the client; otherwisethe
RMI clients won’t find them.
2.2.3RemoteExceptions
In RMI applications, all remote methods must declare java.rmi.Remote Exception. This
exception will be thrown by the server application in such cases as communication failures,
marshalling or un marshalling errors, and so on. Because a RemoteException is a checked
exception, it has to be handled in the client code.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_III_RMI_E_CONTENT
Besides the RemoteException, a remote application can throw any other exceptions to be
handled by the client exactly as if they were thrown locally.
3.2.4StubsandSkeletons
After the remote interface and its implementation are created, there is aneed to generate
the objects responsible for the network communications between them.
The stub is a client-side object that represents the remote object. When a client calls a
remote method, the stub is invoked and it does the following:
o Initiatesaconnectionwiththeremote JVM
o Marshals(preparesandtransmits)theparameterstotheserver
o Waitsfortheresultofthemethodinvocation
o Unmarshals(reads)thereturnvalueorexceptionreturned
o Returnsthevaluetotheclient
An RMI server may have a similar object called a skeleton to process the client’s network
calls. It performs the following operations for each received call
o Unmarshals(reads)theparametersfortheremotemethod
o Invokesthemethodsontheactualremote-objectimplementation
o Marshalstheresulttothecaller
The skeleton is responsible for dispatching the client call to the actual object
implementation.
J2SE comes with the RMI compiler called rmic, which generates stubs and skeletons fromthe
existing implementation class.
The stub implements only remote interfaces. When the client calls a remote method the
stub marshals and serializes the data over the network to the skeleton (or to the server
application). The skeleton in turn unmarshals and deserializes the data on the remote
machine and passesthedatatothe actual implementation ofthe method. After the method
completes, the return value is delivered back to the client in the reverse order. Obviously,
the remote method parameters and returned values of the remote methods must be
serializable.
3.2.5RegisteringRemoteObjects
A server makes remote objects visible to the clients by registering these objects with a
naming service. The process of registering an object with the RMI registry is called binding.
The RMI registry is nothing but a naming service that knows where to find the server’s
objects,anditwillenableclientstolookupanobjectinthenetworkbyname.Whilethe
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_III_RMI_E_CONTENT
Twomethodsinthejava.rmi.Namingclasscanbindanobjecttotheregistry.
Therebind()methodreplacesanypreexistingregistryentrywiththenewone. The
unbind() method removes an object from the registry.
The registry must be up and running by the time that bind the objects. To start the registry,
open a command window and type the following:
c:\>rmiregistry
Forexample,tostarttheregistryonport6000usethefollowingcommand:
c:\>rmiregistry 6000
ExampleProgram:
1) Createtheremoteinterface
For creating the remote interface, we need to extend the Remote interface and declare the
RemoteException with all the methods of the remote interface.
Here, weare creating a remote interface that extends the Remoteinterface. There is onlyone
method named add() and it declares RemoteException.
importjava.rmi.*;
publicinterfaceAdderextendsRemote
{
publicintadd(intx,inty)throwsRemoteException;
}
2) Providetheimplementationoftheremoteinterface
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_III_RMI_E_CONTENT
import java.rmi.*;
importjava.rmi.server.*;
publicclassAdderRemoteextendsUnicastRemoteObjectimplementsAdder
{
AdderRemote()throwsRemoteException
{
super();
}
publicintadd(intx,int y)
{
returnx+y;
}
}
3) Createthestubandskeletonobjectsusingthermictool
rmicAdderRemote
4) Starttheregistryservicebythermiregistrytool
Inthisexample,weareusingtheportnumber5000.
rmiregistry 5000
5) Createandruntheserverapplication
Inthisexample,wearebindingtheremoteobjectbythenameAdd. import
java.rmi.*;
importjava.rmi.registry.*;
publicclassMyServer
{
publicstaticvoidmain(Stringargs[])
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_III_RMI_E_CONTENT
{
try
{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/Add",stub);
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
6) Createandruntheclientapplication
At the client we are getting the stub object by the lookup() method of the Naming class and
invoking the method on this object.
In this example, we are running the server and client applications, in the same machine
sowe are using localhost.
import java.rmi.*;
publicclassMyClient{
publicstaticvoidmain(Stringargs[]){
try{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/Add");
System.out.println(stub.add(34,4));
}catch(Exceptione){}
}
}
Output
Figure 2.1 shows the screen shot of invoking the RMI compiler and starting the RMI registry
at port no 5000.
Figure2.1InvokingRMIRegistry
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_III_RMI_E_CONTENT
Figure2.2showsthescreenshotofrunningtheserverapplication.
Figure2.2RunningServerApplication
Figure2.3showsthescreenshotofexecutingtheclientapplication.
Figure2.3ExecutingClientApplication
WritingRMIclients
AremoteclasscanstartitsownregistrythatsupportsthenamingservicesfortheRMI clients.
TheregistryAPIisdefinedbythejava.rmi.registry.RegistryInterface.
TheRMIregistryrunsbydefaultonport1099,unlessanotherportnumberisspecified.
Whentheclientwantstoinvokemethodsontheremoteobjectitobtainsareferenceto
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_III_RMI_E_CONTENT
thatobjectbylookingupthename.Thelookupreturnstotheclientastuboftheremote object.
Themethodtakestheobject’sURLasanargumentinthisformat:
rmi://<hostname>[:<name_service_port>]/<service_name>
Thesecomponentsaredescribedasfollows:
✦hostname isthe name ofthe computer on the local area network (LAN)or aDNSname on
the Internet.
✦service_nameisthenameoftheremoteobjectthatshouldhavebeenboundtothe registry.
PushingDatafromtheRMIServer
The RMI client(s) has to register itself with the server, and it also has to implement an
interface that contains the code refreshing the screen. Periodically the RMI server will call
the method that refreshes the screen on each registered client. In other words, instead of
the client pulling the data from the server, the server is pushing the data to the client.
RMIoverInter-ORBProtocol(IIOP)
The RMI technology internally uses the Java Remote Method Protocol (JRMP), which can be
used for communications between Java programs only. On the other hand, CORBA
technology can be used in distributed applications whose components are written in
different languages, but CORBA uses the Internet Inter-ORB Protocol (IIOP).
Backin 1997, IBMand Sun Microsystems created RMI-IIOP protocol, which allows write Java
client programs that are communicating with non-Java objects.
RMI-IIOP supports both JRMP and IIOP protocols. CORBA uses the Interface Definition
Language (IDL) to define objects, and the RMI compiler supports mapping between Java and
IDL objects.
Some other differences in the development of RMI-IIOP applications (as opposed to CORBA
applications) are listed here:
Theserver-implementationclassmustextendthejavax.rmi.PortableRemoteObjectclass.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_III_RMI_E_CONTENT
JSDKincludesthetnameserv.exeprogram,whichisusedasanamingservice. The
Objectobj=ctx.lookup(“FlightService”);
FlightServer fs = (FlightServer)
PortableRemoteObject.narrow(obj,FlightServer.class);
rmicmustberun oneextratimewiththe–idloptiontogenerateIDLforCORBAclients.
While RMI is a lot simpler than CORBA, the latter gives you more flexibility in creating
distributed applications. As a matter of fact, you may not even have a choice if anapplication
written in CORBA is already in production and you need to write a Java application that
communicates with it.
ReferenceBooks:
1. JEE1.4Bible,J.McGovern,R.Adatia,Y.Fain,Wiley-dreamtechPublication,2003
2. Java2CompleteReference,H.Schildt,TMH,5thEdition,2002.
WebResources:
1. https://www.javatpoint.com/RMI
2. https://www.tutorialspoint.com/java_rmi/java_rmi_introduction.htm
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
ADVANCEJAVA PROGRAMMING
EJB– Overview
EJBstandsforEnterpriseJavaBeans.EJBisanessentialpartofaJ2EEplatform.J2EEplatformhas
componentbasedarchitecturetoprovidemulti-tiered,distributedandhighlytransactionalfeaturesto
enterprise level applications.
EJB provides an architecture to develop and deploy component based enterprise applications
consideringrobustness,highscalability,andhighperformance.AnEJBapplicationcanbedeployed on any
of the application server compliant with the J2EE 1.3 standard specification.
TypesofEJB
EJBisprimarilydividedintothreecategories;followingtableliststheirnameswithbriefdescriptions
S.No Type&Description
1 SessionBean
Sessionbeanstoresdataofaparticularuserforasinglesession.Itcan bestatefulorstateless.
Itislessresourceintensiveascomparedtoentitybean.Sessionbean gets destroyed as soon as user
session terminates.
2 EntityBean
Entity beansrepresent persistent data storage. User data can be saved to database via entity
beans and later on can be retrieved from the database in the entity bean.
3
MessageDrivenBean
MessagedrivenbeansareusedincontextofJMS(JavaMessagingService).MessageDriven Beans
can consumes JMS messages from external entities and act accordingly.
Benefits
FollowingaretheimportantbenefitsofEJB–
• Simplifieddevelopmentoflarge-scaleenterpriselevelapplication.
• Application Server/EJB container provides most of the system level services like
transactionhandling,logging,loadbalancing,persistencemechanism,exceptionhandling, and
so on. Developer has to focus only on business logic of the application.
• EJBcontainermanageslifecycleofEJBinstances,thusdeveloperneedsnottoworry about
when to create/delete EJB objects.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
EJB-EnvironmentSetup
EJBisaframeworkforJava,sotheveryfirstrequirementistohavea JavaDevelopmentKit(JDK) installed in the
machine.
SystemRequirement
JDK 1.5orabove.
Memory nominimumrequirement.
DiskSpace nominimumrequirement.
OperatingSystem nominimumrequirement.
Step1-VerifyJavaInstallationinSystem.
Nowopenconsoleandexecutethefollowingjavacommand.
OS Task Command
Windows OpenCommandConsole c:\>java-version
Linux OpenCommandTerminal $java –version
Mac OpenTerminal machine:~joseph$java-version
Theoutputforalltheoperatingsystemswillbeasfollows
OS Output
javaversion"1.6.0_21"
Windows Java(TM)SERuntimeEnvironment(build1.6.0_21-b11)
JavaHotSpot(TM)64-BitServerVM(build23.21-b01,mixedmode)
javaversion"1.6.0_21"
Linux Java(TM)SERuntimeEnvironment(build1.6.0_21-b11)
JavaHotSpot(TM)64-BitServerVM(build23.21-b01,mixedmode)
javaversion"1.6.0_21"
Mac Java(TM)SERuntimeEnvironment(build1.6.0_21-b11)
JavaHotSpot(TM)64-BitServerVM(build23.21-b01,mixedmode)
Step2–SetJAVAEnvironment
SettheJAVA_HOME environmentvariabletopointthebasedirectorylocationwhereJavais installed on
system. For example,
OS Output
SettheenvironmentvariableJAVA_HOMEtoC:\Program
Windows
Files\Java\jdk1.6.0_21
Linux exportJAVA_HOME=/usr/local/java-current
Mac exportJAVA_HOME=/Library/Java/Home
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
AppendJavacompilerlocationtoSystemPath.
OS Output
Appendthestring;C:\ProgramFiles\Java\jdk1.6.0_21\bintotheendof the
Windows
systemvariable,Path.
Linux exportPATH=$PATH:$JAVA_HOME/bin/
Mac notrequired
VerifyJavaInstallationusingjava-versioncommandexplainedabove.
Step3–DownloadandInstallNetBeansIDE
DownloadthelatestversionofNetBeansIDEfromnetbeans.org
OS Installername
Windows Netbeans7.3
Linux Netbeans7.3
Mac Netbeans7.3
Step4–SetupJBossApplicationServer
DownloadthelatestversionofJBossServerfrom www.jboss.org.Downloadthearchiveasperthe platform.
Extract the Jboss to any location on the machine.
OS File name
Windows jboss-5.1.0.GA-jdk6.zip
Linux jboss-5.1.0.GA-src.tar.gz
Mac jboss-5.1.0.GA-src.tar.gz
Step5-ConfigureJEEPluginstoNetbeans
Open Plugin window using Tools > Plugins. Open "Available Plugin" tab and select "Java EE Base"
and"EJBandEAR"under"JavaWebandEE"category.Clickinstallbutton.Netbeanswilldownload and
install the respective plugins. Verify plugins installation using "Installed"
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
Step6-ConfigureJBossServerinNetbeans
GotoServicestabandrightclickonserverstoaddanew server.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
Onceeverythingisconfigured,thefollowingscreenisvisible.
Step7-InstallDatabaseServer(PostGreSql)
DownloadlatestversionofPostGreSqldatabaseserverfromwww.postgresql.org.
OS Installername OS
Windows PostGreSql9.2 Windows
Linux PostGreSql9.2 Linux
Mac PostGreSql9.2 Mac
CreateProject
InNetBeansIDE,selectFile>NewProject>.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
SelectprojecttypeundercategoryJavaEE,ProjecttypeasEJBModule.ClickNext>button.
Enterprojectnameandlocation.ClickNext>button.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
SelectServerasJBossApplicationServer.ClickFinishbutton
CreateApplication
CreateProject
InNetBeansIDE,selectFile>NewProject>.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
SelectprojecttypeundercategoryJavaEE,ProjecttypeasEJBModule.ClickNext>button.
Enterprojectnameandlocation.ClickNext>button.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
CreateaSampleEJB
TocreateasimpleEJB,wewilluseNetBeans"New"wizard.Intheexamplegivenbelow,Wewill create a
stateless EJB class named librarySessionBean under EjbComponent project.
Entersessionbeannameandpackagename.Click Finishbutton.ThefollowingEJBclassescreated by
NetBeans is visible.
• LibrarySessionBean−statelesssessionbean
• LibrarySessionBeanLocal−localinterfaceforsessionbean
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
ThelocalinterfacecanbechangedtoremoteinterfacetoaccessEJBinaconsolebasedapplication. Remote/Local
interface is used to expose business methods that an EJB has to implement.
LibrarySessionBeanLocalisrenamedtoLibrarySessionBeanRemoteandLibrarySessionBean implements
LibrarySessionBeanRemote interface.
LibrarySessionBeanRemote
packagecom.tutorialspoint.stateless;
import java.util.List;
importjavax.ejb.Remote;
@Remote
publicinterfaceLibrarySessionBeanRemote
{
voidaddBook(StringbookName);
List getBooks();
}
LibrarySessionBean
packagecom.tutorialspoint.stateless;
import java.util.ArrayList;
import java.util.List;
importjavax.ejb.Stateless;
@Stateless
publicclassLibrarySessionBeanimplementsLibrarySessionBeanRemote
{
List<String> bookShelf;
publicLibrarySessionBean()
{
bookShelf=newArrayList<String>();
}
publicvoidaddBook(StringbookName)
{
bookShelf.add(bookName);
}
publicList<String>getBooks()
{
returnbookShelf;
}
}
BuildtheProject
• SelectEjbComponentprojectinProjectExplorerwindow.
• Rightclickonittoopencontext menu.
• Selectcleanandbuild.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
StarttheApplicationServer
• SelectJBossapplicationserverunderServersinServiceswindow.
• Rightclickonittoopencontext menu.
• Selectstart.
ThefollowingistheoutputinNetBeans,outputunderJBossApplicationServer. Calling
C:\jboss-5.1.0.GA\bin\run.conf.bat
========================================================================
JBoss Bootstrap Environment
JBOSS_HOME:C:\jboss-5.1.0.GA
JAVA: C:\Program Files
(x86)\Java\jdk1.6.0_21\bin\javaJAVA_OPTS:-
Dprogram.name=run.bat-Xms128m-Xmx512m-server CLASSPATH:
C:\jboss-5.1.0.GA\bin\run.jar
========================================================================
16:25:50,062INFO[ServerImpl]StartingJBoss(Microcontainer)... 16:25:50,062
INFO[ServerImpl] Release ID: JBoss
[TheOracle]5.1.0.GA(build:SVNTag=JBoss_5_1_0_GAdate=200905221634)
...
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
16:26:40,420INFO[TomcatDeployment]deploy,ctxPath=/admin-console
16:26:40,485INFO[config]InitializingMojarra(1.2_12-b01-FCS)forcontext'/admin-console' 16:26:42,362
INFO[TomcatDeployment] deploy, ctxPath=/
16:26:42,406INFO[TomcatDeployment]deploy,ctxPath=/jmx-console
16:26:42,471INFO[Http11Protocol]StartingCoyoteHTTP/1.1onhttp-127.0.0.1-8080
16:26:42,487 INFO[AjpProtocol] Starting Coyote AJP/1.3 on ajp-127.0.0.1-8009
16:26:42,493 INFO[ServerImpl] JBoss (Microcontainer)
[5.1.0.GA(build:SVNTag=JBoss_5_1_0_GAdate=200905221634)]Startedin52s:427ms
DeploytheProject
• SelectEjbComponentprojectinProjectExplorerwindow.
• Rightclickonittoopencontext menu.
• SelectDeploy.
ThefollowingistheoutputinNetBeansconsoleoutput.
ant-fC:\\EJB\\EjbComponent-DforceRedeploy=true-Ddirectory.deployment.supported=false-
Dnb.wait.for.caches=truerun
init:
deps-jar:
compile:
library-inclusion-in-archive:
Buildingjar:C:\EJB\EjbComponent\dist\EjbComponent.jar
dist-directory-deploy:
pre-run-deploy:
JBossApplicationServerLogOutput
16:30:00,963INFO[DeployHandler]Beginstart,[EjbComponent.jar]
...
16:30:01,233INFO[Ejb3DependenciesDeployer]Encountereddeployment
AbstractVFSDeploymentContext@12038795{vfszip:/C:/jboss-
5.1.0.GA/server/default/deploy/EjbComponent.jar/}
...
16:30:01,281 INFO[JBossASKernel] jndi:LibrarySessionBean/remote-
com.tutorialspoint.stateless.LibrarySessionBeanRemote
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
16:30:01,281INFO[JBossASKernel]
Class:com.tutorialspoint.stateless.LibrarySessionBeanRemote
16:30:01,281 INFO[JBossASKernel] jndi:LibrarySessionBean/remote
16:30:01,281INFO[JBossASKernel]Addedbean(jboss.j2ee:jar=EjbComponent.jar,name=
LibrarySessionBean,service=EJB3) to KernelDeployment of: EjbComponent.jar
16:30:01,282 INFO[JBossASKernel] installing bean:
jboss.j2ee:jar=EjbComponent.jar,name=BookMessageHandler,service=EJB3
16:30:01,282INFO[JBossASKernel]withdependencies:
16:30:01,282INFO[JBossASKernel]anddemands:
16:30:01,282INFO[JBossASKernel] jboss.ejb:service=EJBTimerService
...
16:30:01,283 INFO[EJB3EndpointDeployer] Deploy
AbstractBeanMetaData@5497cb{name=jboss.j2ee:jar=EjbComponent.jar,
name=LibrarySessionBean, service=EJB3_endpoint
bean=org.jboss.ejb3.endpoint.deployers.impl.EndpointImplproperties=[container]constructor=null
autowireCandidate=true}
...
16:30:01,394 INFO[SessionSpecContainer] Starting
jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3
16:30:01,395 INFO[EJBContainer] STARTED EJB:
com.tutorialspoint.stateless.LibrarySessionBeanejbName:LibrarySessionBean
16:30:01,401INFO[JndiSessionRegistrarBase]BindingthefollowingEntriesinGlobalJNDI:
LibrarySessionBean/remote - EJB3.x Default Remote Business Interface
LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote-EJB3.x
RemoteBusinessInterface
16:30:02,723 INFO[SessionSpecContainer] Starting
jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3
16:30:02,723 INFO[EJBContainer] STARTED EJB:
com.tutorialspoint.stateless.LibrarySessionBeanejbName:LibrarySessionBean
16:30:02,731INFO[JndiSessionRegistrarBase]BindingthefollowingEntriesinGlobalJNDI:
LibrarySessionBean/remote - EJB3.x Default Remote Business Interface
LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote-EJB3.x
RemoteBusinessInterface
CreateClienttoAccess EJB
• InNetBeansIDE,selectFile>NewProject>.
• SelectprojecttypeundercategoryJava,ProjecttypeasJavaApplication.ClickNext>button
• Enterprojectnameandlocation.ClickFinish>button.Wehavechosennameas
EjbTester.
• RightclickonprojectnameinProjectexplorerwindow.Selectproperties.
• AddEJBcomponentprojectcreatedearlierunderlibrariesusing AddProjectbutton in
compile tab.
• Addjbosslibrariesusing Addjar/folder buttonincompiletab.Jbosslibrariescanbe
located at <jboss installation folder>> client folder.
• Createjndi.propertiesunderprojectsayEjbTester.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
jndi.properties
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost
Createpackagecom.tutorialspoint.testandEJBTester.javaclassunderit.
EJBTester.java
packagecom.tutorialspoint.test;
import com.tutorialspoint.stateless.LibrarySessionBeanRemote;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
importjava.util.Properties;
import javax.naming.InitialContext;
importjavax.naming.NamingException;
public class EJBTester {
BufferedReaderbrConsoleReader=null;
Properties props;
InitialContextctx;
{
props=newProperties();
try {
props.load(newFileInputStream("jndi.properties"));
}catch(IOExceptionex){
ex.printStackTrace();
}
try{
ctx=newInitialContext(props);
}catch(NamingExceptionex){
ex.printStackTrace();
}
brConsoleReader=
newBufferedReader(newInputStreamReader(System.in));
}
public static void main(String[] args) {
EJBTesterejbTester=newEJBTester();
ejbTester.testStatelessEjb();
}
private void showGUI() {
System.out.println("**********************");
System.out.println("Welcome to Book Store");
System.out.println("**********************");
System.out.print("Options\n1.AddBook\n2.Exit\nEnterChoice:");
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
}
privatevoidtestStatelessEjb(){
try {
int choice = 1;
LibrarySessionBeanRemotelibraryBean=
(LibrarySessionBeanRemote)ctx.lookup("LibrarySessionBean/remote");
while (choice != 2) {
StringbookName;
showGUI();
StringstrChoice=brConsoleReader.readLine();
choice = Integer.parseInt(strChoice);
if (choice == 1) {
System.out.print("Enterbookname:");
bookName=brConsoleReader.readLine();
libraryBean.addBook(bookName);
}elseif(choice==2){
break;
}
}
List<String> booksList = libraryBean.getBooks();
System.out.println("Book(s)enteredsofar:"+booksList.size()); for
(int i = 0; i < booksList.size(); ++i) {
System.out.println((i+1)+"."+booksList.get(i));
}
LibrarySessionBeanRemote libraryBean1 =
(LibrarySessionBeanRemote)ctx.lookup("LibrarySessionBean/remote");
List<String> booksList1 = libraryBean1.getBooks();
System.out.println(
"***Usingsecondlookuptogetlibrarystatelessobject***");
System.out.println(
"Book(s)enteredsofar:"+booksList1.size()); for
(int i = 0; i < booksList1.size(); ++i) {
System.out.println((i+1)+"."+booksList1.get(i));
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}finally{ try
{
if(brConsoleReader!=null){
brConsoleReader.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
RunClienttoAccessEJB
LocateEJBTester.javainprojectexplorer.RightclickonEJBTesterclassandselect runfile. Verify
the following output in Netbeans console.
run:
**********************
Welcome to Book Store
**********************
Options
1. AddBook
2. Exit
EnterChoice:1
Enterbookname:LearnJava
**********************
Welcome to Book Store
**********************
Options
1. AddBook
2. Exit
EnterChoice:2
Book(s)enteredsofar:1
1. LearnJava
***Usingsecondlookuptogetlibrarystatelessobject*** Book(s)
entered so far: 0
BUILDSUCCESSFUL(totaltime:13seconds)
StatelessBean
A stateless session bean is a type of enterprise bean, which is normally used to performindependent
operations. A stateless session bean as per its name does not have any associated client state, but it
maypreserveitsinstancestate.EJBContainernormallycreatesapooloffewstatelessbean'sobjects and use
these objects to process client's request. Because of pool, instance variable values are not guaranteed
to be same across lookups/method calls.
StepstoCreateaStatelessEJB
FollowingarethestepsrequiredtocreateastatelessEJB–
• Createaremote/localinterfaceexposingthebusinessmethods.
• ThisinterfacewillbeusedbytheEJBclientapplication.
• Use@Localannotation,ifEJBclientisinsameenvironmentwhereEJBsessionbeanis to be
deployed.
• Use@Remoteannotation,ifEJBclientisindifferentenvironmentwhereEJBsession bean
is to be deployed.
• Createastatelesssessionbean,implementingtheaboveinterface.
• Use @Stateless annotation to signify it a stateless bean. EJB Container automatically
createstherelevantconfigurationsorinterfacesrequiredbyreadingthisannotationduring
deployment.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
RemoteInterface
importjavax.ejb.Remote;
@Remote
publicinterfaceLibrarySessionBeanRemote {
//addbusinessmethoddeclarations
}
StatelessEJB
@Stateless
publicclassLibrarySessionBeanimplementsLibrarySessionBeanRemote{
//implementbusinessmethod
}
StatefulBean
A stateful session bean is a type of enterprise bean, which preserve the conversational state with
client.Astatefulsessionbeanasperitsnamekeepsassociatedclientstateinitsinstancevariables. EJB
Container creates a separate stateful session bean to process client's each request. As soon as request
scope is over, statelful session bean is destroyed.
StepstoCreateStatefulEJB
FollowingarethestepsrequiredtocreateastatefulEJB–
• Createaremote/localinterfaceexposingthebusinessmethods.
• ThisinterfacewillbeusedbytheEJBclientapplication.
• Use@LocalannotationifEJBclientisinsameenvironmentwhereEJBsessionbeanneed to be
deployed.
• Use@RemoteannotationifEJBclientisindifferentenvironmentwhereEJBsession bean
need to be deployed.
• Createastatefulsessionbean,implementingtheaboveinterface.
• Use@Statefulannotationtosignifyitastatefulbean.EJBContainerautomaticallycreates the
relevant configurations or interfaces required by reading this annotation during
deployment.
RemoteInterface
importjavax.ejb.Remote;
@Remote
publicinterfaceLibraryStatefulSessionBeanRemote{
//addbusinessmethoddeclarations
}
StatefulEJB
@Stateful
publicclassLibraryStatefulSessionBeanimplementsLibraryStatefulSessionBeanRemote{
//implementbusinessmethod
}
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
MessageDrivenBeans
A message driven bean is a type of enterprise bean, which is invoked by EJB container when it
receivesamessagefromqueueortopic.Messagedrivenbeanisastatelessbeanandisusedtodotask
asynchronously.
Todemonstrateuseofmessagedrivenbean,dothefollowingtasks–
• Step1−Createtableindatabase
• Step2−CreateEntityclasscorrespondingto table
• Step3−CreateDataSourceandPersistenceUnit
• Step4−CreateastatelessEJBhavingEntityManagerinstance
• Step5−Updatestatelessejb.Add methodstoaddrecordsandgetrecordsfromdatabase via
entity manager
• Step6−CreateaQueuenamedBookQueueinJBossdefaultapplicationdirectory.
• Step7−Aconsolebasedapplicationclientwillsendmessagetothisqueue.
• Step8−CreateaMessagedrivenbean,whichwillusethestatelessbeantopersistthe client
data.
• Step9−EJBContainerofjbosswillcalltheabove messagedrivenbeanandpassitthe message
that client will be sending to.
CreateQueue
Createafilenamedjbossmq-destinations-service.xmlifnotexistsin <JBossInstallationFolder>> server >
default > deploy folder.
HerecreatingaqueuenamedBookQueue–
jbossmq-destinations-service.xml
<mbean
code="org.jboss.mq.server.jmx.Queue"name="jboss.mq.destination:service=Queue,name=BookQueue">
<depends optional-attribute-name="DestinationManager">
jboss.mq:service=DestinationManager
</depends>
</mbean>
WhentheJbossisstarted,thereisasimilarentryinjbosslog.
...
10:37:06,167INFO[QueueService]Queue[/queue/BookQueue]started,fullSize=200000, pageSize=2000,
downCacheSize=2000
...
CreateMessageDrivenBean
@MessageDriven(
name="BookMessageHandler",
activationConfig = {
@ActivationConfigProperty(propertyName="destinationType", propertyValue
= "javax.jms.Queue"),
@ActivationConfigProperty(propertyName="destination",
propertyValue ="/queue/BookQueue")
}
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
)
publicclassLibraryMessageBeanimplementsMessageListener
{
@Resource
privateMessageDrivenContextmdctx;
@EJB
LibraryPersistentBeanRemotelibraryBean;
publicLibraryMessageBean()
{
}
publicvoidonMessage(Messagemessage)
{
}
}
• LibraryMessageBeanisannotatedwith@MessageDrivenannotationtomarkitasmessage
driven bean.
• ItspropertiesaredefinedasdestinationType-Queueanddestination-/queue/BookQueue.
• ItimplementsMessageListenerinterface,whichexposesonMessagemethod.
• IthasMessgeDrivenContextasaresource.
• LibraryPersistentBeanRemotestatelessbeanisinjectedinthisbeanforpersistence
purpose.
BuildtheEjbComponentprojectanddeployitonJBoss.AfterbuildinganddeployingtheEJB module, a
client is needed to send a message to jboss queue.
Persistence
EJB3.0,entitybeanusedinEJB2.0islargelyreplacedbypersistencemechanism.Now entitybeanis a simple
POJO having mapping with table.
FollowingarethekeyactorsinpersistenceAPI–
• Entity−Apersistentobjectrepresentingthedata-storerecord.Itisgoodtobe
serializable.
• EntityManager−Persistenceinterfacetododataoperationslikeadd/delete/update/find on
persistent object(entity). It also helps to execute queries using Query interface.
• Persistenceunit(persistence.xml)−Persistenceunitdescribesthepropertiesof
persistence mechanism.
• DataSource(*ds.xml)−DataSourcedescribesthedata-storerelatedpropertieslike
connection url. user-name,password etc.
TodemonstrateEJBpersistencemechanism,dothefollowingtasks–
• Step1−Createtablein database.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
• Step2−CreateEntityclasscorrespondingto table.
• Step3−CreateDataSourceandPersistence Unit.
• Step4−CreateastatelessEJBhavingEntityManagerinstance.
• Step5−UpdatestatelessEJB.Addmethodstoaddrecordsandgetrecordsfrom
database via entity manager.
• Step6−AconsolebasedapplicationclientwillaccessthestatelessEJBtopersistdata in
database.
CreateTable
Createatablebooksindefaultdatabasepostgres.
CREATETABLEbooks(idintegerPRIMARYKEY,namevarchar(50));
CreateEntityclass
//markitentityusingEntityannotation
//maptablenameusingTableannotation
@Entity
@Table(name="books")
publicclassBookimplementsSerializable
{
private int id;
privateStringname;
public Book()
{
}
//markidasprimarykeywithautogeneratedvalue
//mapdatabasecolumnidwithidfield @Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
publicintgetId()
{
returnid;
}
...
}
CreateDataSourceandPersistenceUnit
DataSource (jboss-ds.xml)
<?xmlversion="1.0"encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>PostgresDS</jndi-name>
<connection-url>jdbc:postgresql://localhost:5432/postgres</connection-url>
<driver-class>org.postgresql.driver</driver-class>
<user-name>sa</user-name>
<password>sa</password>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<idle-timeout-minutes>5</idle-timeout-minutes>
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
</local-tx-datasource>
</datasources>
PersistenceUnit(persistence.xml)
<persistenceversion="1.0"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/persistencehttp://java.sun.com/xml/ns/per
sistence/persistence_1_0.xsd">
<persistence-unitname="EjbComponentPU"transaction-type="JTA">
<jta-data-source>java:/PostgresDS</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
<persistence-unitname="EjbComponentPU2"transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/PostgresDS</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<propertyname="hibernate.hbm2ddl.auto"value="update"/>
</properties>
</persistence-unit>
</persistence>
CreateStatelessEJBHavingEntityManagerInstance
@Stateless
publicclassLibraryPersistentBeanimplementsLibraryPersistentBeanRemote{
publicvoidaddBook(Bookbook){
entityManager.persist(book);
}
publicList<Book>getBooks(){
returnentityManager.createQuery("FromBooks").getResultList();
}
...
}
AfterbuildingtheEJBmodule,aclientisneededtoaccessthestatelessbean.
Annotations
Annotations were introduced in Java 5.0. The purpose of having annotations is to attach additional
informationintheclassorameta-dataofaclasswithinitssourcecode.InEJB3.0,annotationsare
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
usedtodescribeconfigurationmeta-datainEJBclasses.Bythisway,EJB3.0eliminatestheneedto describe
configuration data in configuration XML files.
EJBcontainerusescompilertooltogeneraterequiredartifactslikeinterfaces,deploymentdescriptors by
reading those annotations. Following is the list of commonly used annotations.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
ofthereferencedbean.
• beanName − Used to provide name of the
referenced bean.
• mappedName− Used to specify the JNDI name of
the referenced bean.
• description−Usedtoprovidedescriptionofthe
referenced bean.
5 javax.ejb.Local Used to specify Local interface(s) of a session bean. This
local interface states the business methods of the session
bean (which can be stateless or stateful).
This interface is used to expose the business methods to
local clients, which are running in the same
deployment/application as EJB.
Attributes
• value−Usedto specify thelist oflocalinterfaces as an
array of interfaces.
6 javax.ejb.Remote UsedtospecifyRemoteinterface(s)ofasessionbean.This
remote interface states the business methods of the session
bean (which can be stateless or stateful).
This interface is used to expose the business methods to
remote clients, which are running in different
deployment/application as EJB.
Attributes
• value− Used to specify the list of remote interfaces
as an array of interfaces.
7 javax.ejb.Activation Used to specify properties required for a message driven
ConfigProperty bean. For example, end point, destination, messageselector
etc.
This annotation is passed as a parameter to
activationConfig attribute of
javax.ejb.MessageDrivenBean annotation.
Attributes
• propertyName−nameoftheproperty.
• propertyValue−valueoftheproperty.
8 javax.ejb.PostActiva Used to specify callback method of EJB lifecycle. This
te method will be called when EJB container just
activated/reactivated the bean instance.
This interface is used to expose the business methods to
local clients, which are running in same
deployment/application as EJB.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
Callback
Callback is a mechanism by which the life cycle of an enterprise bean can be intercepted. EJB 3.0
specificationhasspecifiedcallbacksforwhichcallbackhandlermethodsarecreated.EJBContainer calls
these callbacks. We can define callback methods in the EJB class itself or in a separate class.
EJB 3.0 has provided many annotations for callbacks.
Followingisthelistofcallbackannotationsforstatelessbean–
Annotation Description
@PostConstruct Invokedwhenabeaniscreated for
thefirsttime.
Invokedwhenabeanis removed
@PreDestroy
fromthebeanpoolorisdestroyed.
Followingisthelistofcallbackannotationsforstatefulbean–
Annotation Description
@PostConstruct Invokedwhenabeaniscreatedforthefirsttime.
Invokedwhenabeanisremovedfromthebeanpoolor is
@PreDestroy
destroyed.
@PostActivate Invokedwhenabeanisloadedtobeused.
Followingisthelistofcallbackannotationsformessagedrivenbean–
Annotation Description
@PostConstruct Invokedwhenabeaniscreatedforthefirsttime.
Invokedwhenabeanisremovedfromthebeanpoolor is
@PreDestroy
destroyed.
Followingisthelistofcallbackannotationsforentitybean–
Annotation Description
@PrePersist Invokedwhenanentityiscreatedindatabase.
@PostPersist Invokedafteranentityiscreatedindatabase.
@PreRemove Invokedwhenanentityisdeletedfromthedatabase.
@PostRemove Invokedafteranentityisdeletedfromthe database.
@PreUpdate Invokedbeforeanentityistobeupdatedinthedatabase.
Invokedwhenarecordisfetchedfromdatabaseandloaded
@PostLoad
intotheentity.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
TimerService
TimerServiceisamechanismbywhichscheduledapplicationcanbebuild.For example,salaryslip
generation on the 1st of every month. EJB 3.0 specification has specified @Timeout annotation,
which helps in programming the EJB service in a stateless or message driven bean. EJB Container
calls the method, which is annotated by @Timeout.
StepstoCreateTimer
InjectSessionContextinbeanusing@Resourceannotation–
@Stateless
publicclassTimerSessionBean
{
@Resource
privateSessionContextcontext;
...
}
publicvoidcreateTimer(longduration)
{
context.getTimerService().createTimer(duration,"HelloWorld!");
}
StepstoUseTimer
Use@Timeoutannotationtoamethod.ReturntypeshouldbevoidandpassaparameteroftypeTimer. The timer
has to be cancelled after first execution otherwise it will keep running after fix intervals.
@Timeout
public void timeOutHandler(Timer timer) {
System.out.println("timeoutHandler:"+timer.getInfo());
timer.cancel();
}
JNDIBindings
JNDI stands for Java Naming and Directory Interface. It is a set of API and service interfaces. Java
basedapplicationsuseJNDIfornaminganddirectoryservices.IncontextofEJB,thereare twoterms.
• Binding−ThisreferstoassigninganametoanEJBobject,whichcanbeusedlater.
• Lookup−ThisreferstolookingupandgettinganobjectofEJB. In
Jboss, session beans are bound in JNDI in the following format by default.
• local−EJB-name/local
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
• remote−EJB-name/remote
Incase,EJBarebundledwith<application-name>.earfile,thendefaultformatisasfollowing–
• local−application-name/ejb-name/local
• remote−application-name/ejb-name/remote
CustomizedBinding
FollowingannotationscanbeusedtocustomizethedefaultJNDIbindings–
• local−org.jboss.ejb3.LocalBinding
• remote−org.jboss.ejb3.RemoteBindings
QueryLanguage
EJB Query Language is quite handy to write custom queries without worrying about underlying
databasedetails.ItisquitesimilartoHQL,hibernatequerylanguageandisoftenreferredbythename EJBQL.
TodemonstrateEJBQLinEJB,wearegoingtodothefollowingtasks–
• Step1−Createtablein database.
• Step2−CreateastatelessEJBhavingbusinessme.
• Step3−UpdatestatelessEJB.Addmethodstoaddrecordsandgetrecordsfromdatabase via
entity manager.
• Step4−AconsolebasedapplicationclientwillaccessthestatelessEJBtopersistdatain database.
CreateTable
Createatablebooksindefaultdatabasepostgres.
CREATETABLEbooks( id integerPRIMARYKEY,namevarchar(50));
CreateaModelClass
publicclassBookimplementsSerializable
{
private int id;
privateStringname;
public Book()
{
}
publicintgetId()
{
returnid;
}
...
}
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
CreateStatelessEJB
@Stateless
publicclassLibraryPersistentBeanimplementsLibraryPersistentBeanRemote
{
publicvoidaddBook(Bookbook){
//persistbookusingentitymanager
}
publicList<Book>getBooks(){
//getbooksusingentitymanager
}
...
}
AfterbuildingtheEJBmodule,aclientisneededtoaccessthestatelessbean.
AccessDatabase
InEJB3.0,persistencemechanismisusedtoaccessthedatabaseinwhichthecontainermanagesthe database
related operations. Developers can access database using JDBC API call directly in EJB business
methods.
TodemonstratedatabaseaccessinEJB,weneedtoperformthefollowingtasks–
• Step1−Createatableinthedatabase.
• Step2−CreateastatelessEJBhavingbusinessme.
• Step3−UpdatestatelessEJB.Addmethodstoaddrecordsandgetrecordsfromdatabase via
entity manager.
• Step4−AconsolebasedapplicationclientwillaccessthestatelessEJBtopersistdatain database.
CreateTable
Createatablebooksindefaultdatabasepostgres.
CREATETABLEbooks(idintegerPRIMARYKEY,namevarchar(50));
CreateaModelClass
publicclassBookimplementsSerializable
{
private int id;
privateStringname;
public Book() {
}
publicintgetId(){
return id;
}
...
}
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
CreateStatelessEJB
@Stateless
publicclassLibraryPersistentBeanimplementsLibraryPersistentBeanRemote
{
publicvoidaddBook(Bookbook)
{
//persistbookusingjdbccalls
}
publicList<Book>getBooks()
{
//getbooksusingjdbc calls
}
...
}
AfterbuildingtheEJBmodule,aclientisneededtoaccessthestatelessbean.
ExceptionHandling
EJBsarea partofenterpriseapplications whicharenormallybasedondistributedenvironments.So,
apartfromthenormalexceptionsthatcanoccur,therecanbeexceptionslikecommunicationfailure, security
permissions, server down, etc.
EJBcontainerconsidersexceptionsintwoways–
• ApplicationException−Ifbusinessruleisviolatedorexceptionoccurswhileexecuting the
business logic.
• SystemException−Anyexception,whichisnotcausedbybusinesslogicorbusiness
code.RuntimeException,RemoteExceptionareSystemException.Forexample,error
during EJB lookup. RuntimeException, RemoteException are SystemException.
HowDoesEJBContainerHandleExceptions?
WhenApplication Exceptionoccurs, EJB container intercepts the exception, but returns the same to
the client as it is. It does not roll back the transaction unless it is specified in the code by
EJBContext.setRollBackOnly() method. EJB Container does not wrap the exception in case of
Application Exception.
WhenSystemExceptionoccurs, EJBcontainerinterceptsthe exception,rollbacks thetransactionand start
the clean up tasks. It wraps the exception into RemoteException and throws it to the client.
HandlingApplicationException
Application exceptions are generally thrown in Session EJB methods as these are the methods
responsible to execute business logic. Application exception should be declared in throws clause of
business method and should be thrown in case business logic fails.
@Stateless
publicclassLibraryPersistentBeanimplementsLibraryPersistentBeanRemote{
...
publicList<Book>getBooks()throwsNoBookAvailableException{
List<Book>books=entityManager.createQuery("FromBooks").getResultList();
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_IV_EJB_E_CONTENT
if(books.size==0)
throwNoBookAvailableException
("No Book available in library.");
returnbooks;
}
...
}
HandlingSystemException
Systemexceptioncan occur at anytime like naming lookup fails, sql error occurs while fetching data. In
such a case, such exception should be wrapped under EJBException and thrown back to the client.
@Stateless
publicclassLibraryPersistentBeanimplementsLibraryPersistentBeanRemote{
...
publicList<Book>getBooks(){
try {
List<Book>books=
entityManager.createQuery("FromBooks").getResultList();
}catch(CreateExceptionce){
throw(EJBException)newEJBException(ce).initCause(ce);
}catch(SqlExceptionse){
throw(EJBException)newEJBException(se).initCause(se);
}
returnbooks;
}
}
Atclientside,handletheEJBException.
}
}
ReferenceBook:JEE1.4Bible,J.McGovern,R.Adatia,Y.Fain,Wiley-dreamtechPublication,2003
WebResource:https://www.tutorialspoint.com/ejb/ejb_exception_handling.htm
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
ADVANCEJAVAPROGRAMMING
UNIT-V:
Springframework–Architecture–environmentsetup–simpleprograms–IOCcontainers– Bean
definition, scope and life cycle - dependency injections- injecting inner beans, injecting collection
- Hibernate overview – architecture – configuration – session – persistence class– mapping files –
O/R mapping – Annotation, query language.
SpringFramework-Overview
Spring is the most popular application development framework for enterprise Java. Millions of
developersaroundtheworlduseSpringFrameworktocreatehighperforming,easilytestable,and reusable code.
SpringframeworkisanopensourceJavaplatform.ItwasinitiallywrittenbyRodJohnsonandwas first
released under the Apache 2.0 license in June 2003.
Architecture
Springcouldpotentiallybeaone-stopshopforall yourenterpriseapplications.However,Springis
modular,allowingtopickandchoosewhichmodulesareapplicable,withouthavingtobringinthe rest.
The following section provides details about all the modules available in Spring Framework.
TheSpringFrameworkprovidesabout20moduleswhichcanbeusedbasedonanapplication requirement.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
CoreContainer
TheCoreContainerconsistsoftheCore,Beans,Context,andExpressionLanguagemodulesthe details of
which are as follows –
• TheCoremoduleprovidesthefundamentalpartsoftheframework,includingtheIoC and
Dependency Injection features.
• TheBeanmoduleprovidesBeanFactory,whichisasophisticatedimplementationof the
factory pattern.
• TheContextmodulebuildsonthesolidbaseprovidedbytheCoreandBeansmodules and it is
a medium to access any objects defined and configured. The ApplicationContext
interface is the focal point of the Context module.
• TheSpELmoduleprovidesapowerfulexpressionlanguageforqueryingand
manipulating an object graph at runtime.
•
DataAccess/Integration
TheDataAccess/IntegrationlayerconsistsoftheJDBC,ORM,OXM,JMSandTransactionmodules whose
detail is as follows –
• TheJDBC moduleprovidesaJDBC-abstractionlayerthatremovestheneedfor
tedious JDBC related coding.
• TheORMmoduleprovidesintegrationlayersforpopularobject-relationalmapping
APIs, including JPA, JDO, Hibernate, and iBatis.
• TheOXMmoduleprovidesanabstractionlayerthatsupportsObject/XMLmapping
implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
• TheJavaMessagingServiceJMSmodulecontainsfeaturesforproducingand
consuming messages.
• The Transaction module supports programmatic and declarative transaction
managementforclassesthatimplementspecialinterfacesandforallyourPOJOs.
Web
TheWeblayerconsistsoftheWeb,Web-MVC,Web-Socket,andWeb-Portletmodulesthedetailsof which are
as follows –
• TheWebmoduleprovidesbasicweb-orientedintegrationfeaturessuchasmultipart file-
upload functionality and the initialization of the IoC container using servlet
listeners and a web-oriented application context.
• TheWeb-MVCmodulecontainsSpring'sModel-View-Controller(MVC)
implementation for web applications.
• TheWeb-SocketmoduleprovidessupportforWebSocket-based,two-way
communication between the client and the server in web applications.
• TheWeb-PortletmoduleprovidestheMVCimplementationtobeusedinaportlet
environment and mirrors the functionality of Web-Servlet module.
Miscellaneous
TherearefewotherimportantmoduleslikeAOP,Aspects,Instrumentation,WebandTestmodules the
details of which are as follows −
• TheAOPmoduleprovidesanaspect-orientedprogrammingimplementationallowing you
to define method-interceptors and pointcuts to cleanly decouple code that implements
functionality that should be separated.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
• TheAspectsmoduleprovidesintegrationwithAspectJ,whichisagainapowerfuland
mature AOP framework.
• TheInstrumentationmoduleprovidesclassinstrumentationsupportandclassloader
implementations to be used in certain application servers.
• TheMessagingmoduleprovidessupportforSTOMPastheWebSocketsub-protocol to
use in applications. It also supports an annotation programming model for routing
and processing STOMP messages from WebSocket clients.
• TheTestmodulesupportsthetestingofSpringcomponentswithJUnitorTestNG
frameworks.
EnvironmentSetup
Step1-SetupJavaDevelopmentKit(JDK)
DownloadthelatestversionofSDKfromOracle'sJavasite−JavaSEDownloads.
setPATH=C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME=C:\jdk1.6.0_15
Alternatively,onWindowsNT/2000/XP,right-clickonMyComputer,selectProperties→Advanced
→EnvironmentVariables.
Then,updatethePATHvalueandclicktheOKbutton.
setenvPATH/usr/local/jdk1.6.0_15/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.6.0_15
Alternatively, use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse,
IntelliJIDEA,orSunONEStudio,compileandrunasimpleprogramtoconfirmthattheIDEknows where Java
is installed. Otherwise, carry out a proper setup as given in the document of the IDE.
Step2-InstallApacheCommonLoggingAPI
DownloadthelatestversionofApacheCommonsLoggingAPIfrom https://commons.apache.org/logging/.
Oncedownloadtheinstallation,unpackthebinarydistributionintoaconvenientlocation.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
Forexample,inC:\commons-logging-1.1.1onWindows,or/usr/local/commons-logging-1.1.1on Linux/Unix.
This directory will have the following jar files and other supporting documents, etc.
Step3-SetupEclipseIDE
ToinstallEclipseIDE,downloadthelatestEclipsebinariesfrom https://www.eclipse.org/downloads/. Once
downloaded the installation, unpack the binary distribution into a convenient location.
Forexample,inC:\eclipseonWindows,or/usr/local/eclipseonLinux/UnixandfinallysetPATH variable
appropriately.
EclipsecanbestartedbyexecutingthefollowingcommandsonWindowsmachine,orsimplydouble- click on
eclipse.exe
%C:\eclipse\eclipse.exe
EclipsecanbestartedbyexecutingthefollowingcommandsonUnix(Solaris,Linux,etc.)machine−
$/usr/local/eclipse/eclipse
Afterasuccessfulstartup,ifeverythingisfinethenitshoulddisplaythefollowingresult–
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
Step4-SetupSpringFrameworkLibraries
Nowifeverythingisfine,thenproceedtosetupSpringframework.Followingarethesimplestepsto download and
install the framework on machine.
• MakeachoicewhethertoinstallSpringonWindowsorUnix,andthenproceedtothe next
step to download .zip file for Windows and .tz file for Unix.
• DownloadthelatestversionofSpringframeworkbinariesfrom
https://repo.spring.io/release/org/springframework/spring.
• Atthetimeofdevelopingthistutorial,spring-framework-4.1.6.RELEASE-dist.zipwas
downloaded on Windows machine. After the downloaded file was unzipped, it gives
the following directory structure inside E:\spring.
•
FindalltheSpringlibrariesinthedirectoryE:\spring\libs.MakesuretosetCLASSPATHvariableon this
directory properly otherwise face a problem while running application. If Eclipse is used, then it is
not required to set CLASSPATH because all the setting will be done through Eclipse.
Simpleprogram
TowriteasimpleSpringApplication,whichwillprint"Hello World!"oranyother messagebasedon the
configuration done in Spring Beans Configuration file.
Step1-CreateJavaProject
ThefirststepistocreateasimpleJavaProjectusingEclipseIDE.Followtheoption File→New → Project and
finally select Java Project wizard from the wizard list. Now name the project
asHelloSpringusingthewizardwindowasfollows–
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
Oncetheprojectiscreatedsuccessfully,havethefollowingcontentinProjectExplorer–
Step2-AddRequiredLibraries
Add Spring Framework and common logging API libraries in project. To do this, right-click on
projectnameHelloSpringandthenfollowthefollowingoptionavailableinthecontextmenu− Build Path
→ Configure Build Path to display the Java Build Path window as follows –
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
• commons-logging-1.1.1
• spring-aop-4.1.6.RELEASE
• spring-aspects-4.1.6.RELEASE
• spring-beans-4.1.6.RELEASE
• spring-context-4.1.6.RELEASE
• spring-context-support-4.1.6.RELEASE
• spring-core-4.1.6.RELEASE
• spring-expression-4.1.6.RELEASE
• spring-instrument-4.1.6.RELEASE
• spring-instrument-tomcat-4.1.6.RELEASE
• spring-jdbc-4.1.6.RELEASE
• spring-jms-4.1.6.RELEASE
• spring-messaging-4.1.6.RELEASE
• spring-orm-4.1.6.RELEASE
• spring-oxm-4.1.6.RELEASE
• spring-test-4.1.6.RELEASE
• spring-tx-4.1.6.RELEASE
• spring-web-4.1.6.RELEASE
• spring-webmvc-4.1.6.RELEASE
• spring-webmvc-portlet-4.1.6.RELEASE
• spring-websocket-4.1.6.RELEASE
Step3-CreateSourceFiles
CreateactualsourcefilesundertheHelloSpringproject.Firstcreateapackagecalled
com.tutorialspoint.Todothis,rightclickonsrcinpackageexplorersectionandfollowtheoption
−New→Package.
NextcreateHelloWorld.javaandMainApp.javafilesunderthecom.tutorialspointpackage.
Hereisthecontentof HelloWorld.javafile–
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
packagecom.tutorialspoint;
public class HelloWorld {
privateStringmessage;
publicvoidsetMessage(Stringmessage){
this.message= message;
}
public void getMessage(){
System.out.println("YourMessage:"+message);
}
}
Followingisthecontentofthesecondfile MainApp.java–
package com.tutorialspoint;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassMainApp{
publicstaticvoidmain(String[]args){
ApplicationContextcontext=newClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
Followingtwoimportantpointsaretobenotedaboutthemainprogram–
• Thefirststepistocreateanapplicationcontextwhereweusedframework
APIClassPathXmlApplicationContext().ThisAPIloadsbeansconfigurationfileand
eventually based on the provided API, it takes care of creating and initializing all the
objects, i.e. beans mentioned in the configuration file.
• The second step is used to get the required bean using getBean() method of the created
context.ThismethodusesbeanIDtoreturnagenericobject,whichfinallycanbecasted to the
actual object. Once you have an object, you can use this object to call any class method.
Step4-CreateBeanConfigurationFile
CreateaBeanConfigurationfilewhichisanXMLfileandactsasa cementthatgluesthebeans,i.e. the classes
together. This file needs to be created under the src directory as shown in the following screenshot –
Usuallydevelopersnamethisfileas Beans.xml,butitisindependenttochooseanynameaslike.It is to
make sure that this file is available in CLASSPATH and use the same name in the main application
while creating an application context as shown in MainApp.java file.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
Letusseehowitworks–
<?xmlversion="1.0"encoding="UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beansh
ttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<beanid="helloWorld"class="com.tutorialspoint.HelloWorld">
<propertyname="message"value="HelloWorld!"/>
</bean>
</beans>
When Spring application gets loaded into the memory, Framework makes use of the above
configurationfiletocreateallthebeansdefinedandassignsthemauniqueIDasdefinedin<bean>tag. The
<property>tag is used to pass the values of different variables used at the time of object creation.
Step5-RunningtheProgram
Oncedonewithcreatingthesourceandbeansconfigurationfiles,i.e.,readyforthisstep,whichis compiling and
running the program. To do this, keep MainApp.Java file tab active and use either
RunoptionavailableintheEclipseIDEoruseCtrl+F11tocompileandrunMainAppapplication.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
Ifeverythingisfinewiththeapplication,thiswillprintthefollowingmessageinEclipseIDE's console –
YourMessage:Hello World!
Congratulations,successfullycreatedthefirstSpringApplication.
IoCContainers
TheSpringcontainerisatthecoreoftheSpringFramework.Thecontainerwillcreatetheobjects, wire them
together, configure them, and manage their complete life cycle from creation till destruction.
TheSpring containerusesDIto managethecomponentsthat makeup anapplication. These objects are
called Spring Beans.
Springprovidesthefollowingtwodistincttypesofcontainers.
Sr.No. Container&Description
1 SpringBeanFactoryContainer
ThisisthesimplestcontainerprovidingthebasicsupportforDIandisdefinedby
theorg.springframework.beans.factory.BeanFactoryinterface.TheBeanFactory and
related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean,
are still present in Spring for the purpose of backward compatibility with a large
number of third-party frameworks that integrate with Spring.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
2 SpringApplicationContextContainer
This container adds more enterprise-specific functionality such as the ability to
resolve textual messages from a properties file and the ability to publish application
eventstointerestedeventlisteners.Thiscontainerisdefinedby
theorg.springframework.context.ApplicationContextinterface.
TheApplicationContextcontainerincludesallfunctionalityoftheBeanFactorycontainer,soitis generally
recommended over BeanFactory. BeanFactory can still be used for lightweight applications like
mobile devices or applet-based applications where data volume and speed is significant.
BeanDefinition
The objects that form the backbone of your application and that are managed by the Spring IoC
container are called beans. A bean is an object that is instantiated, assembled, and otherwise
managedbyaSpringIoCcontainer.Thesebeansarecreatedwiththeconfigurationmetadatathat supply to
the container..
• Howtocreatea bean
• Bean'slifecycledetails
• Bean'sdependencies
Sr.No. Properties&Description
1 Class-Thisattributeismandatoryandspecifiesthebeanclasstobeusedto create the
bean.
2 Name - This attribute specifies the bean identifier uniquely. In XMLbased
configuration metadata, you use the id and/or name attributes to specify the
bean identifier(s).
3 Scope- This attribute specifiesthescopeof the objects created froma particular
bean definition and it will be discussed in bean scopes chapter.
4 constructor-arg - This is used to inject the dependencies and will be discussed
in subsequent chapters.
5 Properties-Thisisusedtoinjectthedependenciesandwillbediscussedin subsequent
chapters.
6 autowiringmode-Thisisusedtoinjectthedependenciesandwillbe discussed in
subsequent chapters.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
7 lazy-initializationmode-Alazy-initializedbeantellstheIoCcontainerto create a
bean instance when it is first requested, rather than at the startup.
8 initializationmethod- Acallbacktobecalledjustafterallnecessaryproperties on
the bean have been set by the container. It will be discussed in bean lifecycle
chapter.
9 destruction method- A callback to be used when the container containing the
bean is destroyed. It will be discussed in bean life cycle chapter.
SpringConfigurationMetadata
SpringIoCcontaineristotallydecoupledfromtheformatinwhichthisconfigurationmetadatais actually
written.
FollowingarethethreeimportantmethodstoprovideconfigurationmetadatatotheSpring Container –
• XMLbasedconfigurationfile.
• Annotation-basedconfiguration
• Java-basedconfiguration
ThefollowingisasampleofXML-basedconfigurationfilewithdifferentbeandefinitionsincluding lazy
initialization, initialization method, and destruction method –
<?xmlversion="1.0"encoding="UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beansh
ttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!--Asimplebeandefinition-->
<beanid="..."class="...">
<!--collaboratorsandconfigurationforthisbeangohere-->
</bean>
<!--Abeandefinitionwithlazyinitseton-->
<beanid="..."class="..."lazy-init="true">
<!--collaboratorsandconfigurationforthisbeangohere-->
</bean>
<!--Abeandefinitionwithinitializationmethod-->
<beanid="..."class="..."init-method="...">
<!--collaboratorsandconfigurationforthisbeangohere-->
</bean>
<!--Abeandefinitionwithdestructionmethod-->
<beanid="..."class="..."destroy-method="...">
<!--collaboratorsandconfigurationforthisbeangohere-->
</bean>
<!--morebeandefinitionsgohere-->
</beans>
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
BeanScopes
Whendefininga <bean>,thereisa option of declaringascopefor thatbean.For example,to force
Springtoproduceanewbeaninstanceeachtimeoneisneeded, youshoulddeclarethebean'sscope attribute to
be prototype. Similarly, if Spring is to return the same bean instance each time one is needed, the
bean's scope should be declared as the attribute to be singleton.
BeanLife Cycle
ThelifecycleofaSpringbeaniseasytounderstand.Whenabeanisinstantiated,itmayberequired to perform
some initialization to get it into a usable state. Similarly, when the bean is no longer required and is
removed from the container, some cleanup may be required.
Though, there are lists of the activities that take place behind the scene between the time of bean
Instantiationanditsdestruction,therearetwoimportantbeanlifecyclecallbackmethods,whichare required at
the time of bean initialization and its destruction.
To define setup and teardown for a bean, simply declare the <bean>withinit methodand/or
destroy-method parameters. The init-method attribute specifies a method that is to be called on the
beanimmediatelyuponinstantiation.Similarly,destroymethodspecifiesamethodthatiscalledjust before
a bean is removed from the container.
Initializationcallbacks
Theorg.springframework.beans.factory.InitializingBeaninterfacespecifiesasinglemethod− void
afterPropertiesSet() throws Exception;
Thus,simplyimplementtheaboveinterfaceandinitializationworkthatcanbedoneinside afterPropertiesSet()
method as follows –
publicclassExampleBeanimplementsInitializingBean{
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
publicvoidafterPropertiesSet()
{
//dosomeinitializationwork
}
}
<beanid="exampleBean"class="examples.ExampleBean"init-method="init"/>
publicclassExampleBean{
public void init() {
//dosomeinitializationwork
}
}
Destructioncallbacks
Theorg.springframework.beans.factory.DisposableBeaninterfacespecifiesasinglemethod−
void destroy() throws Exception;
Thus,simplyimplementtheaboveinterfaceandfinalizationworkthatcanbedoneinsidedestroy() method as
follows –
publicclassExampleBeanimplementsDisposableBean{ public
void destroy() {
//dosomedestructionwork
}
}
<beanid="exampleBean"class="examples.ExampleBean"destroy-method="destroy"/> Following is
publicclassExampleBean{
public void destroy() {
//dosomedestructionwork
}
}
DependencyInjection
EveryJava-based application has a few objects that work together to present what the end-user sees
asaworkingapplication.WhenwritingacomplexJavaapplication,applicationclassesshouldbeas
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
independent as possible of other Java classes to increase the possibilityto reuse these classes and to
test them independently of other classes while unit testing. Dependency Injection (or sometime
calledwiring)helpsingluingtheseclassestogetherandatthesametimekeepingthemindependent.
Consideranapplicationwhichhasatexteditorcomponentandthattoprovideaspellcheck. public
class TextEditor {
privateSpellCheckerspellChecker;
publicTextEditor(){
spellChecker=newSpellChecker();
}
}
Here,adependencyiscreatedbetweentheTextEditorandtheSpellChecker.Inaninversionof control
scenario, instead do something like this –
publicclassTextEditor{
privateSpellCheckerspellChecker;
publicTextEditor(SpellCheckerspellChecker){
this.spellChecker = spellChecker;
}
}
Here,theTextEditorshouldnotworryaboutSpellCheckerimplementation.TheSpellCheckerwill be
implemented independently and will be provided to the TextEditor at the time of TextEditor
instantiation. This entire procedure is controlled by the Spring Framework.
Here, remove the total control from the TextEditor and kept it somewhere else (i.e. XML
configurationfile)andthedependency(i.e.classSpellChecker)isbeinginjectedintotheclassText Editor
through a Class Constructor. Thus the flow of control has been "inverted" by Dependency Injection
(DI) because that has effectively delegated dependences to some external system.
The second method of injecting dependency is through Setter Methods of the TextEditor class
wherecreateaSpellCheckerinstance.Thisinstancewillbeusedtocallsettermethodstoinitialize
TextEditor's properties.
Thus,DIexistsintwomajorvariantsandthefollowingtwosub-chapterswillcoverbothofthem with
examples –
Sr.No. DependencyInjectionType&Description
1 Constructor-baseddependencyinjection
Constructor-based DI is accomplished when the container invokes a class
constructorwithanumberofarguments,eachrepresentingadependencyonthe other
class.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
2 Setter-baseddependencyinjection
Setter-basedDIisaccomplishedbythecontainercallingsetter methodson your
beans after invoking a no-argument constructor or no-argument static factory
method to instantiate your bean.
InjectingInnerBeans
Javainnerclassesaredefinedwithinthescopeofotherclasses,similarly, innerbeansarebeansthat are
defined within the scope of another bean. Thus, a <bean/> element inside the <property/> or
<constructor-arg/>elementsiscalledinnerbeananditisshownbelow.
<?xmlversion="1.0"encoding="UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beansh
ttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<beanid="outerBean"class="...">
<propertyname="target">
<beanid="innerBean"class="..."/>
</property>
</bean>
</beans>
InjectingCollection
SpringoffersfourtypesofcollectionconfigurationelementstopasspluralvalueslikeJava Collection types
such as List, Set, Map, and Properties.
Sr.No Element&Description
1 <list>Thishelpsinwiringieinjectingalistofvalues,allowingduplicates.
2 <set>Thishelpsinwiringasetofvaluesbutwithoutanyduplicates.
3 <map>This can be used to inject a collection ofname-value pairs where name andvalue
can be of any type.
4 <props>This can be used to inject a collection of name-value pairs where the name
and value are both Strings.
Hibernate-Overview
Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is an open source
persistentframeworkcreatedbyGavinKingin2001.Itisapowerful,highperformanceObject- Relational
Persistence and Query service for any Java Application.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
HibernateAdvantages
• HibernatetakescareofmappingJavaclassestodatabasetablesusingXMLfilesand
without writing any line of code.
• ProvidessimpleAPIsforstoringandretrievingJavaobjectsdirectlytoandfromthe
database.
• Ifthereischangeinthedatabaseorinanytable,then youneedtochangetheXMLfile
properties only.
• AbstractsawaytheunfamiliarSQLtypesandprovidesawaytoworkaroundfamiliarJava
Objects.
• Hibernatedoesnotrequireanapplicationservertooperate.
• ManipulatesComplexassociationsofobjectsofyourdatabase.
• Minimizesdatabaseaccesswithsmartfetchingstrategies.
• Providessimplequeryingofdata.
SupportedDatabases
HibernatesupportsalmostallthemajorRDBMS.Followingisalistoffewofthedatabaseengines supported by
Hibernate –
• HSQLDatabaseEngine
• DB2/NT
• MySQL
• PostgreSQL
• FrontBase
• Oracle
• MicrosoftSQLServerDatabase
• SybaseSQLServer
• InformixDynamicServer
SupportedTechnologies
Hibernatesupportsavarietyofothertechnologies,including–
• XDocletSpring
• J2EE
• Eclipseplug-ins
• Maven
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
Hibernate–Architecture
Hibernate has a layered architecture which helps the user to operate without having to know the
underlyingAPIs.Hibernatemakesuseofthedatabaseandconfigurationdatatoprovidepersistence services
(and persistent objects) to the application.
FollowingisaveryhighlevelviewoftheHibernateApplicationArchitecture.
FollowingisadetailedviewoftheHibernateApplicationArchitecturewithitsimportantcore classes.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming
and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality
commontorelationaldatabases,allowingalmostanydatabasewithaJDBCdrivertobesupportedby
Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.
FollowingsectiongivesbriefdescriptionofeachoftheclassobjectsinvolvedinHibernate Application
Architecture.
ConfigurationObject
The Configuration object is the first Hibernate object you create in any Hibernate application. It is
usuallycreatedonlyonceduringapplicationinitialization.Itrepresentsaconfigurationorproperties file
required by the Hibernate.
TheConfigurationobjectprovidestwokeyscomponents–
SessionFactoryObject
Configuration object is used to create a SessionFactoryobject which in turn configures Hibernate for
theapplicationusingthesuppliedconfigurationfileandallowsforaSessionobjecttobeinstantiated. The
SessionFactory is a thread safe object and used by all the threads of an application.
SessionObject
ASession isused togeta physical connection with adatabase.The Sessionobjectislightweightand
designedto beinstantiatedeachtimeaninteractionisneededwiththedatabase.Persistentobjectsare saved
and retrieved through a Session object.
TransactionObject
A Transaction represents a unit of work with the database and most of the RDBMS supports
transactionfunctionality.TransactionsinHibernatearehandledbyanunderlyingtransactionmanager and
transaction (from JDBC or JTA).
ThisisanoptionalobjectandHibernateapplicationsmaychoosenottousethisinterface,instead managing
transactions in their own application code.
QueryObject
QueryobjectsuseSQLorHibernateQueryLanguage(HQL)stringtoretrievedatafromthedatabase and
create objects.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
CriteriaObject
Criteriaobjectsareusedtocreateandexecuteobjectorientedcriteriaqueriestoretrieveobjects.
Hibernate–Configuration
Hibernate requires to know in advance — where to find the mapping information that defines how
your Java classes relate to the database tables. Hibernate also requires a set of configuration settings
relatedtodatabaseandotherrelatedparameters.Allsuchinformationisusuallysuppliedasastandard Java
properties file called hibernate.properties, or as an XML file named hibernate.cfg.xml.
HibernateProperties
Followingisthelistofimportantproperties, youwillberequiredtoconfigureforadatabasesina standalone
situation –
Sr.No. Properties&Description
1 hibernate.dialect -This property makes Hibernate generate the
appropriate SQL for the chosen database.
2 hibernate.connection.driver_class-TheJDBCdriverclass.
3 hibernate.connection.url-TheJDBCURLtothedatabaseinstance.
4 hibernate.connection.username-Thedatabaseusername.
5 hibernate.connection.password-Thedatabasepassword.
6 hibernate.connection.pool_size-Limitsthenumberofconnections waiting
in the Hibernate database connection pool.
7 hibernate.connection.autocommit- Allowsautocommitmodetobeused for
the JDBC connection.
HibernatewithMySQLDatabase
MySQLisoneofthemostpopularopen-sourcedatabasesystemsavailabletoday.
Createhibernate.cfg.xmlconfigurationfileandplaceitintherootoftheapplication'sclasspath.Make sure
that you have testdb database available in the MySQL database and have a user test available to
access the database.
TheXMLconfigurationfilemustconformtotheHibernate3ConfigurationDTD,whichisavailable at
http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd.
<?xmlversion="1.0"encoding="utf-8"?>
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
Hibernate–Sessions
ASession isused togeta physical connection with adatabase.The Sessionobjectislightweightand
designedto beinstantiatedeachtimeaninteractionisneededwiththedatabase.Persistentobjectsare saved
and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe
andtheyshouldbecreatedanddestroyedthemasneeded.ThemainfunctionoftheSessionistooffer, create,
read, and delete operations for instances of mapped entity classes.
Instancesmayexistinoneofthefollowingthreestatesatagivenpointintime–
• transient − A new instance of a persistent class, which is not associated with a Session
andhasnorepresentationinthedatabaseandnoidentifiervalueisconsideredtransientby
Hibernate.
• persistent−AtransientinstancecanbemadepersistentbyassociatingitwithaSession.
Apersistentinstancehasarepresentationinthedatabase,anidentifiervalueandis associated with
a Session.
• detached−OncetheHibernateSessionisclosed,thepersistentinstancewillbecomea
detached instance.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
Sessionsession=factory.openSession();
Transaction tx = null;
try{
tx=session.beginTransaction();
//dosomework
...
tx.commit();
}
catch(Exceptione){
if(tx!=null)tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
IftheSessionthrowsanexception,thetransactionmustberolledbackandthesessionmustbe discarded.
PersistentClass
Javaclasseswhoseobjectsorinstanceswillbestoredindatabasetablesarecalledpersistentclassesin
Hibernate. Hibernate works best if these classes follow some simple rules, also known as the Plain
Old Java Object (POJO) programming model.
Therearefollowingmainrulesofpersistentclasses,however,noneoftheserulesarehard requirements –
• AllJavaclassesthatwillbepersistedneedadefaultconstructor.
• All classes should contain an ID in order to allow easy identification of your objects
withinHibernateandthedatabase.Thispropertymapstotheprimarykeycolumnofa
database table.
• All attributes that will be persisted should be declared private and
havegetXXXandsetXXXmethodsdefinedintheJavaBeanstyle.
• AcentralfeatureofHibernate,proxies,dependsuponthepersistentclassbeingeither non-
final, or the implementation of an interface that declares all public methods.
• Allclassesthatdonotextendorimplementsomespecializedclassesandinterfaces
required by the EJB framework.
SimplePOJOExample
Basedonthefewrulesmentionedabove,defineaPOJOclassasfollows–
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
publicclassEmployee{
private int id;
privateStringfirstName;
private String lastName;
private int salary;
publicEmployee(){}
publicEmployee(Stringfname,Stringlname,intsalary){
this.firstName = fname;
this.lastName=lname;
this.salary = salary;
}
publicintgetId(){
return id;
}
publicvoidsetId(intid){ this.id
= id;
}
publicStringgetFirstName(){
return firstName;
}
publicvoidsetFirstName(Stringfirst_name){
this.firstName = first_name;
}
publicStringgetLastName(){
return lastName;
}
publicvoidsetLastName(Stringlast_name){
this.lastName = last_name;
}
publicintgetSalary(){
return salary;
}
publicvoidsetSalary(intsalary){
this.salary = salary;
}
}
MappingFiles
AnObject/relational mappingsareusuallydefinedinanXMLdocument.Thismappingfileinstructs Hibernate —
how to map the defined class or classes to the database tables?
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
ThoughmanyHibernateuserschoosetowritetheXMLbyhand,butanumberoftoolsexisttogenerate the
mapping document. These include XDoclet, Middlegen and AndroMDA for the advanced Hibernate
users.
Example:
publicclassEmployee{
private int id;
privateStringfirstName;
private String lastName;
private int salary;
publicEmployee(){}
publicEmployee(Stringfname,Stringlname,intsalary){
this.firstName = fname;
this.lastName=lname;
this.salary = salary;
}
publicintgetId(){
return id;
}
publicvoidsetId(intid){ this.id
= id;
}
publicStringgetFirstName(){
return firstName;
}
publicvoidsetFirstName(Stringfirst_name){
this.firstName = first_name;
}
publicStringgetLastName(){
return lastName;
}
publicvoidsetLastName(Stringlast_name){ this.lastName =
last_name;
}
publicintgetSalary(){
return salary;
}
publicvoidsetSalary(intsalary){
this.salary = salary;
}
}
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
objects need to be stored and retrieved into the following RDBMS table –
createtableEMPLOYEE(
id INT NOT NULL auto_increment,
first_nameVARCHAR(20)defaultNULL,
last_nameVARCHAR(20)defaultNULL,
salary INTdefault NULL,
PRIMARYKEY(id)
);
Basedonthetwoaboveentities,followingmappingfilecanbedefined,whichinstructsHibernate how to
map the defined class or classes to the database tables.
<?xmlversion="1.0"encoding="utf-8"?>
<!DOCTYPEhibernate-mappingPUBLIC"-
//Hibernate/HibernateMappingDTD//EN""http://www.hibernate.org/dtd/hibernate-
mapping-3.0.dtd">
<hibernate-mapping>
<classname="Employee"table="EMPLOYEE">
<metaattribute="class-description">
Thisclasscontainstheemployeedetail.
</meta>
<idname="id"type="int"column= "id">
<generatorclass="native"/>
</id>
<propertyname="firstName"column="first_name"type="string"/>
<propertyname="lastName"column="last_name"type="string"/>
<propertyname="salary"column="salary" type="int"/>
</class>
</hibernate-mapping>
Savethemappingdocumentinafilewiththeformat<classname>.hbm.xml.Themappingdocument in the
file is saved as Employee.hbm.xml.
Themappingelementsusedinthemappingfile–
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
O/RMappings
Thefollowingarethreemostimportantmappingtopics
o Mappingofcollections,
o Mappingofassociationsbetweenentityclasses,and
o ComponentMappings.
CollectionsMappings
Ifanentityorclasshascollectionofvaluesforaparticularvariable,thenmapthosevaluesusingany one of the
collection interfaces available in java. Hibernate can persist instances of java.util. Map, java.util.
Set,java.util.SortedMap,java.util.SortedSet, java.util.List,andanyarray of persistent entities or
values.
ArraysaresupportedbyHibernatewith<primitive-array>forJavaprimitivevaluetypesand<array> for
everything else.
Ifauserdefinedcollectioninterfaceshastobemapped,whichisnotdirectlysupportedbyHibernate, it is to
tell Hibernate about the semantics of the custom collections, which is not very easy and not
recommend to be used.
AssociationMappings
Themappingofassociationsbetweenentityclassesandtherelationshipsbetweentablesisthesoulof ORM.
Following are the four ways in which the cardinality of the relationship between the objects can be
expressed. An association mapping can be unidirectional as well as bidirectional.
Sr.No. Mappingtype&Description
1 Many-to-One Mappingmany-to-onerelationshipusingHibernate
2 One-to-One Mappingone-to-onerelationshipusingHibernate
3 One-to-Many Mappingone-to-manyrelationshipusingHibernate
4 Many-to-ManyMappingmany-to-manyrelationshipusingHibernate
ComponentMappings
ItisverymuchpossiblethatanEntityclasscanhaveareferencetoanotherclassasamember variable.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
Sr.No. Mappingtype&Description
1.ComponentMappings Mappingforaclasshavingareferencetoanotherclassasamember
variable.
Annotations
Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational
Tablemapping.AllthemetadataisclubbedintothePOJOjavafilealongwiththecode,thishelpsthe user to
understand the table structure and POJO simultaneously during the development.
ConsiderthefollowingEMPLOYEEtabletostoretheobjects− create
table EMPLOYEE (
id INT NOT NULL auto_increment,
first_nameVARCHAR(20)defaultNULL,
last_nameVARCHAR(20)defaultNULL,
salary INTdefault NULL,
PRIMARYKEY(id)
);
importjavax.persistence.*;
@Entity
@Table(name="EMPLOYEE")
public class Employee {
@Id @GeneratedValue
@Column(name="id")
private int id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="salary")
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
publicEmployee(){}
publicintgetId(){
return id;
}
publicvoidsetId(intid){ this.id
= id;
}
publicStringgetFirstName(){
return firstName;
}
publicvoidsetFirstName(Stringfirst_name){
this.firstName = first_name;
}
publicStringgetLastName(){
return lastName;
}
publicvoidsetLastName(Stringlast_name){
this.lastName = last_name;
}
publicintgetSalary(){
return salary;
}
publicvoidsetSalary(intsalary){
this.salary = salary;
}
}
Hibernatedetectsthatthe@Idannotationisonafieldandassumesthatitshouldaccesspropertiesof an object
directlythrough fields at runtime. If the @Id annotation on the getId() method is placed, it enable
access topropertiesthroughgetterand setter methodsbydefault.Hence,allother annotations are also
placed on either fields or getter methods, following the selected strategy.
HibernateQueryLanguage
HibernateQueryLanguage(HQL)isanobject-orientedquerylanguage,similartoSQL,butinsteadof
operating on tables and columns, HQL works with persistent objects and their properties. HQLqueries
are translated by Hibernate into conventional SQL queries, which in turns perform action on database.
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
KeywordslikeSELECT,FROM,andWHERE,etc.,arenotcasesensitive,butpropertiesliketable and
column names are case sensitive in HQL.
FROMClause
FROMclauseisusediftoloadcompletepersistentobjectsintomemory.Followingisthesimple syntax of
using FROM clause –
Stringhql="FROMEmployee";
Queryquery=session.createQuery(hql);
List results = query.list();
"FROM com.hibernatebook.criteria.Employee";
Queryquery= session.createQuery(hql);
Listresults=query.list();
ASClause
TheASclausecanbeusedtoassignaliasestotheclassesintheHQLqueries,especiallywhenthere are long
queries.
Forinstance,previoussimpleexamplewouldbethefollowing– String
TheASkeywordisoptionalandcanalsobespecifiedthealiasdirectlyaftertheclassname,as follows
SELECTClause
TheSELECTclauseprovidesmorecontrolovertheresultsetthenthefromclause.Iftoobtainfew properties of
objects instead of the complete object, use the SELECT clause.
Stringhql="SELECTE.firstNameFROMEmployeeE"; Query
query = session.createQuery(hql);
Listresults=query.list();
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
WHEREClause
Iftonarrowthespecificobjectsthatarereturnedfromstorage, youusetheWHEREclause.Following is the
simple syntax of using WHERE clause –
Stringhql="FROMEmployeeEWHEREE.id=10"; Query
query = session.createQuery(hql);
Listresults=query.list();
ORDERBYClause
TosortHQLquery'sresults,the ORDERBY clauseisused.Theresultscanbe orderedbyany property on
the objects in the result set either ascending (ASC) or descending (DESC).
FollowingisthesimplesyntaxofusingORDERBYclause–
Stringhql="FROMEmployeeEWHEREE.id>10ORDERBYE.salaryDESC"; Query
query = session.createQuery(hql);
Listresults=query.list();
Iftosortbymorethanoneproperty,justaddtheadditionalpropertiestotheendoftheorderby clause,
separated by commas as follows –
GROUPBYClause
This clause lets Hibernate pull information from the database and group it based on a value of an
attributeand,typically,usetheresulttoincludeanaggregatevalue.Followingisthesimplesyntaxof using
GROUP BY clause –
Stringhql="SELECTSUM(E.salary),E.firtNameFROMEmployeeE"+
"GROUP BY E.firstName";
Queryquery=session.createQuery(hql);
List results = query.list();
UsingNamedParameters
HibernatesupportsnamedparametersinitsHQLqueries.ThismakeswritingHQLqueriesthataccept input
from the user easy and do not have to defend against SQL injection attacks. Following is the simple
syntax of using named parameters –
Stringhql="FROMEmployeeEWHEREE.id=:employee_id"; Query
query = session.createQuery(hql);
query.setParameter("employee_id",10);
Listresults=query.list();
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.
20BHM404 AJAVA_UNIT_V_SPRING_HIBERNATE_E_CONTENT
UPDATEClause
TheQueryinterfacenowcontainsamethodcalledexecuteUpdate()forexecutingHQLUPDATEor DELETE
statements.
Stringhql="UPDATEEmployeesetsalary=:salary"+ "WHERE
id = :employee_id";
Queryquery=session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("employee_id",10);
int result = query.executeUpdate();
System.out.println("Rowsaffected:"+result);
DELETEClause
TheDELETEclausecanbeusedtodeleteoneormoreobjects.Followingisthesimplesyntaxof using
DELETE clause –
Stringhql="DELETEFROMEmployee"+
"WHERE id = :employee_id";
Queryquery=session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rowsaffected:"+result);
INSERTClause
HQLsupportsINSERTINTOclauseonlywhererecordscanbeinsertedfromoneobjecttoanother object.
Following is the simple syntax of using INSERT INTO clause –
Stringhql="INSERTINTOEmployee(firstName,lastName,salary)"+ "SELECT
firstName, lastName, salary FROM old_employee";
Queryquery=session.createQuery(hql); int
result = query.executeUpdate();
System.out.println("Rowsaffected:"+result);
WebReferences:
1. https://www.tutorialspoint.com/spring/index.htm
2. https://www.tutorialspoint.com/hibernate/
PreparedbyH.RiazAhamed,AssistantProfessor,TheNewCollege,Chennai-14.