J2EE Notes
J2EE Notes
Tutorial
JSP Overview
ava Server Pages (JSP) is a technology for developing web pages that support dynamic content which
helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <
% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user interface for a
Java web application. Web developers write JSPs as text files that combine HTML or XHTML code, XML
elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through web page forms, present records from a database or
another source, and create web pages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering
user preferences, accessing JavaBeans components, passing control between pages and sharing information
between requests, pages etc.
Advantages of JSP:
Following is the list of other advantages of using JSP over other technologies:
vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is written in
Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it
is portable to other operating systems and non-Microsoft Web servers.
vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real" programs
that use form data, make database connections, and the like.
vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly interact with the
web server to perform complex tasks like database access and image processing etc.
vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
development environment is where you would develop your JSP programs, test them and finally run
them.
This chapter will guide you to setup your JSP development environment which involves following steps:
Further information about configuring and running Tomcat can be found in the documentation included here, as
well as on the Tomcat web site: http://tomcat.apache.org
Tomcat can be stopped by executing the following commands on windows machine:
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$CATALINA_HOME/bin/shutdown.sh
or
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes to the
compiler.
If you are running Windows, you need to put the following lines in your C:\autoexec.bat file.
set CATALINA=C:\apache-tomcat-5.5.29
set CLASSPATH=%CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%
Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then
Advanced, then Environment Variables. Then, you would update the CLASSPATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines into your .cshrc file.
setenv CATALINA=/usr/local/apache-tomcat-5.5.29
setenv CLASSPATH $CATALINA/common/lib/jsp-api.jar:$CLASSPATH
NOTE: Assuming that your development directory is C:\JSPDev (Windows) or /usr/JSPDev (Unix) then you would
need to add these directories as well in CLASSPATH in similar way as you have added above.
JSP Architecture
he web server needs a JSP engine ie. container to process JSP pages. The JSP container is responsible
for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP container to
support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It
knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web Application.
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is
done by using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very
simple in which all template text is converted to println( ) statements and all JSP elements are converted to
Java code that implements the corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet
engine.
A part of the web server called the servlet engine loads the Servlet class and executes it. During execution,
the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an
HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if
it were a static page.
All the above mentioned steps can be shown below in the following diagram:
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the
modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP
container assumes that the JSP hasn't changed and that the generated servlet still matches the JSP's contents.
This makes the process more efficient than with other scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz.
Except for the translation phase, a JSP page is handled exactly like a regular servlet
his chapter will explain how to install Hibernate and other associated packages to prepare a develop
environment for the Hibernate applications. We will work with MySQL database to experiment with Hibernate
examples, so make sure you already have setup for MySQL database. For a more detail on MySQL you can
check our MySQL Tutorial.
The key to understanding the low-level functionality of JSP is to understand the simple life cycle they follow.
A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a
servlet life cycle with an additional step which is required to compile a JSP into servlet.
The following are the paths followed by a JSP
Compilation
Initialization
Execution
Cleanup
The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:
JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the
page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine
compiles the page.
The compilation process involves three steps:
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform
JSP-specific initialization, override the jspInit() method:
public void jspInit(){
// Initialization code...
}
Typically initialization is performed only once and as with the servlet init method, you generally initialize database
connections, open files, and create lookup tables in the jspInit method.
JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the
_jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as
follows:
void _jspService(HttpServletRequest request,
HttpServletResponse response)
}
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response
for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie.
GET, POST, DELETE etc.
JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you
need to perform any cleanup, such as releasing database connections or closing open files.
The jspDestroy() method has the following form:
public void jspDestroy()
{
// Your cleanup code goes here.
}
JSP Syntax
his chapter will give basic idea on simple syntax (ie. elements) involved with JSP development:
The Scriptlet:
A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions
that are valid in the page scripting language.
Following is the syntax of Scriptlet:
<% code fragment %>
You can write XML equivalent of the above syntax as follows:
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first
example for JSP:
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " +
request.getRemoteAddr()); %>
</body>
</html>
NOTE: Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your environment is setup as per
environment setup tutorial.
Let us keep above code in JSP file hello.jsp and put this file in C:\apache-tomcat-7.0.2\webapps\ROOTdirectory
and try to browse it by giving URL http://localhost:8080/hello.jsp. This would generate following result:
JSP Declarations:
A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You
must declare the variable or method before you use it in the JSP file.
Following is the syntax of JSP Declarations:
<%! declaration; [ declaration; ]+ ... %>
You can write XML equivalent of the above syntax as follows:
<jsp:declaration>
code fragment
</jsp:declaration>
Following is the simple example for JSP Declarations:
<%! int i = 0; %> <
%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
JSP Expression:
A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and
inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an expression within a line of text,
whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java Language Specification but
you cannot use a semicolon to end an expression.
Following is the syntax of JSP Expression:
<%= expression %>
You can write XML equivalent of the above syntax as follows:
<jsp:expression>
expression
</jsp:expression>
Following is the simple example for JSP Expression:
<html>
<head><title>A Comment Test</title></head>
<body>
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
This would generate following result:
JSP Comments:
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you
want to hide or "comment out" part of your JSP page.
Following is the syntax of JSP comments:
<%-- This is JSP comment --%>
Following is the simple example for JSP Comments:
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source -%> </body>
</html>
This would generate following result:
A Test of Comments
There are a small number of special constructs you can use in various cases to insert comments or characters
that would otherwise be treated specially. Here's a summary:
Syntax
Purpose
<\%
%\>
\'
\"
JSP Directives:
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
There are three types of directive tag:
Directive
Description
JSP Actions:
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically
insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java
plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />
Action elements are basically predefined functions and there are following JSP actions available:
Syntax
Purpose
jsp:include
jsp:include
jsp:useBean
jsp:setProperty
jsp:getProperty
jsp:forward
jsp:plugin
Generates browser-specific code that makes an OBJECT or EMBED tag for the
Java plugin
jsp:element
jsp:attribute
jsp:body
jsp:text
Description
request
response
This is the HttpServletResponse object associated with the response to the client.
out
session
application
config
pageContext
page
This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception
The Exception object allows the exception data to be accessed by designated JSP.
We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.
Control-Flow Statements:
JSP provides full power of Java to be embedded in your web application. You can use all the APIs and building
blocks of Java in your JSP programming including decision making statements, loops etc.
Decision-Making Statements:
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text
included between Scriptlet tags.
<%! int day = 3; %>
<html>
<head><title>IF...ELSE Example</title></head>
<body>
<% if (day == 1 | day == 7) { %>
<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
<% } %>
</body>
</html>
Now look at the following switch...case block which has been written a bit differentlty using out.println()and
inside Scriptletas:
<%! int day = 3; %>
<html>
<head><title>SWITCH...CASE Example</title></head>
<body>
<%
switch(day)
{ case 0:
out.println("It\'s Sunday.");
break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");
break;
case 4:
out.println("It\'s Thursday.");
break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It's Saturday.");
}
%>
</body>
</html>
This would produce following result:
It's Wednesday.
Loop Statements:
You can also use three basic types of looping blocks in Java: for, while,and dowhile blocks in your JSP
programming.
Let us look at the following for loop example:
<%! int fontSize; %>
<html>
<head><title>FOR LOOP Example</title></head>
<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
JSP Tutorial
JSP Tutorial
</body>
</html>
JSP Tutorial
JSP Tutorial
JSP Operators:
JSP supports all the logical and arithmetic operators supported by Java. Following table give a list of all the
operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.
Within an expression, higher precedence operators will be evaluated first.
Category
Operator
Associativity
Postfix
() [] . (dot operator)
Left to right
Unary
++ - - ! ~
Right to left
Multiplicative
*/%
Left to right
Additive
+-
Left to right
Shift
Left to right
Relational
Left to right
Equality
== !=
Left to right
Bitwise AND
&
Left to right
Bitwise XOR
Left to right
Bitwise OR
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
Right to left
Comma
Left to right
JSP Literals:
The JSP expression language defines the following literals:
Boolean: true and false
Integer: as in Java
Floating point: as in Java
String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
Null: null
I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate properties in my examples.
Most of the properties take their default values and it is not required to specify them in the property file unless it is
really required. This file is kept in the root directory of your application's classpath.
JSP Directives
SP directives provide directions and instructions to the container, telling it how to handle certain aspects of
JSP processing.
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
Directives can have a number of attributes which you can list down as key-value pairs and separated by commas.
The blanks between the @ symbol and the directive name, and between the last attribute and the closing %>, are
optional.
There are three types of directive tag:
Directive
Description
Attributes:
Following is the list of attributes associated with page directive:
Attribute
Purpose
buffer
autoFlush
contentType
errorPage
Defines the URL of another JSP that reports on Java unchecked runtime exceptions.
isErrorPage
Indicates if this JSP page is a URL specified by another JSP page's errorPage
attribute.
extends
import
Specifies a list of packages or classes for use in the JSP as the Java import
statement does for Java classes.
info
Defines a string that can be accessed with the servlet's getServletInfo() method.
isThreadSafe
language
session
isELIgnored
Specifies whether or not EL expression within the JSP page will be ignored.
isScriptingEnabled
Check more detail related to all the above attributes at Page Directive.
JSP Actions
SP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically
insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java
plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />
Action elements are basically predefined functions and there are following JSP actions available:
Syntax
Purpose
jsp:include
jsp:include
jsp:useBean
jsp:setProperty
jsp:getProperty
jsp:forward
jsp:plugin
Generates browser-specific code that makes an OBJECT or EMBED tag for the
Java plugin
jsp:element
jsp:attribute
jsp:body
jsp:text
Common Attributes:
There are two attributes that are common to all Action elements: the id attribute and the scope attribute.
Id attribute: The id attribute uniquely identifies the Action element, and allows the action to be referenced
inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it
through the implicit object PageContext
Scope attribute: This attribute identifies the lifecycle of the Action element. The id attribute and the scope
attribute are directly related, as the scope attribute determines the lifespan of the object associated with the
id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.
Description
page
flush
The boolean attribute determines whether the included resource has its buffer
flushed before it is included.
Example:
Let us define following two files (a)date.jps and (b) main.jsp as follows:
Following is the content of date.jsp file:
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
Here is the content of main.jsp file:
<html>
<head>
<title>The include Action
Example</title> </head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page="date.jsp" flush="true" />
</center>
</body>
</html>
Now let us keep all these files in root directory and try to access main.jsp. This would display result something like
this:
Description
class
type
Specifies the type of the variable that will refer to the object.
beanName
Gives the name of the bean as specified by the instantiate () method of the
java.beans.Beans class.
Let us discuss about jsp:setProperty and jsp:getProperty actions before giving a valid example related to these
actions.
Description
name
Designates the bean whose property will be set. The Bean must have been
previously defined.
property
Indicates the property you want to set. A value of "*" means that all request
parameters whose names match bean property names will be passed to the
appropriate setter methods.
value
The value that is to be assigned to the given property. The the parameter's value is
null, or the parameter does not exist, the setProperty action is ignored.
param
The param attribute is the name of the request parameter whose value the property
is to receive. You can't use both value and param, but it is permissible to use
neither.
Description
name
The name of the Bean that has a property to be retrieved. The Bean must have been
previously defined.
property
Example:
Let us define a test bean which we will use in our example:
/* File: TestBean.java */
package action;
public class TestBean {
private String message = "No message specified";
public String getMessage()
{ return(message);
}
public void setMessage(String message) {
this.message = message;
}
}
Compile above code to generated TestBean.class file and make sure that you copied TestBean.class in
C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and CLASSPATH variable should also be set to
this folder:
Now use the following code in main.jsp file which loads the bean and sets/gets a simple String parameter:
<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id="test" class="action.TestBean" />
<jsp:setProperty name="test"
property="message"
value="Hello JSP..." />
<p>Got message....</p>
<jsp:getProperty name="test" property="message" />
</center>
</body>
</html>
Now try to access main.jsp, it would display following result:
Description
page
Should consist of a relative URL of another resource such as a static page, another
JSP page, or a Java Servlet.
Example:
Let us reuse following two files (a) date.jps and (b) main.jsp as follows:
Following is the content of date.jsp file:
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
Here is the content of main.jsp file:
<html>
<head>
<title>The include Action
Example</title> </head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:forward page="date.jsp" />
</center>
</body>
</html>
Now let us keep all these files in root directory and try to access main.jsp. This would display result something like
as below. Here it discarded content from main page and displayed content from forwarded page only.
Today's date: 12-Sep-2010 14:54:22
<jsp:fallback>
Unable to initialize Java Plugin
</jsp:fallback>
</jsp:plugin>
You can try this action using some applet if you are interested. A new element, the <fallback> element, can be
used to specify an error string to be sent to the user in case the component fails.
<jsp:text><![CDATA[<br>]]></jsp:text>
If you need to include a DOCTYPE declaration, for instance for XHTML, you must also use the <jsp:text> element
as follows:
<jsp:text><![CDATA[<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN" "DTD/xhtml1-strict.dtd">]]>
</jsp:text>
<head><title>jsp:text
action</title></head> <body>
<books><book><jsp:text> Welcome
to JSP Programming
</jsp:text></book></books>
</body>
</html>
SP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page
and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called predefined variables.
JSP supports nine Implicit Objects which are listed below:
Object
Description
request
response
This is the HttpServletResponse object associated with the response to the client.
out
session
application
config
pageContext
page
This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception
Description
out.print(dataType dt)
out.println(dataType dt)
Print a data type value then terminate the line with new line character.
out.flush()
This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the
paths or file locations etc.
The following config method is the only one you might ever use, and its usage is trivial:
config.getServletName();
This returns the servlet name, which is the string contained in the <servlet-name> element defined in the WEBINF\web.xml file
pageContext.removeAttribute("attrName", PAGE_SCOPE);
You can check a very good usage of pageContext in coming chapter: JSP - File Uploading.
9
JSP Client Request
hen a browser requests for a web page, it sends lot of information to the web server which can not
be read directly because this information travel as a part of header of HTTP request. You can check HTTP
Protocol for more information on this.
Following is the important header information which comes from browser side and you would use very frequently
in web programming:
Header
Description
Accept
This header specifies the MIME types that the browser or other clients can handle.
Values of image/png or image/jpeg are the two most common possibilities.
Accept-Charset
This header specifies the character sets the browser can use to display the
information. For example ISO-8859-1.
Accept-Encoding
This header specifies the types of encodings that the browser knows how to
handle. Values of gzip or compress are the two most common possibilities.
Accept-Language
This header specifies the client's preferred languages in case the servlet can
produce results in more than one language. For example en, en-us, ru, etc.
Authorization
This header is used by clients to identify themselves when accessing passwordprotected Web pages.
Connection
This header indicates whether the client can handle persistent HTTP connections.
Persistent connections permit the client or other browser to retrieve multiple files
with a single request. A value ofKeep-Alive means that persistent connections
should be used
Content-Length
This header is applicable only to POST requests and gives the size of the POST
data in bytes.
Cookie
This header returns cookies to servers that previously sent them to the browser.
Host
This header specifies the host and port as given in the original URL.
If-Modified-Since
This header indicates that the client wants the page only if it has been changed
after the specified date. The server sends a code, 304 which means Not
Modified header if no newer result is available.
If-Unmodified-Since
This header is the reverse of If-Modified-Since; it specifies that the operation should
This header identifies the browser or other client making the request and can be
used to return different content to different types of browsers.
Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained in this
request.
HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a session, creates
one.
10
1
13
String getContextPath()
Returns the portion of the request URI that indicates the context of the request.
14
15
14
15
16
17
18
19
String getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET, POST, or
PUT.
String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does not exist.
String getPathInfo()
Returns any extra path information associated with the URL the client sent when it made this request.
String getProtocol()
Returns the name and version of the protocol the request.
String getQueryString()
Returns the query string that is contained in the request URL after the path.
String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent the request.
String getRemoteHost()
Returns the fully qualified name of the client that sent the request.
22
String getRemoteUser()
Returns the login of the user making this request, if the user has been authenticated, or null if the user has
not been authenticated.
23
String getRequestURI()
Returns the part of this request's URL from the protocol name up to the query string in the first line of the
HTTP request.
24
String getRequestedSessionId()
Returns the session ID specified by the client.
25
String getServletPath()
Returns the part of this request's URL that calls the JSP.
26
19
28
int getContentLength()
Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length
is not known.
29
30
int getServerPort()
Returns the port number on which this request was received.
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
%>
</table>
</center>
</body>
</html>
Now put the above code in main.jsp and try to access it. This would produce result something as follows:
Header Value(s)
accept
*/*
accept-language
en-us
user-agent
accept-encoding
gzip, deflate
host
localhost:8080
connection
Keep-Alive
cache-control
no-cache
To become more comfortable with other methods you can try few more above listed methods in the same fashion.
10
JSP Server Response
hen a Web server responds to a HTTP request to the browser, the response typically consists of a
status line, some response headers, a blank line, and the document. A typical response looks like this:
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and
a very short message corresponding to the status code (OK in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the browser from web
server side and you would use them very frequently in web programming:
Header
Description
Allow
This header specifies the request methods (GET, POST, etc.) that the server
supports.
Cache-Control
This header specifies the circumstances in which the response document can safely
be cached. It can have values public, private orno-cache etc. Public means
document is cacheable, Private means document is for a single user and can only
be stored in private (nonshared) caches and no-cache means document should
never be cached.
Connection
This header instructs the browser whether to use persistent in HTTP connections or
not. A value of close instructs the browser not to use persistent HTTP connections
and keep-alive means using persistent connections.
Content-Disposition
This header lets you request that the browser ask the user to save the response to
This header specifies the way in which the page was encoded during transmission.
Content-Language
This header signifies the language in which the document is written. For example en,
en-us, ru, etc.
Content-Length
This header indicates the number of bytes in the response. This information is
needed only if the browser is using a persistent (keep-alive) HTTP connection.
Content-Type
This header gives the MIME (Multipurpose Internet Mail Extension) type of the
response document.
Expires
This header specifies the time at which the content should be considered out-of-date
and thus no longer be cached.
Last-Modified
This header indicates when the document was last changed. The client can then
cache the document and supply a date by an If-Modified-Since request header in
later requests.
Location
This header should be included with all responses that have a status code in the
300s. This notifies the browser of the document address. The browser automatically
reconnects to this location and retrieves the new document.
Refresh
This header specifies how soon the browser should ask for an updated page. You
can specify time in number of seconds after which a page would be refreshed.
Retry-After
This header can be used in conjunction with a 503 (Service Unavailable) response
to tell the client how soon it can repeat its request.
Set-Cookie
Sets the content type of the response being sent to the client, if the response has not been committed yet.
void setDateHeader(String name, long date)
Sets a response header with the given name and date-value.
void setHeader(String name, String value)
Sets a response header with the given name and value.
void setIntHeader(String name, int value)
Sets a response header with the given name and integer value.
void setLocale(Locale loc)
Sets the locale of the response, if the response has not been committed yet.
void setStatus(int sc)
Sets the status code for this response.
</head>
<body>
<center>
<h2>Auto Refresh Header
Example</h2> <%
Set refresh, autoload time as 5 seconds
response.setIntHeader("Refresh", 5);
Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
out.println("Current Time is: " + CT + "\n");
%>
</center>
</body>
</html>
Now put the above code in main.jsp and try to access it. This would display current system time after every 5
seconds as follows. Just run the JSP and wait to see the result:
11
HTTP Status Codes
he format of the HTTP request and HTTP response messages are similar and will have following
structure:
An initial status line + CRLF ( Carriage Return + Line Feed ie. New Line )
Zero or more header lines + CRLF
A blank line ie. a CRLF
An optional message body like file, query data or query output.
For example, a server response header looks as follows:
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and
a very short message corresponding to the status code (OK in the example).
Following is a list of HTTP status codes and associated messages that might be returned from the Web Server:
Code: Message:
Description:
100
Continue
Only a part of the request has been received by the server, but as long as
it has not been rejected, the client should continue with the request
Switching Protocols
101
200
OK
The request is OK
201
Created
202
Accepted
The request is accepted for processing, but the processing is not complete.
203
Non-authoritative
Information
204
No Content
205
Reset Content
206
Partial Content
300
Multiple Choices
A link list. The user can select a link and go to that location. Maximum five
addresses
301
Moved Permanently
302
Found
303
See Other
304
Not Modified
305
Use Proxy
306
Unused
This code was used in a previous version. It is no longer used, but the
code is reserved.
307
Temporary Redirect
400
Bad Request
401
Unauthorized
402
Payment Required
403
Forbidden
404
Not Found
405
406
Not Acceptable
The server can only generate a response that is not accepted by the client.
407
Proxy Authentication
Required
You must authenticate with a proxy server before this request can be
served.
408
Request Timeout
The request took longer than the server was prepared to wait.
409
Conflict
410
Gone
Length Required
The "Content-Length" is not defined. The server will not accept the request
without it.
Precondition Failed
The server will not accept the request, because the request entity is too
large.
The server will not accept the request, because the url is too long. Occurs
411
412
413
414
when you convert a "post" request to a "get" request with a long query
information.
415
The server will not accept the request, because the media type is not
supported.
417
Expectation Failed
500
The request was not completed. The server met an unexpected condition
Not Implemented
The request was not completed. The server did not support the
functionality required.
Bad Gateway
The request was not completed. The server received an invalid response
from the upstream server
Service Unavailable
504
Gateway Timeout
505
501
502
503
APACHE TOMCAT/5.5.29
To become more comfortable with HTTP status codes, try to set different status codes and their description.
CHAPTER
12
JSP Form Processing
ou must have come across many situations when you need to pass some information from your browser
to web server and ultimately to your backend program. The browser uses two methods to pass this information to
web server. These methods are GET Method and POST Method.
GET method:
The GET method sends the encoded user information appended to the page request. The page and the encoded
information are separated by the ? character as follows:
http://www.test.com/hello?key1=value1&key2=value2
The GET method is the default method to pass information from browser to web server and it produces a long
string that appears in your browser's Location:box. Never use the GET method if you have password or other
sensitive information to pass to the server.
The GET method has size limitation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING
environment variable which can be handled using getQueryString() and getParameter() methods of request
object.
POST method:
A generally more reliable method of passing information to a backend program is the POST method.
This method packages the information in exactly the same way as GET methods, but instead of sending it as a
text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in
the form of the standard input which you can parse and use for your processing.
JSP handles this type of requests using getParameter() method to read simple parameters and getInputStream()
method to read binary data stream coming from the client.
getParameter(): You call request.getParameter() method to get the value of a form parameter.
getParameterValues(): Call this method if the parameter appears more than once and returns multiple
values, for example checkbox.
getParameterNames(): Call this method if you want a complete list of all parameters in the current request.
getInputStream(): Call this method to read binary data stream coming from the client.
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Now type http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI in your browser's Location:box. This
would generate following result:
Keep this HTML in a file Hello.htm and put it in <Tomcat-installation-directory>/webapps/ROOT directory. When
you would access http://localhost:8080/Hello.htm, here is the actual output of the above form.
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button to see the result on your local machine where
tomcat is running. Based on the input provided, it will generate similar result as mentioned in the above example.
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Following is the content of Hello.htm file:
<html>
<body>
<form action="main.jsp" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Now let us keep main.jsp and hello.htm in <Tomcat-installation-directory>/webapps/ROOT directory. When you
would access http://localhost:8080/Hello.htm, below is the actual output of the above form.
First Name:
Last Name:
Try to enter First and Last Name and then click submit button to see the result on your local machine where
tomcat is running.
Based on the input provided, it would generate similar result as mentioned in the above examples.
Physics
Chemistry
Below is main.jsp JSP program to handle input given by web browser for checkbox button.
<html>
<head>
<title>Reading Checkbox
Data</title> </head>
<body>
<center>
<h1>Reading Checkbox Data</h1>
<ul>
<li><p><b>Maths Flag:</b>
<%= request.getParameter("maths")%>
</p></li>
<li><p><b>Physics Flag:</b>
<%= request.getParameter("physics")%>
</p></li>
<li><p><b>Chemistry Flag:</b>
<%= request.getParameter("chemistry")%>
</p></li>
</ul>
</body>
</html>
%>
</table>
</center>
</body>
</html>
Following is the content of Hello.htm:
<html>
<body>
<form action="main.jsp" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> Chem
<input type="submit" value="Select Subject" />
</form>
</body>
</html>
Now try calling JSP using above Hello.htm, this would generate a result something like as below based on the
provided input:
Param Value(s)
maths
on
chemistry
on
You can try above JSP to read any other form's data which is having other objects like text box, radio button or
drop down box etc.
JSP Filters
ervlet and JSP Filters are Java classes that can be used in Servlet and JSP Programming for the
following purposes:
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.
There are various types of filters suggested by the specifications:
Authentication Filters.
Data compression Filters
Encryption Filters .
Filters that trigger resource access events.
Image Conversion Filters .
Logging and Auditing Filters.
MIME-TYPE Chain Filters.
Tokenizing Filters .
XSL/T Filters That Transform XML Content.
Filters are deployed in the deployment descriptor file web.xml and then map to either servlet or JSP names or
URL patterns in your application's deployment descriptor. The deployment descriptor file web.xml can be found in
<Tomcat-installation-directory>\conf directory.
When the JSP container starts up your web application, it creates an instance of each filter that you have declared
in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.
This method is called by the web container to indicate to a filter that it is being placed into service.
public void destroy()
This method is called by the web container to indicate to a filter that it is being taken out of service.
java
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws java.io.IOException, ServletException {
\ Get the IP address of client machine.
String ipAddress = request.getRemoteAddr();
\ Log the IP address and current timestamp.
System.out.println("IP "+ ipAddress + ", Time "
new Date().toString());
\
Pass request back down the filter chain
chain.doFilter(request,response);
}
public void destroy( ){
/* Called before the Filter instance is removed
from service by the web container*/
}
}
Compile LogFilter.java in usual way and put your LogFilter.class class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The above filter would apply to all the servlets and JSP because we specified /* in our configuration. You can
specify a particular servlet or JSP path if you want to apply filter on few servlets or JSP only.
Now try to call any servlet or JSP in usual way and you would see generated log in you web server log. You can
use Log4J logger to log above log in a separate file.
onsider a webpage which is displaying live game score or stock market status or currency exchange
ration. For all such type of pages, you would need to refresh your web page regularly using refresh or reload
button with your browser.
JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it
would refresh automatically after a given interval.
The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the
signature of this method:
public void setIntHeader(String header, int headerValue)
This method sends back header "Refresh" to the browser along with an integer value which indicates time interval
in seconds.
am_pm = "AM";
else
am_pm = "PM";
%>
</center>
</body>
</html>
Now put the above code in main.jsp and try to access it. This would display current system time after every 5
seconds as follows. Just run the JSP and wait to see the result:
his chapter assumes you have good understanding on how JDBC application works. Before starting with
database access through a JSP, make sure you have proper JDBC environment setup along with a database.
For more detail on how to access database using JDBC and its environment setup you can go through our JDBC
Tutorial.
To start with basic concept, let us create a simple table and create few records in that table as follows:
Create Table
To create the Employees table in EMP database, use the following steps:
Step 1:
SELECT Operation:
Following example shows how we can execute SQL SELECT statement using JTSL in JSP programming:
<%@
<%@
<%@
<%@
page import="java.io.*,java.util.*,java.sql.*"%>
page import="javax.servlet.http.*,javax.servlet.*" %>
taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>SELECT Operation</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>
</sql:query>
<table border="1"
width="100%"> <tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="$
{result.rows}"> <tr>
<td><c:out
<td><c:out
<td><c:out
<td><c:out
</tr>
value="${row.id}"/></td>
value="${row.first}"/></td>
value="${row.last}"/></td>
value="${row.age}"/></td>
</c:forEach>
</table>
</body>
</html>
Now try to access above JSP, which should display the following result:
Emp ID
First Name
Last Name
Age
100
Zara
Ali
18
101
Mahnaz
Fatma
25
102
Zaid
Khan
30
103
Sumit
Mittal
28
INSERT Operation:
Following example shows how we can execute SQL INSERT statement using JTSL in JSP programming:
<%@
<%@
<%@
<%@
page import="java.io.*,java.util.*,java.sql.*"%>
page import="javax.servlet.http.*,javax.servlet.*" %>
taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>JINSERT Operation</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>
</sql:update>
<sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees;
</sql:query>
<table border="1"
width="100%"> <tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="$
{result.rows}"> <tr>
<td><c:out value="${row.id}"/></td>
<td><c:out
value="${row.first}"/></td>
<td><c:out
value="${row.last}"/></td>
<td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
Now try to access above JSP, which should display the following result:
Emp ID
First Name
Last Name
Age
100
Zara
Ali
18
101
Mahnaz
Fatma
25
102
Zaid
Khan
30
103
Sumit
Mittal
28
104
Nuha
Ali
DELETE Operation:
Following example shows how we can execute SQL DELETE statement using JTSL in JSP programming:
<%@
<%@
<%@
<%@
page import="java.io.*,java.util.*,java.sql.*"%>
page import="javax.servlet.http.*,javax.servlet.*" %>
taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>DELETE Operation</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>
</sql:update>
<sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees;
</sql:query>
<table border="1"
width="100%"> <tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="$
{result.rows}"> <tr>
<td><c:out
<td><c:out
<td><c:out
<td><c:out
</tr>
</c:forEach>
</table>
value="${row.id}"/></td>
value="${row.first}"/></td>
value="${row.last}"/></td>
value="${row.age}"/></td>
</body>
</html>
Now try to access above JSP, which should display the following result:
Emp ID
First Name
Last Name
Age
100
Zara
Ali
18
101
Mahnaz
Fatma
25
102
Zaid
Khan
30
UPDATE Operation:
Following example shows how we can execute SQL UPDATE statement using JTSL in JSP programming:
<%@
<%@
<%@
<%@
page import="java.io.*,java.util.*,java.sql.*"%>
page import="javax.servlet.http.*,javax.servlet.*" %>
taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>DELETE Operation</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>
</sql:update>
<sql:query dataSource="${snapshot}" var="result">
</sql:query>
<table border="1"
width="100%"> <tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="$
{result.rows}"> <tr>
<td><c:out
<td><c:out
<td><c:out
<td><c:out
</tr>
</c:forEach>
</table>
value="${row.id}"/></td>
value="${row.first}"/></td>
value="${row.last}"/></td>
value="${row.age}"/></td>
</body>
</html>
Now try to access above JSP, which should display the following result:
Emp ID
First Name
Last Name
Age
100
Zara
Ali
18
101
Mahnaz
Fatma
25
102
Zaid
Ali
30
Hibernate
Tutorial
ORM Overview
databases from Java program. These Java APIs enables Java programs to execute SQL statements and interact
with any SQL compliant database.
JDBC provides a flexible architecture to write a database independent application that can run on different
platforms and interact with different DBMS without any modification.
Cons of JDBC
Complex if it is used in large projects
No encapsulation
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public String getFirstName() {
return first_name;
}
public String getLastName() {
return last_name;
}
public int getSalary() {
return salary;
}
}
Mismatch
Description
Granularity
Sometimes you will have an object model which has more classes than the
number of corresponding tables in the database.
Inheritance
Identity
A RDBMS defines exactly one notion of 'sameness': the primary key. Java,
however, defines both object identity (a==b) and object equality (a.equals(b)).
Associations
Navigation
The ways you access objects in Java and in a RDBMS are fundamentally different.
The Object-Relational Mapping (ORM) is the solution to handle all the above impedance mismatches.
What is ORM?
ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between
relational databases and object oriented programming languages such as Java, C# etc. An ORM system has
following advantages over plain JDBC
S.N. Advantages
1
A language or API to specify queries that refer to classes and properties of classes.
Hibernate Overview
ibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source
persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational
Persistence and Query service for any Java Application.
Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the
developer from 95% of common data persistence related programming tasks.
Hibernate sits between traditional Java objects and database server to handle all the work in persisting those
objects based on the appropriate O/R mechanisms and patterns.
Hibernate Advantages
Hibernate takes care of mapping Java classes to database tables using XML files and without writing any
line of code.
Provides simple APIs for storing and retrieving Java objects directly to and from the database.
If there is change in Database or in any table then the only need to change XML file properties.
Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.
Hibernate does not require an application server to operate.
Manipulates Complex associations of objects of your database.
Supported Databases
Hibernate supports almost all the major RDBMS. Following is list of few of the database engines supported by
Hibernate.
HSQL Database Engine
DB2/NT
MySQL
PostgreSQL
FrontBase
Oracle
Microsoft SQL Server Database
Sybase SQL Server
Informix Dynamic Server
Supported Technologies
Hibernate supports a variety of other technologies, including the following:
XDoclet Spring
J2EE
Eclipse plug-ins
Maven
Hibernate Architecture
he Hibernate architecture is layered to keep you isolated from having to know the underlying APIs.
Hibernate makes use of the database and configuration data to provide persistence services (and persistent
objects) to the application.
Following is a very high level view of the Hibernate Application Architecture.
Following is a detailed view of the Hibernate Application Architecture with few important core classes.
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 common to relational
databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow
Hibernate to be integrated with J2EE application servers.
Following section gives brief description of each of the class objects involved in Hibernate Application
Architecture.
Configuration Object
The Configuration object is the first Hibernate object you create in any Hibernate application and usually created
only once during application initialization. It represents a configuration or properties file required by the Hibernate.
The Configuration object provides two keys components:
Database Connection: This is handled through one or more configuration files supported by Hibernate.
These files are hibernate.properties and hibernate.cfg.xml.
Class Mapping Setup: This component creates the connection between the Java classes and database
tables.
SessionFactory Object
Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the
application using the supplied configuration file and allows for a Session object to be instantiated. The
SessionFactory is a thread safe object and used by all the threads of an application.
The SessionFactory is heavyweight object so usually it is created during application start up and kept for later
use. You would need one SessionFactory object per database using a separate configuration file. So if you are
using multiple databases then you would have to create multiple SessionFactory objects.
Session Object
A Session is used to get a physical connection with a database. The Session object is lightweight and designed to
be instantiated each time an interaction is needed with the database. Persistent objects are 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 and they
should be created and destroyed them as needed.
Transaction Object
A Transaction represents a unit of work with the database and most of the RDBMS supports transaction
functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from
JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface, instead managing
transactions in their own application code.
Query Object
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create
objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and
finally to execute the query.
Criteria Object
Criteria object are used to create and execute object oriented criteria queries to retrieve objects.
Hibernate Environment
his chapter will explain how to install Hibernate and other associated packages to prepare a develop
environment for the Hibernate applications. We will work with MySQL database to experiment with Hibernate
examples, so make sure you already have setup for MySQL database. For a more detail on MySQL you can
check our MySQL Tutorial.
Downloading Hibernate:
It is assumed that you already have latest version of Java is installed on your machine. Following are the simple
steps to download and install Hibernate on your machine.
Make a choice whether you want to install Hibernate on Windows, or Unix and then proceed to the next
step to download .zip file for windows and .tz file for Unix.
Download the latest version of Hibernate from http://www.hibernate.org/downloads.
At the time of writing this tutorial I downloaded hibernate-distribution-3.6.4.Final and when you unzip
the downloaded file it will give you directory structure as follows.
Installing Hibernate
Once you downloaded and unzipped the latest version of the Hibernate Installation file, you need to perform
following two simple steps. Make sure you are setting your CLASSPATH variable properly otherwise you will face
problem while compiling your application.
Now copy all the library files from /lib into your CLASSPATH, and change your classpath variable to
include all the JARs:
Finally copy hibernate3.jar file into your CLASSPATH. This file lies in the root directory of the installation
and is the primary JAR that Hibernate needs to do its work.
Hibernate Prerequisites
Following is the list of the packages/libraries required by Hibernate and you should install them before starting
with Hibernate. To install these packages you would have to copy library files from /lib into your CLASSPATH, and
change your CLASSPATH variable accordingly.
S.N.
Packages/Libraries
Hibernate Configuration
ibernate 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 related to database
and other related parameters. All such information is usually supplied as a standard Java properties file called
hibernate.properties, or as an XML file named hibernate.cfg.xml.
I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate properties in my examples.
Most of the properties take their default values and it is not required to specify them in the property file unless it is
really required. This file is kept in the root directory of your application's classpath.
Hibernate Properties
Following is the list of important properties you would require to configure for a databases in a standalone
situation:
S.N. Properties and Description
1
hibernate.dialect
This property makes Hibernate generate the appropriate SQL for the chosen database.
2
hibernate.connection.driver_class
The JDBC driver class.
3
hibernate.connection.url
The JDBC URL to the database instance.
4
hibernate.connection.username
The database username.
5
hibernate.connection.password
The database password.
6
hibernate.connection.pool_size
Limits the number of connections waiting in the Hibernate database connection pool.
7
hibernate.connection.autocommit
Allows autocommit mode to be used for the JDBC connection.
If you are using a database along with an application server and JNDI then you would have to configure the
following properties:
hibernate.jndi.<JNDIpropertyname>
Passes any JNDI property you like to the JNDI InitialContext.
hibernate.jndi.url
Provides the URL for JNDI.
hibernate.connection.username
The database username.
hibernate.connection.password
The database password.
The above configuration file includes <mapping> tags which are related to hibernate-mapping file and we will see
in next chapter what exactly is a hibernate mapping file and how and why do we use it. Following is the list of
various important databases dialect property type:
Database
Dialect Property
DB2
org.hibernate.dialect.DB2Dialect
HSQLDB
org.hibernate.dialect.HSQLDialect
HypersonicSQL
org.hibernate.dialect.HSQLDialect
Informix
org.hibernate.dialect.InformixDialect
Ingres
org.hibernate.dialect.IngresDialect
Interbase
org.hibernate.dialect.InterbaseDialect
org.hibernate.dialect.SQLServerDialect
org.hibernate.dialect.SQLServer2005Dialect
org.hibernate.dialect.SQLServer2008Dialect
MySQL
org.hibernate.dialect.MySQLDialect
org.hibernate.dialect.OracleDialect
Oracle 11g
org.hibernate.dialect.Oracle10gDialect
Oracle 10g
org.hibernate.dialect.Oracle10gDialect
Oracle 9i
org.hibernate.dialect.Oracle9iDialect
PostgreSQL
org.hibernate.dialect.PostgreSQLDialect
Progress
org.hibernate.dialect.ProgressDialect
SAP DB
org.hibernate.dialect.SAPDBDialect
Sybase
org.hibernate.dialect.SybaseDialect
Sybase Anywhere
org.hibernate.dialect.SybaseAnywhereDialect
Serial No
Class Name
Functionality
Assert
TestCase
TestResult
TestSuite
Hibernate Sessions
Session is used to get a physical connection with a database. The Session object is lightweight and
designed to be instantiated each time an interaction is needed with the database. Persistent objects are 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 and they
should be created and destroyed them as needed. The main function of the Session is to offer create, read and
delete operations for instances of mapped entity classes. Instances may exist in one of the following three states
at a given point in time:
transient: A new instance of a a persistent class which is not associated with a Session and has no
representation in the database and no identifier value is considered transient by Hibernate.
persistent: You can make a transient instance persistent by associating it with a Session. A persistent
instance has a representation in the database, an identifier value and is associated with a Session.
detached: Once we close the Hibernate Session, the persistent instance will become a detached
instance.
A Session instance is serializable if its persistent classes are serializable. A typical transaction should use the
following idiom:
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// do some work
...
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
If the Session throws an exception, the transaction must be rolled back and the session must be discarded.
20
boolean isOpen()
23
24
21
22
Update the persistent instance with the identifier of the given detached instance.
Update the persistent instance with the identifier of the given detached instance.
Hibernate Persistent
Class
he entire concept of Hibernate is to take the values from Java class attributes and persist
them to a
database table. A mapping document helps Hibernate in determining how to pull the values from
the classes and map them with table and associated fields.
Java classes whose objects or instances will be stored in database tables are called persistent
classes in Hibernate. Hibernate works best if these classes follow some simple rules, also known
as the Plain Old Java Object (POJO) programming model. There are following main rules of
persistent classes, however, none of these rules are hard requirements.
All Java classes that will be persisted need a default constructor.
All classes should contain an ID in order to allow easy identification of your objects within
Hibernate and the database. This property maps to the primary key column of a database
table.
All attributes that will be persisted should be declared private and have getXXX and
setXXXmethods defined in the JavaBean style.
A central feature of Hibernate, proxies, depends upon the persistent class being either
non-final, or the implementation of an interface that declares all public methods.
All classes that do not extend or implement some specialized classes and interfaces
required by the EJB framework.
The POJO name is used to emphasize that a given object is an ordinary Java Object, not a special
object, and in particular not an Enterprise JavaBean.
n Object/relational mappings are usually defined in an XML document. This mapping file
instructs
Hibernate how to map the defined class or classes to the database tables.
Though many Hibernate users choose to write the XML by hand, a number of tools exist to
generate the mapping document. These include XDoclet, Middlegen and AndroMDA for
advanced Hibernate users.
You should save the mapping document in a file with the format <classname>.hbm.xml. We saved
our mapping document in the file Employee.hbm.xml. Let us see little detail about the mapping
elements used in the mapping file:
The mapping document is an XML document having <hibernate-mapping> as the root
element which contains all the <class> elements.
The <class> elements are used to define specific mappings from a Java classes to the
database tables. The Java class name is specified using the name attribute of the class
element and the database table name is specified using the table attribute.
The <meta> element is optional element and can be used to create the class description.
The <id> element maps the unique ID attribute in class to the primary key of the database
table.
The name attribute of the id element refers to the property in the class and the column
attribute refers to
the column in the database table. The type attribute holds the hibernate mapping type,
this mapping
types will convert from Java to SQL data type.
The <generator> element within the id element is used to automatically generate the
primary key values. Set the class attribute of the generator element is set to native to let
hibernate pick up
either identity, sequence or hilo algorithm to create primary key depending upon the
capabilities of the
underlying database.
The <property> element is used to map a Java class property to a column in the database
table.
The name attribute of the element refers to the property in the class and the column
attribute refers to
the column in the database table. The type attribute holds the hibernate mapping type, this
mapping
types will convert from Java to SQL data type.
There are other attributes and elements available which will be used in a mapping document and I
would try to cover as many as possible while discussing other Hibernate related topics.
9
Hibernate Mapping
Types
hen you prepare a Hibernate mapping document, we have seen that you map Java
Primitive types
Mapping type
Java type
integer
int or java.lang.Integer
INTEGER
long
long or java.lang.Long
BIGINT
short
short or java.lang.Short
SMALLINT
float
float or java.lang.Float
FLOAT
double
double or java.lang.Double
DOUBLE
big_decimal
java.math.BigDecimal
NUMERIC
character
java.lang.String
CHAR(1)
string
java.lang.String
VARCHAR
byte
byte or java.lang.Byte
TINYINT
boolean
boolean or java.lang.Boolean
BIT
yes/no
boolean or java.lang.Boolean
CHAR(1) ('Y' or
'N')
true/false
boolean or java.lang.Boolean
CHAR(1) ('T' or
'F')
Java type
date
java.util.Date or java.sql.Date
DATE
time
java.util.Date or java.sql.Time
TIME
timestamp
java.util.Date or java.sql.Timestamp
TIMESTAMP
calendar
java.util.Calendar
TIMESTAMP
calendar_date
java.util.Calendar
DATE
Java type
binary
byte[]
VARBINARY (or
BLOB)
text
java.lang.String
CLOB
serializable
VARBINARY (or
BLOB)
clob
java.sql.Clob
CLOB
blob
java.sql.Blob
BLOB
JDK-related types
Mapping type
Java type
class
java.lang.Class
VARCHAR
locale
java.util.Locale
VARCHAR
timezone
java.util.TimeZone
VARCHAR
currency
java.util.Currency
VARCHAR
o far we have seen very basic O/R mapping using hibernate but there are three most important mapping
topics which we have to learn in detail. These are the mapping of collections, the mapping of associations
between entity classes and Component Mappings.
Collections Mappings
If an entity or class has collection of values for a particular variable, then we can map those values using any one
of the collection interfaces available in java. Hibernate can persist instances ofjava.util.Map, java.util.Set,
java.util.SortedMap, java.util.SortedSet, java.util.List, and any array of persistent entities or values.
Collection type
java.util.Set
java.util.SortedSet
java.util.List
java.util.Collection
java.util.Map
java.util.SortedMap
Arrays are supported by Hibernate with <primitive-array> for Java primitive value types and <array> for everything
else. However, they are rarely used so I'm not going to discuss them in this tutorial.
If you want to map a user defined collection interfaces which is not directly supported by Hibernate, you need to
tell Hibernate about the semantics of your custom collections which is not very easy and not recommend to be
used.
implement both the equals() and hashCode() methods so that Java can determine whether any two
elements/objects are identical.
A Set is mapped with a <set> element in the mapping table and initialized with java.util.HashSet. You can use
Set collection in your class when there is no duplicate element required in the collection.
</id>
<set name="certificates" cascade="all">
<key column="employee_id"/> <one-tomany class="Certificate"/>
</set>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</id>
<property name="name" column="certificate_name" type="string"/>
</class>
</hibernate-mapping>
You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping
document in the file Employee.hbm.xml. You are already familiar with most of the mapping detail but let us see all
the elements of mapping file once again:
The mapping document is an XML document having <hibernate-mapping> as the root element which
contains two <class> elements corresponding to each class.
The <class> elements are used to define specific mappings from a Java classes to the database tables. The
Java class name is specified using the name attribute of the class element and the database table name is
specified using the table attribute.
The <meta> element is optional element and can be used to create the class description.
The <id> element maps the unique ID attribute in class to the primary key of the database table. The name
attribute of the id element refers to the property in the class and the column attribute refers to the column in
the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from
Java to SQL data type.
The <generator> element within the id element is used to automatically generate the primary key values. Set
the class attribute of the generator element is set to native to let hibernate pick up either identity, sequence
or hilo algorithm to create primary key depending upon the capabilities of the underlying database.
The <property> element is used to map a Java class property to a column in the database table. The name
attribute of the element refers to the property in the class and the column attribute refers to the column in the
database table. The type attribute holds the hibernate mapping type, this mapping types will convert from
Java to SQL data type.
The <set> element is new here and has been introduced to set the relationship between Certificate and
Employee classes. We used the cascade attribute in the <set> element to tell Hibernate to persist the
Certificate objects at the same time as the Employee objects. The nameattribute is set to the defined Set
variable in the parent class, in our case it is certificates. For each set variable, we need to define a separate
set element in the mapping file.
The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object ie.
table EMPLOYEE.
The <one-to-many> element indicates that one Employee object relates to many Certificate objects and, as
such, the Certificate object must have a Employee parent associated with it. You can use either <one-toone>, <many-to-one> or <many-to-many> elements based on your requirement.
);
Further, assume each employee can have one or more certificate associated with him/her. So we will store
certificate related information in a separate table which has following structure:
create table CERTIFICATE (
id INT NOT NULL auto_increment,
certificate_name VARCHAR(30) default
NULL, employee_id INT default NULL,
PRIMARY KEY (id)
);
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
public List getCertificates() {
return certificates;
}
public void setCertificates( List certificates ) {
this.certificates = certificates;
}
}
We need to define another POJO class corresponding to CERTIFICATE table so that certificate objects can be
stored and retrieved into the CERTIFICATE table.
public class Certificate{
private int id;
private String name;
public Certificate() {}
public Certificate(String name)
{ this.name = name;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
}
</id>
<list name="certificates" cascade="all">
<key column="employee_id"/> <listindex column="idx"/> <one-to-many
class="Certificate"/>
</list>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</id>
<property name="name" column="certificate_name" type="string"/>
</class>
</hibernate-mapping>
You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping
document in the file Employee.hbm.xml. You are already familiar with most of the mapping detail but let us see all
the elements of mapping file once again:
The mapping document is an XML document having <hibernate-mapping> as the root element which
contains two <class> elements corresponding to each class.
The <class> elements are used to define specific mappings from a Java classes to the database tables. The
Java class name is specified using the name attribute of the class element and the database table name is
specified using the table attribute.
The <meta> element is optional element and can be used to create the class description.
The <id> element maps the unique ID attribute in class to the primary key of the database table. The name
attribute of the id element refers to the property in the class and the column attribute refers to the column in
the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from
Java to SQL data type.
The <generator> element within the id element is used to automatically generate the primary key values. Set
the class attribute of the generator element is set to native to let hibernate pick up either identity,
sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.
Finally, we will create our application class with the main() method to run the application. We will use this
application to save few Employee's records alongwith their certificates and then we will apply CRUD operations on
those records.
import java.util.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
}
ManageEmployee ME = new ManageEmployee();
/* Let us have a set of certificates for the first employee */
ArrayList set1 = new ArrayList();
set1.add(new
Certificate("MCA"));
set1.add(new
Certificate("MBA"));
set1.add(new Certificate("PMP"));
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator1 =
employees.iterator(); iterator1.hasNext();){
Employee employee = (Employee) iterator1.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary()); List
certificates = employee.getCertificates();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to delete an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
Salary: 4000
Salary: 3000
Salary: 5000
If you check your EMPLOYEE and CERTIFICATE tables, they should have following records:
select*
mysql>
from
EMPLOYEE;
-------
---+
----+
+
first_
| id |
----+ ------------+ -----------+
K
u
m
a
| 51 |
|
r
----+ ------------+ -----------+
1
row in set (0.00 sec)
name |
mysql>
select* from CERTIFICATE;
----------------+
-----+
-----+
| id |
certificate_name | idx
----------------+
-----+
-----+
|
|
|
|
|
|
+---- +----------------------+
inset
3
sec
6 |
7 |
8 |
rows
+
--------+
last_name | salary |
+
--------+
|
--------+
5000 |
+
+
| employee_id |
-------------+
-------------+
0 |
1 |
2 |
+-------------
+
51 |
51 |
51 |
+
0.00
mysql>
Alternatively, you could map a Java array instead of a list. A array mapping is virtually identical to the previous
example, except with different element and attribute names (<array> and <array-index>). However, for reasons
explained earlier, Hibernate applications rarely use arrays.
Hibernate Interceptors
s you have learnt that in Hibernate, an object will be created and persisted. Once the object has been
changed, it must be saved back to the database. This process continues until the next time the object is needed,
and it will be loaded from the persistent store.
Thus an object passes through different stages in its life cycle and Interceptor Interface provides methods which
can be called at different stages to perform some required tasks. These methods are callbacks from the session
to the application, allowing the application to inspect and/or manipulate properties of a persistent object before it is
saved, updated, deleted or loaded. Following is the list of all the methods available within the Interceptor interface:
S.N. Method and Description
1
findDirty()
This method is be called when the flush() method is called on a Session object.
instantiate()
This method is called when a persisted class is instantiated.
isUnsaved()
This method is called when an object is passed to the saveOrUpdate() method/
onDelete()
This method is called before an object is deleted.
onFlushDirty()
5 This method is called when Hibernate detects that an object is dirty (ie. have been
changed) during a flush i.e. update operation.
6
onLoad()
This method is called before an object is initialized.
onSave()
This method is called before an object is saved.
postFlush()
8 This method is called after a flush has occurred and an object has been updated in
memory.
9
preFlush()
This method is called before a flush.
Hibernate Interceptor gives us total control over how an object will look to both the application and the database.
Create Interceptors
We will extend EmptyInterceptor in our example where Interceptor's method will be called automatically when
Employee object is created and updated. You can implement more methods as per your requirements.
import java.io.Serializable;
import java.util.Date; import
java.util.Iterator;
import org.hibernate.EmptyInterceptor;
import org.hibernate.Transaction; import
org.hibernate.type.Type;
// do nothing
}
// This method is called when Employee object gets updated.
public boolean onFlushDirty(Object entity,
Serializable id,
Object[] currentState,
Object[] previousState,
String[] propertyNames,
Type[] types) {
if ( entity instanceof Employee ) {
System.out.println("Update
Operation"); return true;
}
return false;
}
public boolean onLoad(Object entity,
Serializable id,
Object[] state, String[]
propertyNames, Type[]
types) {
// do nothing
return true;
}
// This method is called when Employee object gets created.
public boolean onSave(Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types) {
if ( entity instanceof Employee ) {
System.out.println("Create
Operation"); return true;
}
return false;
}
//called before commit into database
public void preFlush(Iterator iterator) {
System.out.println("preFlush");
}
//called after committed into database
public void postFlush(Iterator iterator) {
System.out.println("postFlush");
}
}
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
);
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
</id>
try{
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession( new MyInterceptor() );
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession( new MyInterceptor() );
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
Salary: 10000
+------------
+-----------
| id | first_name | last_name
-----------------+
+
-+
| 29 | Zara
| Ali
| 31 | John
| Paul
-----------------+
+
-+
2 rows in set (0.00 sec
mysql>
+
| salary |
+--------
------+
+
|
5000 |
|
10000 |
------+