The JSP Files (part 5): No Forwarding Address (
Page 1 of 7 )
This week, find out how to connect your JSPs to a database and build dynamic, data-driven Web pages. This primer covers different techniques to select, insert and delete records, and uses a simple Web-based address book to illustrate the Connection, Statement, and ResultSet objects.JSP offers a number of advantages over other server-side scripting languages -
as you've already seen, performance is just one of them. And this performance
edge becomes particularly important when you combine it with another important
benefit - the ability to seamlessly connect to a variety of database
servers.
By offering seamless database connectivity (okay, it's not as
transparent as the database connectivity available in PHP, but it's still pretty
good!) in combination with faster response times, JSP allows developers to build
complex, scalable, data-driven Web applications while simultaneously enjoying
short development cycles.
OK, 'nuff said. Let's cut to the
chase.
In this article, we're going to demonstrate how to use JSP to
connect to a database, extract data from it, and use that data to build a
dynamic Web page. We'll be building a simple Web application in order to help
make the process clearer; this should also help you quantify how much easier (or
harder) JSP is to use, as compared to other server-side scripting languages you
may be familiar with.
If you're planning on trying out the examples below
(recommended), you'll need to download and install the mySQL database server,
available at
http://www.mysql.com/. mySQL is
a fast, reliable, open-source database management system, which offers a fair
amount of power at a price that should move you to tears - it's
free!
We'll be assuming that you've installed and configured mySQL, and
have the appropriate permissions to create and edit database
tables.
Since all database interaction in Java takes place using a
technology known as JDBC, or Java Database Connectivity, you'll also need a JDBC
module that allows you to connect to the mySQL database server. We'll be
assuming that you've downloaded the mm.mySQL JDBC module from
http://www.worldserver.com/mm.mysql/
, and configured it to talk to your mySQL database, as described in the article
"
Slapping
Together A JSP Development Environment"
If you're using a database
other than mySQL, fear not - JSP supports all major databases, and you can use
the techniques described over the next few pages to talk to other databases too.
You'll probably need to consult your database vendor's manual or Web site for
information on how to obtain the necessary software.
Finally, some
knowledge of SQL would come in handy. In case you don't know SQL, don't worry -
it's extremely simple, and a few minutes with the "
Speaking SQL"
tutorial will have you executing queries like an expert.
With all that
out of the way, let's actually get our hands dirty.