|
|
In
an earlier class we used a JavaBean to connect to a database. We
provided the driver name and database URL via setter methods. But
that's essentially hardcoding these parameters. Instead we should
read them from an XML file so that we don't have to recompile just to change
databases!
-
So, let's plan the switch to XML.
-
First, we'll need a simple XML file. Start with the header.
-
We'll implement the document type declaration later. Since that's
optional, we won't worry about it now.
-
Then, we'll make a root element, say <database>. This
will have two child elements.
-
<drivername>, for the driver name, and
-
<databasURL>, for the database URL.
-
At this point, no attribtues.
-
On the bean, we'll simply implement the logic described in the previous
slides to read this file and save the properties.
-
There are a lot of moving parts here. So let's test it by putting
all of the logic in a separate class. Once we're comfortable it is
working, we'll move it into our JavaBean.
-
Deployment Notes:
-
The first time I tried this, NetBeans gave me an error stating that it
could not find the org.w3c.dom package or the javax.xml.parsers package.
I downloaded the Java Web Services Developer Pack
and got the necessary XML jars from there. I copied these jars to
the lib directory of both my JDK and Netbeans, but curiously, this did
not work. So I mounted the jars in my project, and it compiled.
-
A strange one. The book mentions method getRootElement of
class Document that returns a single Element. Well,
they are far from right, but almost right at the same time. It ends
up that interface javax.swing.text.Document
has a method called getRootElements that returns an array, but
this isn't the same interface we want. This document is used in Swing
text components. The one we want is org.w3c.dom.Document,
which has a method called getDocumentElement.
That's what we want. This one had me going in circles for a while!
Example
|