Java Reference
In-Depth Information
Example
A Microsoft Access database called
HomeDB.mdb
contains a table called
PhoneNums
, which has fi elds
Surname
,
Forenames
and
PhoneNum
. A User DSN
(Data Source Name) of
HomeDB
has been set up for the above database. (Refer
back to Chap.
7
for details of how to do this.) The initial HTML page (
JDBCServletTest.
html
) uses a form to accept a new record and then passes the values entered by the
user to a servlet that adds a record to the phone numbers table and displays the new
contents of this table. (Note that the use of the
<PRE>
tag below will produce
slightly differing output in different browsers.)
The HTML code for the initial page is shown below.
<!-- JDBCServletTest.html -->
<HTML>
<HEAD>
<TITLE>Database Insertion Form</TITLE>
</HEAD>
<BODY>
<H1><CENTER>Phonebook</CENTER><H1>
<FORM METHOD=POST ACTION="DbServlet">
<PRE>
Surname: <INPUT TYPE="Text" NAME="Surname">
Forenames: <INPUT TYPE="Text"
NAME="Forenames">
Phone number: <INPUT TYPE="Text"
NAME="PhoneNum">
</PRE>
<BR><BR>
<CENTER><INPUT TYPE="Submit"
VALUE="Commit"></CENTER>
</FORM>
</BODY>
</HTML>
Here's the code for servlet
DbServlet
:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*; //Don't forget this!
import javax.servlet.annotation.WebServlet;
@WebServlet("/DbServlet")
public class DbServlet extends HttpServlet
{
private Statement statement;
Search WWH ::
Custom Search