Professional Documents
Culture Documents
JavaJazzUp Team Java News and Updates section provides the latest
updates of the things happening around the globe
making the readers aware of the java technological
advancement. In this section, you will know the new
Editor-in-Chief
features introduced in the existing tools, utilities,
application servers, IDEs, along with the Java API
Deepak Kumar updates.
Editor-in-Chief
Deepak Kumar
Java Jazz up
“Free”
07 Java Developers Desk: Annotations| Sun Microsystem added the features like
annotation to make the development easier and more efficient in jdk 5. The main
objective to develop the annotations is to make the development easier
13 JBoss Application Server| JBoss is a free, open source application server under the LGPL
license that is widely used for developing and deploying enterprise Java applications (J2EE),
Web applications, and Portals.
15 EJB 3.0 | Enterprise beans are the Java EE server side components that run inside the ejb
container and encapsulate the business logic of an enterprise application. Enterprise applications
are the software applications developed intended to use at large scale.
23 XML and JAXP | “XML is a cross-platform, software and hardware independent tool for
transmittingin formation”
36 Hibernate with Annotation |The Java 5 version has introduced a powerful way to provide
the metadata to the JVM. The mechanism is known as Annotations.
39 Introduction to Ant |Ant is a platform-independent build tool that specially supports for the
Java programming language.
42 Struts2 Data Tags | Apache Struts is an open-source framework used to develop Java web
applications. We started introducing struts generic tags in the November issue. In this section,
we will continue further with the data tags (generic tags) provided with struts 2 framework
and the rest will be included in the subsequent issues of the magazine.
51 Integrating JSF, Spring and Hibernate | This article explains integrating JSF (MyFaces),
Spring and Hibernate to build real world User Login and Registration Application using
MySQL as database. This application lets the new user create an account and existing user
access the application by user name and password.
77 Facelet| Facelet is a view technology for Java Server Faces (JSF) that allows building composite
views more quickly and easily than with JSP which is the default view technology for JSF. JSP
pages are compiled into servlets but it’s not the case with Facelets because Facelet pages are
XML compliant and its framework uses a fast SAXbased compiler to build views
90 Design Patterns | Behavioral Patterns Behavioral patterns are those patterns, which are
specifically concerned with communication (interaction) between the objects. The interactions
between the objects should be such that they are talking to each other and are still loosely
coupled.
96 Tips & Tricks| Copy content from one file to another This example explains how to copy
contents from one file to another file. Copy file is one of the good use of io package of Java.
The logic of program is explained below:
104 Advertise with Us | We are the top most providers of technology stuffs to the java community.
It is Secunia’s ambition to be the leading Now the plug-ins for dynamic languages are
vulnerability intelligence provider and distributor available. Recently JetBrains has unveiled the
in the world - second to none. plug-ins that allows the users of its IntelliJ Idea
IDE to accommodate Groovy and Ruby
They have detected few of the vulnerability in programming.
the Sun Java System Web Proxy Server, These
vulnerabilities can be exploited by malicious The IDE highly supports java development, is
people to conduct cross-site scripting attacks. on the way of expansion to accommodate newly
popular dynamic languages. To meet the
A such kind of vulnerability is reported in 4.x purpose, JetBrains is offering its JetGroovy
versions prior to 4.0.6. It is being illustrated Plugin 1.0 for Groovy and Grails framework
through an example: Input passed via developers. It is also available for Ruby
unspecified parameters within the View Error development as the Ruby Plugin 1.0.
Log functionality is not properly sanitized before
being returned to the user. This can be IV. Spring Integration: a central service and
exploited to execute arbitrary HTML and script message bus
code in a user’s browser session in context of Recently, SpringSource announced the creation
an affected site. of Spring Integration, a project aimed to provide
a central service and message bus inside the
Solution is just to update Sun Java System Spring Framework. This is built on the Spring’s
Web Proxy Server 4.x to version 4.0.6. already-impressive capabilities for providing
simple models for using services. Spring
Integration is a logical next step for Spring, as
it already provides services for JMS, remoting, freeing you to focus on the actual content.
scheduling, email, lifecycle management, Furthermore, its layout engine ensures that
transaction management, event publication and every diagram is visually pleasing and
subscription, and transaction management. structurally correct. Trace Modeler also offers
a couple of unique features like inlining message
The benefit is that a Spring configuration can calls, splitting activations, smart flow-based
manage all of the communication protocol, such comment connectors, right-to-left diagram
that the service barely has to know it’s a service layout and full bidi-text support for non-
for an ESB at all. Western scripts, control flow highlighting,
automatic object lifetimes.
Suppose there is spell mistake in the method method any more. On compiling the class
name such as the name is changed from Depricated_method does not generate any
toString to toStrimg. Then on compiling the error. While compiling the class
code will generate the message like this: Test_Deprication generates the message like
Compiling 1 source file to D:tempNew Folder this:
(2) Compiling 1 source file to D:tempNew Folder
TestJavaApplication1buildclasses (2)TestJavaApplication1buildclasses
D:tempNew Folder D:tempNew Folder
(2)TestJavaApplication1srctest (2)TestJavaApplication1srctestmyannotation
myannotationTest_Override.java:24: method Test_Deprication.java:27:
does not override a method from its warning: [deprecation] showSomething() in
superclass test.myannotation.Deprecated_method has
@Override been deprecated
1 error d.showSomething();
BUILD FAILED (total time: 0 seconds) 1 warning
II. Meta-Annotations (Annotation Now lets create a class that use the
Types): Test_Element annotation:
There are four types of Meta annotations (or public class Test_Annotations {
annotations of annotations) defined by the public static void main(String arg[]) {
JDK 5. These are as follows: new Test_Annotations().doTestElement();
}
• Target @Test_Target(doTestElement=”Hi ! How r
• Retention you”)
• Documented public void doTestElement() {
System.out.printf(“Testing Target Element
• Inherited
annotation”);
}
1) Target annotation:
}
Target annotation specifies the elements of a
The @Target(ElementType.METHOD)
class to which annotation is to be applied. Here
specifies that this type of annotation can be
is the listing of the elements of the enumerated
applied only at method level. Compiling and
types as its value:
running the above program will work properly.
Lets try to apply this type of annotation to
• @Target(ElementType.TYPE)— applicable annotate an element:
to any element of a class.
• @Target(ElementType.FIELD)—applicable public class Test_Annotations {
to field or property. @Test_Target(doTestElement=”Hi! How r
• @Target(ElementType.PARAMETER)— you”)
applicable to the parameters of a private String str;
method. public static void main(String arg[]) {
• new Test_Annotations().doTestElement();
@Target(ElementType.LOCAL_VARIABLE)— }
applicable to local variables. public void doTestElement() {
• @Target(ElementType.METHOD)— System.out.printf(“Testing Target Element
applicable to method level annotation. annotation”);
• @Target(ElementType.CONSTRUCTOR)— }
}
aplicable to constructors.
•
@Target(ElementType.ANNOTATION_TYPE)—
Here we are trying to apply
specifies that the declared type itself is
an annotation type.
@Target(ElementType.METHOD) at the
field level by declaring the element private
Here is an example that demonstrates the
String str; after the
target annotation:
@Test_Target(doTestElement=”Hi ! How r
you”) statement.
Example:
On compiling this code will generate an error
like this:
@Target(ElementType.METHOD)
public @interface Test_Element {
“Test_Annotations.java”:
public String doTestElement();
D:R_AND_DTest_Annotationsrctestmyannotation
}
Test_Annotations.java:16:
annotation type not applicable to this kind of
declaration at line
16, column 0
@Inherited tag by an example: Have you seen the difference? You have to
implement all the methods of the parent
Example: interface. You will have to implement the
Lets first, define the annotation: equals(), toString(), and the hashCode()
methods of the Object class and also the
annotation type method of the
@Inherited java.lang.annotation.Annotation class. You will
public @interface ParentObjectDemo { also have to include all these methods in your
boolean isInherited() default true; class regardless of whether you are
String showSomething() default “Show implementing all these methods or not
anything?”;
}
@ParentObjectDemo
public Class ChildObjectDemo {
}
The above example shows that you do not
need to define the interface methods inside
the implemented class. The @Inherited tag
automatically inherits the methods for you.
Suppose you define the implementing class in
the old-fashioned-java-style then let us see
the effect of doing this:
JBoss is a cross-platform Java-based AS, due • JBoss Application Server was started as
to this reason it is usable on any operating an open source EJB container in 1999.
system that Java supports. • JBoss 2.x was a full J2EE 1.2 based
server.· JBoss 3.x was a J2EE 1.3 based
Features of JBoss AS: server.
• JBoss 4.x is our current J2EE 1.4
JBoss is advanced middleware with a full J2EE
production version.
based personality.
• JBoss 5.x as beta version is a Java EE 5
certified based server.
I. Open Standards and Open Source:
JBoss is an open source J2EE 1.4 certified AS • JBoss AS 4.2.x versions support for
having business friendly license that allows the EJB3.
developers to free download, use, embed, and
distribute the JBoss AS. JBoss 3.x was released to provide full
framework for building such applications that
II. Simplicity: are based on a Java microkernel (JMX) and
JBoss AS supports full features of J2EE 1.4 service oriented architecture (SOA). While
including EJB, JCA, JSP, JMX, HTTP etc. It JBoss 4.x explores aspect oriented middleware
provides a bridge for the enterprise Java (AOM) and Java based middleware independent
programming model, and enables developers of J2EE.
to get started quickly and easily with these
applications. JBoss AS 5.x Beta versions include the
following core technologies such as POJO based
III. Clustering and High Availability: microcontainer, EJB 3.0, Hibernate 3.2 - JPA
JBoss AS provides the clustering of any java certified, JBoss Messaging, JBoss WebServices
objects (EJB, HTTP, POJO), load balancing, and 2.0 (JAX-WS), JBoss Seam 1.1, etc.
distributed deployment features that are JBoss AS Architecuture:
required for deploying large scalable enterprise
applications.
JBoss AS 4.2.1.GA is the first bug fixing To stop the server, you can either press Ctrl+C
release version of the JBoss Application Server on the console or you can run the shutdown
v4.2 series. Its aim is to fix the most important script shutdown.bat from the bin directory.
bugs against JBossAS v4.2.0.GA that are Alternatively, you can use the management
reported by the community. There are a few console. Look for type=Server under the
minor components are upgraded (Hibernate, jboss.system domain and invoke the shutdown
JacORB, JBoss TS, JBoss Remoting and Sun operation.
JSF) in this released version.
like primary key generation while EJB 3.0 EJBs commonly represent “pure”
provides support for several database- functionality that is created, as it is
specific operations. The O/R mapping needed.
model has intrinsic support for native SQL.
The O/R mapping is specified using • Entity EJB—An Entity EJB maps a
annotations. combination of data (or equivalent
application concept) and associated
7. Runtime services like transaction and functionality. Entity EJBs are usually
security are often implemented as the based on an underlying data store and
interceptor methods managed by the will be created based on that data within
container. However, in EJB 3.0 developers it.
can write custom interceptor. So
developers have control for the actions • Message-driven EJB—A Message-
like committing transaction, security check, driven EJB is very similar in concept to a
etc. Session EJB, but is only activated when
an asynchronous message arrives.
What is new in EJB 3.0?
Session Bean on EJB Container
Now, have a look over the new features of EJB
3.0 that achieved some simplicity over the
previous EJB APIs in various ways:
Note that, the @Remote annotation decorating in any text-based format such as HTML, WML,
the interface definition. This lets the container and XML.
know that remote clients will access
CalculatorBean. The source code for the “form.jsp” is given
below.
(ii) Coding the Enterprise Bean Class
The enterprise bean class for this example is <html>
called CalculatorBean. This class implements <head>
the four business methods (add, subtract, <title>Calculator</title>
multiply, division) that are defined in the </head>
CalculatorRemote business interface. The <body bgcolor=”pink”>
source code for the CalculatorBean class is <h1>Calculator</h1>
given below. <hr>
<form action=”WebClient.jsp”
package method=”POST”>
com.javajazzup.examples.ejb3.stateless; <p>Enter first value:
import java.math.*; <input type=”text” name=”num1"
import javax.ejb.Stateless; size=”25"></p>
import javax.ejb.Remote; <br>
@Stateless(name=”CalculatorBean”) <p>Enter second value:
@Remote(CalculatorRemote.class) <input type=”text” name=”num2"
public class CalculatorBean implements size=”25"></p>
CalculatorRemote{ <br>
public float add(float x, float y){ <b>Seclect your choice:</b><br>
return x + y; <input type=”radio” name=”group1" value
} =”add”>Addition<br>
public float subtract(float x, float y){ <input type=”radio” name=”group1" value
return x - y; =”sub”>Subtraction<br>
} <input type=”radio” name=”group1" value
public float multiply(float x, float y){ =”multi”>Multiplication<br>
return x * y; <input type=”radio” name=”group1" value
} =”div”>Division<br>
public float division(float x, float y){ <p>
return x / y; <input type=”submit”
} value=”Submit”>
} <input type=”reset”
value=”Reset”></p>
Note that, the @Stateless annotation decorating </form>
the enterprise bean class. This lets the container </body>
know that CalculatorBean is a stateless session </html>
bean.
The classes needed by the client are declared Float num2 = new Float(s2);
using a JSP page directive (enclosed within the if(s3.equals(“add”))
<%@ %> characters). Because locating the result=calculator.add(num1.floatValue(),
business interface and creating the enterprise num2.floatValue());
bean are performed only once, this code appears else if(s3.equals(“sub”))
in a JSP declaration (enclosed within the <%! result=calculator.subtract(num1.floatValue(),
%> characters) that contains the initialization num2.floatValue());
method, jspInit, of the JSP page. A scriptlet else if(s3.equals(“multi”))
(enclosed within the <% %> characters) result=calculator.multiply(num1.floatValue(),
retrieves the parameters from the request and num2.floatValue());
converts it to a Float object. Finally, a JSP else
scriptlet invokes the enterprise bean’s business result=calculator.division(num1.floatValue(),
methods, and JSP expressions (enclosed within num2.floatValue());
the <%= %> characters) insert the results %>
into the stream of data returned to the client. <p>
<b>The result is:</b> <%= result %>
The full source code for the WebClient.jsp is <p>
given below. <%
<%@ page contentType=”text/html; }
charset=UTF-8" %> }// end of try
<%@ page catch (Exception e) {
import=”com.javajazzup.examples.ejb3.stateless.*, e.printStackTrace ();
javax.naming.*”%> }
<%! %>
private CalculatorRemote calculator = null;
float result=0; The source code for the “index.jsp” is given
public void jspInit() { below that will actual call the client-design form.
try {
InitialContext ic = new <%@page language=”java” %>
InitialContext(); <html>
calculator = (CalculatorRemote) <head>
ic.lookup(“example/CalculatorBean/remote”); <title>Ejb3 Stateless Tutorial</title>
System.out.println(“Loaded Calculator </head>
Bean”); <body bgcolor=”#FFFFCC”>
} catch (Exception ex) { <p align=”center”><font size=”6"
System.out.println(“Error:”+ color=”#800000"><b>Welcome to <br>
ex.getMessage()); Ejb3-Jboss 4.2.0 Tutorial</b></font>
} Click <a href=”ejb3/form.jsp”>Calculator
} Example</a> to execute Calculator<br></p>
public void jspDestroy() { </body>
calculator = null; </html>
}
%> 3. Deploy calculator application on the
<% Application Server
try {
String s1 = To deploy the created example application we
request.getParameter(“num1”); are going to use Jboss 4.2.0 Application Server
String s2 = request.getParameter(“num2”); about which you have read in the previous
String s3 =
request.getParameter(“group1”);
if ( s1 != null && s2 != null ) {
Float num1 = new Float(s1);
http://localhost:8080/example
Reasons of using XML Apart from being valid, restrictions are imposed
on an xml file to abide by a DTD or a Schema
There are number of reasons that contributes to make it well formed. Otherwise, the XML
to the XML’s increasing acceptance, few of them parser won’t be able to read the data. XML is a
are: vendor-neutral standard, so a user can choose
among several XML parsers to process XML
1. Plain Text data.
Applications using XML languages like HTML, XML, XHTML, WML etc...
Although there are countless applications that In 1986, SGML became an international
use XML, here are a few examples of the standard for defining the markup languages. It
applications that are making use of this was used to create other languages, including
technology. HTML, which is very popular for its use on the
web. HTML was made by Tim Berners Lee in
Refined search results - With XML-specific 1991.
tags, search engines can give users more
refined search results. A search engine seeks While on one hand SGML is very effective but
the term in the tags, rather than the entire complex, on the other, HTML is very easy, but
document, giving the user more precise results. limited to a fixed set of tags. This situation
raised the need for a language that was as
EDI Transactions - XML has made electronic effective as SGML and at the same time as
data interchange (EDI) transactions accessible simple as HTML. This gap has now been filled
to a broader set of users. XML allows data to by XML.
be exchanged, regardless of the computing
systems or accounting applications being used. The development of XML started in 1996 at
Sun Microsystems. Jon Bosak with his team
Cell Phones - XML data is sent to some cell began work on a project for remoulding SGML.
phones, which is then formatted by the They took the best of SGML and produced
specification of the cell phone software designer something to be powerful, but much simpler to
to display text, images and even play sounds! use.
File Converters - Many applications have been The World Wide Web Consortium also
written to convert existing documents into the contributes to the creation and development
XML standard. An example is a PDF to XML of the standard for XML. The specifications for
converter. XML were laid down in just 26 pages, compared
to the 500+ page specification that define SGML.
VoiceXML - Converts XML documents into an
audio format so that a user can listen to an Difference between HTML and XML
XML document.
1. XML is designed to carry data.
History of XML
XML describes and focuses on the data while
In the 1970’s, Charles Goldfarb, Ed Mosher and HTML only displays and focuses on how data
Ray Lorie invented GML at IBM. GML was used looks. HTML is all about displaying information
to describe a way of marking up technical but XML is all about describing information. In
documents with structural tags. The initials current scenario XML is the most common tool
stood for Goldfarb, Mosher and Lorie. for data manipulation and data transmission.
Goldfarb invented the term “mark-up language” XML is used to store data in files and for sharing
to make better use of the initials and it became data between diverse applications. Unlike HTML
the Standard Generalised Markup Language. document where data and display logic are
available in the same file, XML hold only data.
In 1986, SGML was adopted by the ISO. Different presentation logics could be applied
to display the xml data in the required format.
SGML is just a specification for defining markup XML is the best way to exchange information.
languages.
2. XML is Free and Extensible.
SGML (Standardized Generalized Markup
Language) is the mother of all markup 3. XML tags are not predefined. User
must “invent” his tags. strict. These are easy to learn and use.
Because of this, creating software that can
The tags used to mark up HTML documents read and manipulate XML is very easy. Xml
and the structure of HTML documents is enables a user to create his own tags.
predefined. The author of HTML documents
can only use tags that are defined in the Note - XML documents use a self-describing
HTML standard (like <p>, <h1>, etc.). and simple syntax
XML allows the user to define his own tags Let’s develop a simple XML document:
and document structure.
<?xml version=”1.0" encoding=”ISO-8859-
4. XML Tags are Case Sensitive 1"?>
<E-mail>
Unlike HTML, XML tags are case sensitive. In <To>Rohan</To>
HTML the following will work: <From>Amit</From>
<Subject>Surprise....</Subject>
<Message>This is incorrect</message> <Body>Be ready for a cruise...i will catch u
tonight</Body>
In XML opening and closing tags must </E-mail>
therefore be written with the same case:
<E-mail>
6. XML is a Complement to HTML, not a
replacement for HTML. Child Elements:
It is important to understand that XML is not Next 4 lines describe the four child elements
a replacement for HTML. In Web development of the root (To, From, Subject and Body).
it is most likely that XML will be used to
describe the data, while HTML will be used to <To>Rohan</To>
format and display the same data. <From>Amit</From>
Syntax Rules for XML <Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will catch u
The syntax rules for XML are very simple and tonight</Body>
Now let’s discuss its syntax-rules which are Always Quote the XML Attribute Values
very simple to learn.
All XML elements must have a closing tag In XML the attribute value must always be
quoted. XML elements can have attributes in
In XML all the elements must have a closing name/value pairs just like in HTML. Just look
tag like this: the two XML documents below.
The error in the first document is that the
<To>Rohan</To> date and version attributes are not quoted .
<From>Amit</From>
<?xml version=1.0 encoding=”ISO-8859-
1"?>
XML tags are case sensitive <E-mail date=12/11/2002/>
XML tags are case sensitive. The tag <To> is The second document is correct:
different from the tag <to>. Hence the
opening and closing tags must be written with <?xml version=”1.0" encoding=”ISO-8859-
the same case: 1"?>
<E-mail date=”12/11/2002"/>
<To>Rohan</To>
<to>Rohan</to>
With XML, White Space is preserved
XML Elements Must be Properly Nested With XML, the white space in a document is
preserved.
Improper nesting of tags makes no sense to
XML. In XML all elements must be properly So a sentence likes this: Hello How
nested within each other like this in a logical are you, will be displayed like this:
order:
Hello How are you,
<b><i>Hi , how are you.....</i></b>
Comments in XML
XML Documents Must Have a Root The syntax for writing comments in XML is
Element similar to that of HTML.
All XML documents must contain a single tag <!— This is a comment —>
pair to define a root element. All other
elements must be written within this root
element. All elements can have sub elements
called as child elements. Sub elements must XML Elements
be correctly nested within their parent
element: XML Elements are extensible. They have
XML Elements are Extensible Be ready for a cruise...i will catch u tonight
XML documents can be extended to carry
more information. XML Elements have Relationships
Look at the following XML example: Elements in a xml document are related as
parents and children.
<?xml version=”1.0" encoding=”ISO-8859-
1"?> Imagine that this xml document is a description
<E-mail> of e-mail:
<To>Rohan</To>
<From>Amit</From> <?xml version=”1.0" encoding=”ISO-8859-
<Body>Be ready for a cruise...i will catch u 1"?>
tonight</Body> <E-mail>
</E-mail> <To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
Let’s suppose that we create an application to <Body>Be ready for a cruise...i will catch u
fetch data from the above XML document tonight</Body>
and produce this output: </E-mail>
Now, the author wants to add a new feature XML Element Naming conventions:
(let it be a subject line). He can easily achieve
it by adding one more tag ie..<Subject>in the XML elements must follow these naming
xml document. So the new modified xml conventions:
document will look like this:
Names must not start with a number or
<?xml version=”1.0" encoding=”ISO-8859- punctuation character but it can contain letters,
1"?> numbers, and other characters without spaces.
<E-mail>
<To>Rohan</To> Names must not start with the letters xml (or
<From>Amit</From> XML, or Xml, etc).
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will catch u XML Attributes
tonight</Body>
</E-mail> XML elements can have attributes in the start
Now the new generated output will look like tag, just like HTML. Attributes are used to
this: provide additional information about elements.
Attributes often provide information that
E-mail is not a part of the data. In the example below,
the file type is irrelevant to the data, but
To: Rohan
From: Amit
important to the software that wants to Try to avoid using attributes in few of the
manipulate the element: situations.
Use of Elements vs. Attributes First xml document contains date as a attribute
which can not be further extended. But date
If you start using attributes as containers for used a element in second document makes it
XML data, you might end up with the more flexible.
documents that are both difficult to maintain
and manipulate. So the user should use
elements to describe the data. Use attributes <?xml version=”1.0" encoding=”ISO-8859-
only to provide data that is not relevant to 1"?>
the reader. Only metadata (data about data) <E-mail >
should be stored as attributes, and that data <date=”15/05/07">
itself should be stored as elements. <To>Rohan</To>
<From>Amit</From>
This is not the way to use attributes eg.. <Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will catch u
<?xml version=”1.0" encoding=”ISO-8859- tonight</Body>
1"?> </E-mail>
<E-mail To=”Rohan” From=”Amit”
Subject=”Surprise....” Second xml document can be further
<Body>Be ready for a cruise...i will catch u extended as.
tonight</Body>
</E-mail>
Importance of a DTD:
The name of the element is “img”. The name of In a DTD, elements are declared with an
the attribute is “src”. The value of the attribute ELEMENT declaration.
is “computer.gif”. Since the element itself is
empty it is closed by a “ /”. Declaring Elements: syntax
When children are declared in a sequence The ‘*’ sign in the example above declares
separated by commas, the children must that the child element “Fill-Red” can occur
appear in the same sequence in the zero or more times inside the “color” element.
document. In a full declaration, the children
must also be declared.Children can have
The ‘?’ sign in the example above declares <reciept type=”check” />
that the child element “Fill-Red” can occur
zero or one time inside the “color” element. Attribute-type
FIXED Syntax
<person />
Invalid XML:
Valid XML:
<Profile>&name;&company;</Profile>
Use enumerated attribute values when you
want the attribute value to be one of a fixed
set of legal values.
5. DTD-Entities
DTD Example:
XML example:
<Profile>&name;&company;</Profile>
<property
public static SessionFactory name=”current_session_context_class”>thread
getSessionFactory() { </property>
return sessionFactory; <!— Disable the second-level cache —>
} <property name=”cache.provider_class”>
} org.hibernate.cache.NoCacheProvider
</property>
<!— Echo all executed SQL to stdout —>
If you see the only change in the file for the <property name=”show_sql”>true
annotations is that we simply use </property>
AnnotationConfiguration() class instead of the <!— Drop and re-create the database
Configuration() class to build the schema on startup —>
sessionFactory for the hibernate. <property name=”hbm2ddl.auto”>none
</property>
Step 2: Creating the Hibernate.cfg.xml
<mapping class=”com.roseindia.Employee”/>
The Hibernate.cfg.xml is the configuration file
for the datasource in the Hibernate world. The </session-factory>
following is the example for the configuration </hibernate-configuration>
file.
The only change is that, we are just telling
<?xml version=’1.0' encoding=’utf-8'?> the compiler that instead of any resource get
<!DOCTYPE hibernate-configuration PUBLIC the metadata for the mapping from the POJO
”-//Hibernate/Hibernate Configuration DTD class itself like in this case it is
3.0//EN” net.roseindia.Employee.
”http://hibernate.sourceforge.net/hibernate-
configuration-3.0.dtd”> Note: Using annotations does not mean that
<hibernate-configuration> you cannot give the hbm.xml file mappng. You
<session-factory> can mix annotations and hbm.xml files mapping
<!— Database connection settings —> for different Pojo but you cannot mix the
<property mappings for the same POJO in both ways.
name=”connection.driver_class”>com.mysql.jdbc.Driver</
property> Step 3: Developing a simple POJO
<property
name=”connection.url”>jdbc:mysql:// The major changes occurred only in the POJO
localhost:3306/test</property> files if you want to use the annotations as this
<property is the file which will now contain the mapping of
name=”connection.username”>root</ the properties with the database.
property>
<property The following is the code for the Employee
name=”connection.password”>root</ POJO.
property>
<!— JDBC connection pool (use the built-in) package net.roseindia;
—>
<property name=”connection.pool_size”>1 import java.io.Serializable;
</property>
<!— SQL dialect —> import javax.persistence.Column;
<property name=”dialect”> import javax.persistence.Entity;
org.hibernate.dialect.MySQLDialect import javax.persistence.Id;
</property> import javax.persistence.Table;
<!— Enable Hibernate’s automatic session
context management —> @Entity
Get Gets a file from an URL. Fileset It defines a named list of files
that must actually exist.
Jar Jars a set of files.
Patternset It groups a set of patterns
Java Executes a Java class within together.
the running (Ant) VM or forks
another VM if specified. Filterset It groups a set of filters
together.
<copydir src=”${jsp}”
Path It specifies paths (such as a dest=”${deployJSP}”/>
classpath) in a way that is portable </target>
between operating systems. </project>
In Ant, all the command line tasks used for 1. <?xml version=”1.0"?>
deploying an application are represented by
simple XML elements. It accepts instructions in Since Ant build files are XML files so the
the form of XML documents thus it is extensible document begins with an XML declaration that
and easy to maintain. The Ant installation specifies which version of XML is in use.
comes with a JAXP-Compliant XML parser, that
means the installation of an external XML 2. <project name=”antCompile”
parser is not necessary. default=”deploy” basedir=”.”>
In this section, a simple Ant example is shown The root element of an Ant build file is the
below which is followed by a set of instructions project element that contains information about
that indicates how to use Ant. the overall project that is to be built. It has
three attributes.
Simple build process with Ant
(build.xml): • name: It defines the name of the project
that can be any combination of
<?xml version=”1.0"?> alphanumeric characters that constitute
<project name=”antCompile” valid XML.
default=”deploy” basedir=”.”>
<target name=”init”> • default: It references the default target
<property name=”sourceDir” that is to be executed, and when no target
value=”src”/ > is specified. Out of these three attributes
<property name=” classDir “ default is the only required attribute.
value=”build” />
<property name=”deployJSP” value=”/ • basedir: It is treated as the base directory
web/deploy/jsp” />
from which the relative references
</target>
contained in the build file are retrieved.
Each project can have only one basedir
<target name=”clean” depends=”init”>
attribute.
<deltree dir=”${ classDir }” />
</target>
3. <target name=”init”>
<target name=”prepare” depends=”clean”>
or
<mkdir dir=”${ classDir }” />
<target name=”clean” depends=”init”>
</target>
The target element is used as a wrapper for
<target name=”compile”
sequences of actions. It contains four
depends=”prepare”>
attributes: name, if, unless, and depends. Ant
<javac srcdir=”${sourceDir}” destdir=”${
requires the name attribute, but the other three
classDir }” />
attributes are optional.
</target>
name: The name of the target is used to
<target name=”deploy”
reference it from elsewhere, so that it can be
depends=”compile,init”>
Apache Struts is an open-source framework The action tag is a generic tag that is used to
used to develop Java web applications. We call actions directly from a JSP page by specifying
started introducing struts generic tags in the the action name and an optional namespace.
November issue. In this section, we will continue The body content of the tag is used to render
further with the data tags (generic tags) the results from the Action. Any result
provided with struts 2 framework and the rest processor defined for this action in struts.xml
will be included in the subsequent issues of will be ignored, unless the executeResult
the magazine. parameter is specified.
Just download the zip file Add the following code snippet into the
“struts2datatags.zip” from any link given below struts.xml file.
of each page of this article, unzip it and copy
this application to the webapps directory of struts.xml
Tomcat. Start tomcat and write http://
localhost:8080/struts2datatags/index.jsp to <action name=”actionTag”
the address bar. You can examine the result of class=”net.javajazzup.actionTag”>
each tag from this page. <result name=”success”>/pages/dataTags/
success.jsp</result>
</action>
actionTag.java
package net.javajazzup;
import
com.opensymphony.xwork2.ActionSupport;
success.jsp
Create an action class as shown below:
<%@ taglib prefix=”s” uri=”/struts-tags” %>
beanTag.java
<html> package net.javajazzup;
<head> import
<title>Action Tag Example</title> com.opensymphony.xwork2.ActionSupport;
</head>
<body> public class beanTag extends ActionSupport {
<h2>Action Tag Example</h2> public String execute() throws Exception{
<s:action name=”success”> return SUCCESS;
<b><i> }
The action tag will execute the result and }
include it in this page.</i></b></div>
</s:action>
</body> Create a simple java bean as shown:
</html>
companyName.java
package net.javajazzup;
Output of the success.jsp
public class companyName {
private String name;
beanTag.jsp struts.xml
package net.javajazzup;
import
com.opensymphony.xwork2.ActionSupport;
import java.util.*;
dateTag.jsp </tr>
</table>
<%@ taglib prefix=”s” uri=”/struts-tags” %>
</body>
<html> </html>
<head>
<title>Date Tag Example</title>
</head> Output of the dateTag.jsp :
<body>
<h2>Current Date Format</h2>
<table border=”1" width=”35%”>
<tr>
<td><b>Date Format</b></td>
<td><b>Date</b></td>
</tr>
<tr>
<td>Day/Month/Year</td>
<td><s:date name=”currentDate”
format=”dd/MM/yyyy” /></td>
</tr>
<tr>
<td>Month/Day/Year</td>
<td><s:date name=”currentDate”
format=”MM/dd/yyyy” /></td>
</tr>
<tr>
<td>Month/Day/Year</td>
<td><s:date name=”currentDate”
format=”MM/dd/yy” /></td>
</tr>
<tr>
<td>Month/Day/Year Hour<B>:</ 4. Include Tag (Data Tag) Example
B>Minute</td>
<td><s:date name=”currentDate” The include tag is a generic tag that is used to
format=”MM/dd/yy hh:mm” /></td> include a servlet’s output (result of servlet or a
</tr> JSP page) to the current page.
<tr>
<td>Month/Day/Year Hour<B>:</ Add the following code snippet into the
B>Minute<B>:</B>Second</td> struts.xml file.
<td><s:date name=”currentDate”
format=”MM/dd/yy hh:mm:ss” /></td> struts.xml
</tr>
<tr> <action name=”includeTag”
<td>Nice Date (Current Date & class=”net.javajazzup.includeTag”>
Time)</td> <result>/pages/dataTags/includeTag.jsp
<td><s:date name=”currentDate” </result>
nice=”false” /></td> </action>
</tr>
<tr>
<td>Nice Date</td>
<td><s:date name=”currentDate”
nice=”true” /></td>
struts.xml
<action name=”paramTag”>
<result>/pages/dataTags/paramTag.jsp
</result>
</action>
paramTag.jsp
<html>
<head>
<title>Param Tag Example</title>
</head>
<body>
<h2>Param Tag Example</h2>
5. Param Tag (Data Tag) Example
<ui:component>
<ui:param name=”empname”>Emp1</
The param tag is a generic tag that is used to
ui:param><br>
parameterize other tags. For example the
<ui:param name=”empname”>Emp2</
include tag and bean tag. The parameters can
ui:param><br>
be added with or without a name as a key.
<ui:param name=”empname”>Emp3</
ui:param>
The param tag has the following two
</ui:component>
parameters.
</body>
</html>
1. name (String) - the name of the
parameter
2. value (Object) - the value of the
parameter
<html>
<head>
<title>Set Tag Example</title>
</head>
<body>
<h2>Set Tag Example</h2>
<s:set name=”technologyName”
value=”%{‘Java’}”/>
Technology Name: <s:property
value=”#technologyName”/>
</body>
</html>
struts.xml
bundle, then the body of the tag will be The next tag
used as default message. <s:text name=”empname”>Vinod, Amit,
Sushil, .......</s:text> uses the body of the
3. If there is no body, then the name of the tag as a default message.
message will be used.
The last tag <s:text name=”empname”>
Add the following code snippet into the </s:text> does not have access to the
struts.xml file. package.properties files nor does it have a
body so it uses name of the message to
struts.xml display.
webname1 = http://www.javajazzup.com
webname2 = http://www.roseindia.net
webname3 = http://www.newstrackindia.com
8. Property Tag (Data Tag) Example Create a jsp using the tags.
The property tag is a generic tag that is used <s:property value=”%{name}” /> it prints
to get the property of a value, which will default the result of myBean’s getMyBeanProperty()
to the top of the stack if none is specified. method.
Add the following code snippet into the <s:property value=”name” default=”Default
struts.xml file. Value” /> it prints the result of
companyName’s getName() method and if it
struts.xml is null, print ‘a default value’ instead.
Wiring up everything
o
w
b
e
l:
1. Presentation Layer
2. Business Layer
3. Data Access Layer
Downloading MyFaces
</context-param>
<context-param>
<param-name>contextConfigLocation</
param-name>
<param-value>/WEB-INF/
applicationContext-hibernate.xml</param-
value>
</context-param>
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.
ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!—End Spring configuration —>
<context-param>
<param-name>
javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-
config.xml</param-value>
</context-param>
<context-param>
<param-
Now follow the following steps to create the name>javax.faces.STATE_SAVING_METHOD</
application: param-name>
1. Create a directory with the name of your <param-value>client</param-value>
application (HibernateMyFaces) under </context-param>
webapps directory of tomcat.
2. Create “WEB-INF” directory inside it. <!— Extensions Filter —>
3. Create other directories as shown in the <filter>
above image. <filter-name>extensionsFilter</filter-
4. Copy libraries files from “myfaces- name>
example-simple-1.1.6\WEB-INF\lib” <filter-class>
directory to “lib” directory. org.apache.myfaces.component.html.util.E
5. Create web.xml file under WEB-INF xtensionsFilter </filter-class>
directory and add the following content.
<init-param>
<?xml version=”1.0"?> <param-name>uploadMaxFileSize</
<!DOCTYPE web-app PUBLIC “-//Sun param-name>
Microsystems, Inc.//DTD Web Application 2.3/ <param-value>100m</param-value>
/EN” “http://java.sun.com/dtd/web- <description>Set the size limit for
app_2_3.dtd”> uploaded files.
<web-app> Format: 10 - 10 bytes
<!— Spring context Configuration Begins—> 10k - 10 KB
<context-param> 10m - 10 MB
<param-name>log4jConfigLocation</ 1g - 1 GB
param-name> </description>
<param-value>/WEB-INF/log4j.properties</ </init-param>
param-value> <init-param>
<param-name>uploadThresholdSize <faces-config>
</param-name> <application>
<param-value>100k</param-value> <locale-config>
<description>Set the threshold size – <default-locale>en
files below this limit are stored in memory, </default-locale>
files above this limit are stored on disk. </locale-config>
Format: 10 - 10 bytes <message-
10k - 10 KB bundle>net.roseindia.web.ui.messages
10m - 10 MB </message-bundle>
1g - 1 GB </application>
</description>
</init-param> <managed-bean>
</filter> <managed-bean-name>Bean
</managed-bean-name>
<filter-mapping> <managed-bean-
<filter-name>extensionsFilter class>net.roseindia.web.ui.Bean
</filter-name> </managed-bean-class>
<url-pattern>*.jsf</url-pattern> <managed-bean-scope>session
</filter-mapping> </managed-bean-scope>
<filter-mapping> </managed-bean>
<filter-name>extensionsFilter</filter-
name> <managed-bean>
<url-pattern>/faces/*</url-pattern> <managed-bean-name>CheckValidUser
</filter-mapping> </managed-bean-name>
<servlet> <managed-bean-class>
<servlet-name>Faces Servlet</servlet- net.roseindia.web.ui.CheckValidUser
name> </managed-bean-class>
<servlet- <managed-bean-scope>session
class>javax.faces.webapp.FacesServlet</ </managed-bean-scope>
servlet-class> </managed-bean>
<load-on-startup>1</load-on-startup>
</servlet> <navigation-rule>
<servlet-mapping> <from-view-id>/pages/login.jsp
<servlet-name>Faces Servlet</servlet- </from-view-id>
name> <navigation-case>
<url-pattern>*.jsf</url-pattern> <from-outcome>reg
</servlet-mapping> </from-outcome>
<welcome-file-list> <to-view-id>/pages/
<welcome-file>index.jsp</welcome- registration.jsp</to-view-id>
file> </navigation-case>
</welcome-file-list> <navigation-case>
</web-app> <from-outcome>success</from-outcome>
<to-view-id>/pages/
6. Now create faces-config.xml and add successLogin.jsp</to-view-id>
the following code. </navigation-case>
<navigation-case>
<from-outcome>failure</from-outcome>
<?xml version=”1.0"?> <to-view-id>/pages/login.jsp</to-view-id>
<!DOCTYPE faces-config PUBLIC “-//Sun </navigation-case>
Microsystems, Inc.//DTD JavaServer Faces </navigation-rule>
Config 1.0//EN” “http://java.sun.com/dtd/
web-facesconfig_1_0.dtd” > <navigation-rule>
<from-view-id>/pages/registration.jsp</ 1.1.5.jar”/>
from-view-id> <pathelement path =”lib/jstl-1.1.0.jar”/
<navigation-case> >
<from-outcome>success</from-outcome> <pathelement path =”lib/tomahawk-
<to-view-id>/pages/welcome.jsp 1.1.6.jar”/>
</to-view-id> <pathelement path =”libext/servlet-
</navigation-case> api.jar”/>
<navigation-case> <pathelement path =”classes”/>
<from-outcome>failure</from-outcome> <pathelement path =”${classpath}”/>
<to-view-id>/pages/registration.jsp </path>
</to-view-id>
</navigation-case> <!— Check timestamp on files —>
</navigation-rule> <target name=”prepare”>
</faces-config> <tstamp/>
</target>
Note: In the next sections we will add the <!— Copy any resource or configuration
configuration into web.xml and faces- files —>
config.xml files, so the content will change. <target name=”resources”>
We advice you to download the full code from <copy todir=”src/classes”
our site and then take the files from there. includeEmptyDirs=”no”>
<fileset dir=”src/java”>
7. Create “src” directory parallel to the “lib” <patternset>
directory. <include name=”**/*.conf”/>
<include name=”**/*.properties”/>
8. Create two directories “classes”, “java” <include name=”**/*.xml”/>
and “build.xml” file within “src” folder. Copy </patternset>
the following content into build.xml file: </fileset>
</copy>
</target>
<project name=”MyFaces, Hibernate and <!— Normal build of application —>
Spring Integration” basedir=”../” <target name=”compile”
default=”all”> depends=”prepare,resources”>
<!— Project settings —> <javac srcdir=”src” destdir=”src/
<property name=”project.title” classes” debug=”true”
value=”RoseIndia MyFaces, Hibernate and debuglevel=”lines,vars,source”>
Spring Integration Tutorial”/> <classpath refid=”class.path”/>
<property name=”project.jar.file” </javac>
value=”roseindia.jar”/> <jar jarfile=”lib/${project.jar.file}”
basedir=”src/classes”/>
<path id=”class.path”> </target>
<fileset dir=”lib”> <!— Remove classes directory for clean
<include name=”**/*.jar”/> build —>
</fileset> <target name=”clean”
<fileset dir=”libext”> description=”Prepare for clean build”>
<include name=”**/*.jar”/> <delete dir=”classes”/>
</fileset> <mkdir dir=”classes”/>
</path> </target>
<!— Classpath for Project —> <!— Build Javadoc documentation —>
<path id=”compile.classpath”> <target name=”javadoc”
<pathelement path =”lib/myfaces-api-
1.1.5.jar”/>
<pathelement path =”lib/myfaces-impl-
description=”Generate JavaDoc API docs”> libraries and configuration files to the web
<delete dir=”./doc/api”/> application.
<mkdir dir=”./doc/api”/>
<javadoc sourcepath=”./src/java” destdir=”./ Steps to integrate:
doc/api”
classpath=”${servlet.jar}:${jdbc20ext.jar}” Adding Servlets Library
packagenames=”*” Since we are using ant build tool to compile the
author=”true” private=”true” version=”true” application, it is necessary to make servlets
windowtitle=”${project.title} API api library available to ant build tool for compiling
Documentation” the java code. We are adding Servlets library
doctitle=”<h1>${project.title} to the project.
Documentation (Version 1. Create a directory named libext under
${project.version})</h1>” WEB-INF directory of your application.
bottom=”Copyright ©
2002"> 2. Copy servlet-api.jar from common\lib
<classpath directory of your Tomcat into libext
refid=”compile.classpath”/> directory.
</javadoc>
</target> Adding Hibernate Libraries
<!— Build entire project —> Now we will download hibernate libraries and
<target name=”project” add it to the project.
depends=”clean,prepare,compile”/>
<!— Build project and create 1. Download hibernate-3.2.4.sp1.zip or
distribution—> latest version from http://
<target name=”all” depends=”project”/> www.hibernate.org/6.html. We have
</project> downloaded hibernate-3.2.4.sp1.zip for this
tutorial.
We will use ant tool to build the application, 2. Unzip the file.
so make sure ant tool is installed on your
development machine. 3. Copy all the jar files from hibernate-
9. Create directory with name “net” in 3.2.4.sp1\hibernate-3.2\lib into lib
“java” directory and directory of name directory of your application. (The directories
“roseindia” within “net” directory. hibernate-3.2.4.sp1\hibernate-3.2 may be
different in your case depending on the
10. Create “classes” directory within downloaded version).
“WEB-INF” directory for the class file to be
used in the application. 4. Copy hibernate3.jar from hibernate-
3.2.4.sp1\hibernate-3.2 into lib directory of
4. Adding Spring and Hibernate your application.
Capabilities
Adding Spring Libraries
In this section, we will add Spring and Hibernate Our application uses spring to manage the
capabilities to our web application. So for this, beans, so we have to add the spring
we will have to add the spring and hibernate capabilities to the application.
1. Download spring-framework-2.0.5-
with-dependencies.zip from http://
www.springframework.org/download.
Creating Database:
You can create mysql database by issuing the
following command:
Registration Page:
This page comes to the user if the user is not
registered with the site. The user clicks the
link named “New User?” and so registration
successLogin.jsp: This is the code for page is opened. The figure below is
above page. This is simple page in which only registration page:
welcome string is shown to the user.
</navigation-case> org.springframework.web.context.
</navigation-rule> ContextLoaderServlet
</servlet-class>
<navigation-rule> <load-on-startup>1</load-on-startup>
<from-view-id>/pages/registration.jsp</ </servlet>
from-view-id> <!—End Spring configuration —>
<navigation-case>
<from-outcome>success</from- <context-param>
outcome> <param-
<to-view-id>/pages/welcome.jsp</ name>javax.faces.CONFIG_FILES</param-
to-view-id> name>
</navigation-case> <param-value>
<navigation-case> /WEB-INF/faces-config.xml
<from-outcome>failure</from- </param-value>
outcome> </context-param>
<to-view-id>/pages/
registration.jsp</to-view-id> <context-param>
</navigation-case> <param-
</navigation-rule> name>javax.faces.STATE_SAVING_METHOD</
param-name>
</faces-config> <param-value>client</param-value>
</context-param>
1g - 1 GB import net.roseindia.web.common.*;
</description>
</init-param> import net.roseindia.dao.*;
</filter>
CheckValidUser.java
<filter-mapping> This bean has been used in the login page. All
<filter-name>extensionsFilter</filter- the properties of the bean are related to the
name> fields of the login page. When the page is
<url-pattern>*.jsf</url-pattern> submitted then checkUser() method is called
</filter-mapping> which checks the username and password. If
<filter-mapping> both are correct then the user is sent to the
<filter-name>extensionsFilter</filter- next page which welcomes the user otherwise
name> message is displayed to the user in the same
<url-pattern>/faces/*</url-pattern> login page. In this bean there is one exist
</filter-mapping> property which is set to true if username or
password doesn’t match with the database. So
<servlet> this value is set to the “rendered” property of
<servlet-name>Faces Servlet</servlet- the tag responsible for displaying the string
name> “User name or password is incorrect”.
<servlet-
class>javax.faces.webapp.FacesServlet</ package net.roseindia.web.ui;
servlet-class> import net.roseindia.web.common.*;
<load-on-startup>1</load-on-startup>
</servlet> import net.roseindia.dao.*;
package net.roseindia.web.ui;
public String getUserEmail() { the data in the form of Java objects from
return this.userEmail; database. Hibernate also supports association,
} inheritance, polymorphism, composition and also
the Java Collection framework.
public void setUserEmail(String userEmail)
{ Data Access Object (DAO)
this.userEmail = userEmail; In this application we have used the DAO
} pattern. The DAO pattern abstracts and
encapsulates all access to the data source. Our
public String getUserAddress() { application has one DAO interface:
return this.userAddress; HibernateSpringDAO. The implementation
} classes of it is HibernateSpringDAOImpl that
contains Hibernate-specific logic to manage and
public void setUserAddress(String persist data.
userAddress) {
this.userAddress = userAddress; Here is the code of
} HibernateSpringDAO.java file:
} import
org.springframework.dao.DataAccessException;
import net.roseindia.dao.hibernate.*;
Since we are using Hibernate for persistence,
the User business object provides getter and public interface HibernateSpringDAO {
setter methods for all fields.
Business Services /**
* Retrieve all <code>true</code>/
Business Services contains the code to interact <code>false</code> from the datastore.
with the data tier. In this application we have * @return a <code>true</code> or
developed a formal service layer, client can use <code>fasel</code>.
these services interface. There is only one */
service in this application the ServiceFinder. public User checkUser(String strUserName)
The ServiceFinder service is used to get the throws
Spring managed beans from DataAccessException,java.sql.SQLException;
WebApplicationContext.
/**
In the next section we will learn about * Retrieve all <code>true</code>/
Integration tier of our application. Integration <code>false</code> from the datastore.
tier is also known as data access tier. * @return a <code>true</code> or
<code>fasel</code>.
8. Implementing Data Access Layer with */
Hibernate public User validateUser(String
strUserName,String password) throws
In this application we are using Hibernate to
implement data access layer. Hibernate is an DataAccessException,java.sql.SQLException;
open source O/R mapping framework that
handles all the persistence logic. /**
* Saves User object to the datastore.
Hibernate supports all major database available *
in the market. The Hibernate Query Language */
is an object-oriented extension to SQL, which public void
can be extensively used to save and retrieve addUser(net.roseindia.dao.hibernate.User
obj) throws DataAccessException;
criteria.add(Expression.eq(“userPassword”,
} password));
List objs =
getHibernateTemplate().findByCriteria(criteria);
Here is the code of if ((objs != null) && (objs.size() > 0)) {
HibernateSpringDAOImpl.java file that obj = (User) objs.get(0);
actually implements the logic: }
return obj;
package net.roseindia.dao; }
import java.util.*;
import public void
org.springframework.dao.DataAccessException; addUser(net.roseindia.dao.hibernate.User
import obj)
org.springframework.orm.hibernate3.support.HibernateDaoSupport; throws DataAccessException {
import org.hibernate.criterion.*; getHibernateTemplate().save(obj);
//Java Imports }
import java.sql.*; }
import javax.servlet.http.HttpSession; ;
//Project Imports
import net.roseindia.dao.hibernate.*;
Database Design
public class HibernateSpringDAOImpl Our application contains only one table whose
extends HibernateDaoSupport structure is as follows:
implements HibernateSpringDAO {
1. Creating JSP pages In our application there are two backing beans
The JSP pages used in this application are Bean and CheckValidUser.
login.jsp, registration.jsp, successLogin.jsp and Following code in the faces-config.xml file
welcome.jsp. These pages are already described declares the backing beans:
in the previous section Developing Login and
Registration form and backing beans. <application>
<locale-config>
2. Defining the page navigation rules <default-locale>en</default-locale>
Following code present in the faces-config.xml </locale-config>
file defines the page navigation rule. <message-
bundle>net.roseindia.web.ui.messages
<navigation-rule> </message-bundle>
<from-view-id>/pages/login.jsp</from- </application>
view-id>
<navigation-case> <managed-bean>
<from-outcome>reg</from-outcome> <managed-bean-name>Bean</managed-
<to-view-id>/pages/ bean-name>
registration.jsp</to-view-id> <managed-bean-
</navigation-case> class>net.roseindia.web.ui.Bean
<navigation-case> </managed-bean-class>
<from-outcome>success</from- <managed-bean-scope>session
outcome> </managed-bean-scope>
<to-view-id>/pages/ </managed-bean>
<property
11. Integrating Business Logic Tier and name=”userEmail”
Integration Tier Components type=”java.lang.String”
In the business logic tier web have created column=”userEmail”
business objects, business services and now length=”30" />
we are going to integrate them using Spring
framework. <property
name=”userAddress”
Business Objects type=”java.lang.String”
column=”userAddress”
In this example we have only one business length=”30"/>
object the User.
<!— Associations —>
Integration tier components </class>
</hibernate-mapping>
Hibernate maps the business objects to
database using XML configuration file. Following The HibernateSpringDAO is wired with
file (User.hbm.xml) is used to map User object HibernateTemplate by Spring:
with the database.
<bean id=”HibernateSpringDaoTarget”
<?xml version=”1.0" encoding=”UTF-8"?> class=”net.roseindia.dao.HibernateSpringDAOImpl”>
<!DOCTYPE hibernate-mapping PUBLIC “-// <property name=”sessionFactory”><ref
Hibernate/Hibernate Mapping DTD//EN” local=”sessionFactory”/></property>
”http://hibernate.sourceforge.net/hibernate- </bean>
mapping-3.0.dtd”>
implementation. </props>
—> </property>
</bean>
<bean id=”HibernateSpringDaoTarget”
class=”net.roseindia.dao. </beans>
HibernateSpringDAOImpl”>
<property name=”sessionFactory”><ref
local=”sessionFactory”/></property> This application is supported with full free code.
</bean> In the next section we will show you how you
can download and install it on your computer.
<!—
- Transactional proxy for Application’s central 12. Download full code of JSF, Spring and
data access object. Hibernate based Registration program
-
- Defines specific transaction attributes with From this page you can download the source
“readOnly” markers, code of the application.
- which is an optimization that is particularly
valuable with Hibernate(to suppress Downloading code
unnecessary flush attempts for read-only
operations). Download the code of the application.
-Note that in a real-life app with multiple
transaction proxies, Extracting and Installing the code on Tomcat
-you will probably want to use parent and Extract the downloaded file and copy
child bean definitionsas described in the HibernateMyfaces directory to tomcat
manual, to reduce duplication. webapps directory. This will install application
—> on tomcat server.
Rendered Output:
composition.xhtml:
comptemplate.xhtml : debug.xhtml :
xhtml” </body>
xmlns:ui=”http://java.sun.com/jsf/facelets” </html>
xmlns:h=”http://java.sun.com/jsf/html”>
<body> Rendered Output: This is the page that is
Content above composition tag will not be displayed to the user first. Now if we press
rendered. Ctrl+Shift+p then debug window is opened
<ui:composition template=”/pages/debug/ that is shown in the second figure below:
debugtemplate.xhtml”>
<ui:define name=”face1">
<h2>Java Jazz Up</h2>
<h3>Facelet Examples</h3>
</ui:define>
<ui:define name=”face2">Enter UserID
:<br/>
<h:inputText id=”it” /><br/><br/>
</ui:define>
<ui:define name=”face3">Enter Password
:<br/>
<h:inputSecret id=”is” /><br/><br/>
</ui:define>
<ui:define name=”face4">
<h:commandButton id=”cb”
value=”Submit” />
</ui:define>
</ui:composition>
Content below composition tag will not be
rendered.
</body>
</html>
debugtemplate.xhtml :
decoratetemplate.xhtml :
decorate.xhtml:
Rendered Output:
<html xmlns=”http://www.w3.org/1999/
xhtml”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:h=”http://java.sun.com/jsf/html”>
<body>
Content above composition tag will not be
rendered.
<ui:composition template=”/pages/include/
includetemplate.xhtml”>
<ui:define name=”face1">
<h2>Java Jazz Up</h2>
<h3>Facelet Examples</h3>
</ui:define>
<ui:define name=”face2">Enter UserID
:<br/>
<h:inputText id=”it” /><br/><br/>
</ui:define>
<ui:define name=”face3">Enter Password
:<br/>
<h:inputSecret id=”is” /><br/><br/>
</ui:define>
<ui:define name=”face4">
<h:commandButton id=”cb”
value=”Submit” />
</ui:define>
<ui:define name=”face5">
<ui:include src=”includepage.xhtml”/>
</ui:define>
</ui:composition>
Content below composition tag will not be
7. Facelet include tag rendered.
This tag is used to include the content of a </body>
page. This page name is specified by src </html>
attribute of include tag. The page that has
been included should use composition tag or
component tag. It may contain xhtml or xml includetemplate.xhtml :
to be included. In the program below, we
have used include tag and src attribute is set <!DOCTYPE html PUBLIC “-//W3C//DTD
to “includepage.xhtml”. So the content of this XHTML 1.0 Transitional//EN” “http://
page will be included in the “include.xhtml” www.w3.org/TR/xhtml1/DTD/xhtml1-
page and rendered in “includetemplate.xhtml” transitional.dtd”>
because insert tag with name attribute set to <html xmlns=”http://www.w3.org/1999/
face5 is used in “includetemplate.xhtml”. xhtml”
xmlns:ui=”http://java.sun.com/jsf/
include.xhtml: facelets”>
<head>
<!DOCTYPE html PUBLIC “-//W3C//DTD <title>Facelet include tag example</title>
XHTML 1.0 Transitional//EN” “http:// <link href=”../../style/CSS.css”
www.w3.org/TR/xhtml1/DTD/xhtml1- rel=”stylesheet” type=”text/css”/>
transitional.dtd”> </head>
<body>
<ui:insert name=”face1"></ui:insert>
inserttemplate.xhtml :
param.xhtml: paramtemplate.xhtml :
</ui:define> </html>
</ui:composition>
Content below composition tag will not be
rendered.
</body>
</html>
remove.xhtml:
Rendered Output:
<!DOCTYPE html PUBLIC “-//W3C//DTD
XHTML 1.0 Transitional//EN” “http://
www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/
xhtml”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:h=”http://java.sun.com/jsf/html”>
<body>
<h2>Java Jazz Up</h2>
<h3>Facelet Examples</h3>
<hr/>
<ui:decorate template=”/pages/remove/
removetemplate.xhtml”>
<ui:define name=”face1">
<h3><h:outputText value=”This is the
text to be displayed.”/></h3>
<input type=”text” jsfc=”h:inputText”
value=”This i/p box is rendered” />
<input type=”text” jsfc=”ui:remove”
value=”IT” />
<ui:remove>This line will be removed</
ui:remove>
</ui:define>
</ui:decorate>
<hr/><h3>This is the content below
decorate tag.</h3>
</body>
</html>
removetemplate.xhtml
repeattemplate.xhtml :
In this Issue, we are going to discuss only the class Teacher implements Person {
Iterator, Mediator, and the Memento design private double MonthlyIncome;
patterns. private String name;
public Teacher(String name, double i) {
Iterator Pattern this.name = name;
setMonthlyIncome(i);
Iterator pattern is the mechanism of accessing }
all the objects in a collection. To sequentially
access the objects of a collection, the iterator void setMonthlyIncome(double i) {
pattern defines an interface containing the if (i > 0) {
methods that access the objects of a collection MonthlyIncome = i;
or the aggregate objects without having } else
knowledge about its internal representation. It MonthlyIncome = 0;
provides uniform interface to traverse collections }
of all kinds.
public double income() {
Aggregate objects are the objects containing return MonthlyIncome;
the group of objects as a unit. We can also }
referred them as container or collection. Hash public String getName() {
table and linked list are the examples of return name;
aggregate objects. }
public String toString() {
Example: Lets take an example of employees return “Teacher: “ + getName();
of a software company and their section, then }
we add some enumeration capabilities to the }
Employee class. This class is the collection of
employees having their names; employee id and
their department and these employees are
Mediator.java theChangedPilot ){
MementoDemoDp.java
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.awt.FontMetrics;
In the program code given below, we have used class PopupAppMenu extends PopupMenu
MouseEvent.isPopupTrigger() method to trigger implements ActionListener{
the MouseEvent that pops up the menu. The PopupMenuDemo ref;
example below shows the triggering of a pop- public PopupAppMenu(PopupMenuDemo ref){
up menu and its activation through a command super(“File”);
button. this.ref = ref;
MenuItem mi;
Code of Program: PopupMenuDemo.java add(mi = new MenuItem(“Copy”));
mi.addActionListener(this);
import java.awt.*; add(mi = new MenuItem(“Open”));
import java.awt.event.*; mi.addActionListener(this);
import java.applet.Applet; add(mi = new MenuItem(“Cut”));
mi.addActionListener(this);
public class PopupMenuDemo extends Applet{ add(mi = new MenuItem(“Paste”));
Button b; mi.addActionListener(this);
TextField msg; }
PopupAppMenu m; public void actionPerformed(ActionEvent e){
public PopupMenuDemo(){ String item = e.getActionCommand();
setSize(200, 200); ref.msg.setText(“Option Selected: “ + item);
b = new Button(“Pop-up Menu”); }
add(b, BorderLayout.NORTH); }
msg = new TextField();
msg.setEditable(false); PopupMenuDemo.html
add(msg, BorderLayout.SOUTH);
m = new PopupAppMenu(this); <HTML>
add(m); <HEAD>
b.addActionListener(new </HEAD>
ActionListener(){ <BODY>
public void actionPerformed(ActionEvent e){ <APPLET ALIGN=”CENTER”
m.show(b, 20, 20); CODE=”PopupMenuDemo.class”
} WIDTH=”800" HEIGHT=”500"></APPLET>
}); </BODY>
addMouseListener(new MouseAdapter(){ </HTML>
public void mousePressed(MouseEvent e){
if (e.isPopupTrigger()) Run the program:
m.show(e.getComponent(), e.getX(),
e.getY()); C:\newprgrm>javac PopupMenuDemo.java
} C:\newprgrm>appletviewer
public void mouseReleased(MouseEvent e){ PopupMenuDemo.html
if (e.isPopupTrigger())
m.show(e.getComponent(), e.getX(),
e.getY());
}
});
}
public static void main(String[] args){
popupMenuDemo app = new
PopupMenuDemo();
app.setVisible(true);
public SliderExample(){
JFrame frame = new JFrame(“Slider”);
slider = new JSlider();
slider.setValue(50);
3. JSlider Component of Java Swing
slider.addChangeListener(new
MyChangeAction());
A Slider is a Swing tool that lets the user
label = new JLabel(“JavaJazzUp”);
select a value within a bounded range by
JPanel panel = new JPanel();
moving a knob. In this program, events on
panel.add(slider);
the JSlider component have also been shown.
panel.add(label);
If you increase or decrease the slider by
frame.add(panel, BorderLayout.CENTER);
selecting then the actual position of the slider
frame.setSize(400, 100);
will be displayed on a label. Some methods
frame.setVisible(true);
and APIs have been used to create a JSlider
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
component and perform various tasks related
}
to the slider. Methods and APIs are as follows:
public class MyChangeAction implements
JSlider :
ChangeListener{
This class creates the slider for the swing
public void stateChanged(ChangeEvent
application.
ce){
int value = slider.getValue();
ChangeListener:
String str = Integer.toString(value);
This is the interface of which is used to call
label.setText(str);
stateChanged() method which receives the
}
event generated by the slider using
}
addChangeListener() method of the JSlider
}
class.
Output:
ChangeEvent:
This is the class that handles the event
generated by the JSlider component on change
the state.
addChangeListener(object):
This is the method of the JSlider class which is
used to handle event on change the selected
state of the JSlider component.
import javax.swing.*;
import java.awt.event.*;
public class ShowDialogBox{
JFrame frame;
public static void main(String[] args){
ShowDialogBox db = new ShowDialogBox();
}
public ShowDialogBox(){
frame = new JFrame(“Show Message Dialog”);
JButton button = new JButton(“Show II. Show message and confirm dialog
Message”); box
button.addActionListener(new MyAction());
frame.add(button); There are three types of message dialog box
frame.setSize(300, 300); that you can use in your swing applications.
frame.setVisible(true); In this section, we will display several types of
frame.setDefaultCloseOperation message boxes. When you run the program,
(JFrame.EXIT_ON_CLOSE); it will display a frame with three buttons.
}
public class MyAction implements Description:
ActionListener{
public void actionPerformed(ActionEvent e){ 1. showMessageDialog(): Above method
JOptionPane.showMessageDialog shows a simple message dialog box, which holds
(frame,”JavaJazzUp”); only one button i.e. “Ok” button. This method
} takes four arguments in which, first is the
} parent object name, second is the message as
} string, third is the title of the message dialog
box as string and the last is the type of the
Output: message dialog box.
When you run the program, following window 2. showConfirmDialog(): Above method
will be displayed: asks from the user by displaying a message
dialog box, which contains more than one
button. Depending on the parameter passed
it can be “Ok” and “Cancel” or “Yes”, “No”
and “Cancel”. This method returns the integer
value.
When you click on “Show Message” button,
following Message is displayed: Code of Program:
ShowMessageDialog.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.*;
Output:
http://www.roseindia.net
http://www.newstrackindia.com
http://www.javajazzup.com
http://www.allcooljobs.com
Advertisement Options:
Deepak Kumar
deepak@roseindia.net
If theres something youre curious about, were Present a question, problem, or puzzle
confident that your curiosity, combined with the
knowledge of other participants, will be enough Were inviting people from lots of different
to generate a useful and exciting Readers worlds. We do not expect everybody at Readers
Forum. If theres a topic you feel needs to be Forum to be an expert in some areas. Your
discussed at JavaJazzup, its up to you to get it expertise is a real resource you may contribute
discussed. to the Java Jazzup. We want your curiosity to
be a resource, too. You can also present a
Convene a discussion on a specific subject question, problem, or puzzle that revolves
around java technologies along with their
If you have a topic youd like to talk about . solution that you think would get really
Whether its something you think lots of people appreciated by the java readers around the
will be interested in, or a narrow topic only a globe.
few people may care about, your article will
attract people interested in talking about it at Post resourceful URLs
the Readers Forum. If you like, you can prepare
a really a good article to explain what youre If you think you know such URL links which
interested to tell java technocrates about. can really help the readers to explore their java
skills. Even you can post general URLs that
Sharing Expertise on Java Technologies you think would be really appreciated by the
readers community.
If youre a great expert on a subject in java,
the years you spent developing that expertise Anything else
and want to share it with others. If theres
something youre an expert on that you think If you have another idea for something youd
other technocrates might like to know about, like to do, talk to us. If you want to do
wed love to set you up in the Readers Forum something that we havent thought of, have a
and let people ask you questions. crazy idea, wed really love to hear about it.
Were open to all sorts of suggestions, especially
Show your innovation if they promote readers participation.