Advanced
Line Graph, version 3.2
by Sirius Computer Consultants Limited
Servlet
Example 4
This
example demonstrates how to implement the servlet so that
the graph data is acquired from a database. Here we set
up the servlet to acquire the configuration data from a
text file and the graph data from a server side process
which in turn acquires the data from a database.

and
here is the HTML code,
<img
src="http://localhost:8080/servlet/LineGraphServlet?
config=http://www.jpowered.com/line_graph/Examples/lineprops.txt&
data=http://www.jpowered.com/siriusjava/servlet/DatabaseServlet2"
width="500" height="420">
The
graph servlet will pick up the configuration parameters
from a text file lineprops2.txt and the graph data from
our servlet DatabaseServlet2 ( click
here to view java code ).
The
DatabaseServlet is designed to retrieve product sales data
from a MySQL database, from a table with the following structure,
| Table
Name : ProductSales |
|
|
| ProductName |
Character |
| m1sales |
Integer |
| m2sales |
Integer |
| m3sales |
Integer |
| m4sales |
Integer |
| m5sales |
Integer |
| m6sales |
Integer |
| m7sales |
Integer |
| m8sales |
Integer |
| m9sales |
Integer |
| m10sales |
Integer |
| m11sales |
Integer |
| m12sales |
Integer |
| Year |
Integer |
Our
servlet will pick out the sales figures for the year 2001
for three products ( ProductX, ProductY and ProductZ) and
return the data in the correct format for the line graph.
The
method is as follows,
-
Set the output characteristics for the return data
-
Establish the database connection
-
Build the query statement and retrieve the database records
-
Process the database records and return the Data
-
All finished so close the database connection
The
full servlet code is contained in the DatabaseServlet2.java
file.
(Click
here to view the code).
As you
will see from the code the servlet connects to the database
via JDBC and as such it is essential to have the correct
JDBC drivers for your database. ( For further information
on JDBC drivers please see http://industry.java.sun.com/products/jdbc/drivers
)
The
SQL statement used to retrieve the data from the database
is simply,
SELECT * FROM ProductSales WHERE Year='2001'
The
returned result set from this statement is then passed to
a little routine, GraphData, which reads through the records
picking out the relevant records for the three products.
Also note in this routine how the "rsltStr" is
constructed to provide the data in the correct format for
the Line Graph.
Finally
the rsltStr is returned back to the calling process ( in
this case our Line Graph ) and the database connection is
closed.