Search

Hooking Up To A Database Using Servlets

8 min read
0 views

Preparing Your Workspace and Dependencies

Before you write a single line of servlet code, you need a stable foundation. The first thing to do is install the Java Development Kit (JDK). In this walkthrough we use JDK 8, but any 1.8‑compatible release works fine. Grab the installer from Oracle or adoptOpenJDK, run it, and verify the installation by opening a terminal and typing java -version. You should see a Java runtime and compiler listed.

Next, download the MySQL JDBC driver, the mysql-connector-java‑version.jar file. This JAR allows Java to talk to MySQL using the standard JDBC API. Place the file in a folder named jdbc_drivers inside your home directory for easy reference.

On Windows, you’ll need to set a few environment variables so that the Java Virtual Machine can locate both the JDK and the JDBC driver. Create a user variable called CLASSPATH and point it to the driver path. For example, if the driver sits in C:\Users\yourname\jdbc_drivers, set CLASSPATH to C:\Users\yourname\jdbc_drivers\mysql-connector-java-8.0.32.jar;. Note the trailing semicolon – it signals the end of a path entry.

Similarly, adjust the Path system variable to include the JDK's bin folder. Append C:\Program Files\Java\jdk-17\bin; to the list. Once both variables are configured, open a new terminal window and run javac -version to confirm the compiler is accessible. This step ensures that any subsequent build processes will locate the required tools.

With the JDK and driver ready, choose a servlet container. Tomcat is the most widely used choice, and the community edition is free. Download the latest 9.x release, unzip it to C:\apache-tomcat-9.0.x, and start the server by running startup.bat (Windows) or startup.sh (Unix). Verify that Tomcat is running by visiting http://localhost:8080 – you should see the Tomcat welcome page. The container will host your servlet once you deploy it.

Before deploying, create a MySQL database named guestbook and a table to hold entries. The schema is intentionally simple: an auto‑incremented primary key, fields for email, name, company, and a handful of vehicle selections. The table also stores the visitor’s IP address and the operating system reported by the servlet container. You can run the following SQL script inside the MySQL client or any GUI tool:

Prompt
CREATE DATABASE guestbook;</p> <p>USE guestbook;</p> <p>CREATE TABLE guestbook (</p> <p> entry_id INT NOT NULL AUTO_INCREMENT,</p> <p> email VARCHAR(40) NULL,</p> <p> firstName VARCHAR(40) NULL,</p> <p> lastName VARCHAR(40) NULL,</p> <p> company VARCHAR(40) NULL,</p> <p> golf VARCHAR(3) NULL,</p> <p> jetta VARCHAR(3) NULL,</p> <p> passat VARCHAR(3) NULL,</p> <p> cabrio VARCHAR(3) NULL,</p> <p> ip_address VARCHAR(20) NULL,</p> <p> servlet_os VARCHAR(20) NULL,</p> <p> created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,</p> <p> PRIMARY KEY (entry_id)</p> <p>);</p>

After creating the table, you can test connectivity by running a simple JDBC script that opens a connection and queries the guestbook table. If the script succeeds, you’re ready to write the servlet that will insert new entries. With the environment set up and the database in place, we can focus on the core servlet logic.

Crafting a Simple Guestbook Database

The design of the database dictates how the servlet will interact with it. Each row represents a guestbook submission and includes metadata that can be useful for analysis later. The entry_id column is a surrogate key that automatically increments, ensuring a unique identifier for each record without requiring additional logic. The created timestamp is generated by MySQL itself, capturing the exact moment the row was inserted.

The other columns are straightforward string fields. For the email address and name fields, a 40‑character limit is more than enough for most scenarios. The company field offers a place for users to indicate their employer or affiliation. The four vehicle columns - golf, jetta, passat, cabrio - store short flags, typically “yes” or “no”, that reflect whether the visitor selected a particular VW model. Storing the selections as strings keeps the table flexible; if a future model needs to be added, a new column can be appended without altering existing rows.

Storing the visitor’s IP address and the servlet container’s reported operating system can help diagnose issues or detect spam. The ip_address column pulls the remote address from the HTTP request, while servlet_os reads the system property os.name. Both are capped at 20 characters, a length sufficient for IPv4 addresses and most OS names.

With the schema defined, you can use the MySQL client or a graphical front‑end such as MySQL Workbench to test the table. Insert a dummy row manually and verify that the created field auto‑populates and that entry_id increments correctly. Once you confirm that the table behaves as expected, you can rely on it as a robust backend for your servlet. Remember that any changes to the schema - adding columns, renaming fields, or altering types - should be reflected in both the database and the servlet code to avoid runtime errors.

In a real application, you might also consider indexing frequently queried columns, enforcing non‑null constraints on critical fields, or using foreign keys to relate guestbook entries to other tables. However, for this demonstration the simple structure suffices and keeps the code easier to understand. The next step is to build the servlet that will interact with this table using JDBC.

Implementing the Guestbook Servlet

The servlet’s responsibility is threefold: establish a JDBC connection to the database, retrieve form data from the HTTP request, and persist that data into the guestbook table. Because the servlet will run inside Tomcat, the init() method is the ideal place to load the JDBC driver and open the connection. Tomcat will call init() once when the servlet is first loaded, so you only pay the cost of creating the driver once.

Here’s a minimal version of the GuestbookServlet class that follows best practices. The code is deliberately simple, but each step is fully explained in comments so you can see why it is written that way. The servlet is declared as a public class that extends HttpServlet, and it imports the required JDBC, servlet, and I/O packages.

Prompt
import java.io.*;</p> <p>import java.sql.*;</p> <p>import javax.servlet.*;</p> <p>import javax.servlet.http.*;</p> <p>public class GuestbookServlet extends HttpServlet {</p> <p> private Connection connection;</p> <p> public void init(ServletConfig config) throws ServletException {</p> <p> super.init(config);</p> <p> try {</p> <p> Class.forName("com.mysql.cj.jdbc.Driver");</p> <p> String url = "jdbc:mysql://localhost:3306/guestbook?useSSL=false&serverTimezone=UTC";</p> <p> connection = DriverManager.getConnection(url, "guestuser", "guestpass");</p> <p> } catch (Exception e) {</p> <p> e.printStackTrace();</p> <p> throw new ServletException("Database connection failed", e);</p> <p> }</p> <p> }</p> <p> public void doPost(HttpServletRequest req, HttpServletResponse res)</p> <p> throws ServletException, IOException {</p> <p> String email = req.getParameter("Email");</p> <p> String firstName = req.getParameter("FirstName");</p> <p> String lastName = req.getParameter("LastName");</p> <p> String company = req.getParameter("Company");</p> <p> // Check required fields</p> <p> if (email == null || email.isEmpty() ||</p> <p> firstName == null || firstName.isEmpty() ||</p> <p> lastName == null || lastName.isEmpty()) {</p> <p> res.setContentType("text/html");</p> <p> PrintWriter out = res.getWriter();</p> <p> out.println("<h3>Please fill in all required fields.</h3>");</p> <p> out.close();</p> <p> return;</p> <p> }</p> <p> // Vehicle selections – treat unchecked boxes as null</p> <p> String golf = req.getParameter("golf") != null ? "yes" : "no";</p> <p> String jetta = req.getParameter("jetta") != null ? "yes" : "no";</p> <p> String passat = req.getParameter("passat") != null ? "yes" : "no";</p> <p> String cabrio = req.getParameter("cabrio") != null ? "yes" : "no";</p> <p> String ipAddress = req.getRemoteAddr();</p> <p> String servletOs = System.getProperty("os.name");</p> <p> // Insert into database</p> <p> boolean success = insertEntry(email, firstName, lastName, company,</p> <p> golf, jetta, passat, cabrio, ipAddress, servletOs);</p> <p> res.setContentType("text/html");</p> <p> PrintWriter out = res.getWriter();</p> <p> if (success) {</p> <p> out.println("<h2>Thank you, " + firstName + ", for registering.</h2>");</p> <p> } else {</p> <p> out.println("<h2>An error occurred. Please try again later.</h2>");</p> <p> }</p> <p> out.close();</p> <p> }</p> <p> private boolean insertEntry(String email, String firstName, String lastName,</p> <p> String company, String golf, String jetta,</p> <p> String passat, String cabrio,</p> <p> String ip, String os) {</p> <p> String sql = "INSERT INTO guestbook (email, firstName, lastName, company, " +</p> <p> "golf, jetta, passat, cabrio, ip_address, servlet_os) " +</p> <p> "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";</p> <p> try (PreparedStatement stmt = connection.prepareStatement(sql)) {</p> <p> stmt.setString(1, email);</p> <p> stmt.setString(2, firstName);</p> <p> stmt.setString(3, lastName);</p> <p> stmt.setString(4, company);</p> <p> stmt.setString(5, golf);</p> <p> stmt.setString(6, jetta);</p> <p> stmt.setString(7, passat);</p> <p> stmt.setString(8, cabrio);</p> <p> stmt.setString(9, ip);</p> <p> stmt.setString(10, os);</p> <p> stmt.executeUpdate();</p> <p> return true;</p> <p> } catch (SQLException e) {</p> <p> return false;</p> <p> }</p> <p> }</p> <p> public void destroy() {</p> <p> try {</p> <p> if (connection != null && !connection.isClosed()) {</p> <p> connection.close();</p> <p> }</p> <p> System.err.println("Problem closing the database connection");</p> <p> }</p> <p> }</p> <p>}</p>

The servlet uses a PreparedStatement rather than string concatenation to guard against SQL injection and to handle escaping automatically. The init() method builds a JDBC URL that points to the local MySQL instance, disables SSL for simplicity, and sets the server timezone to UTC. Replace guestuser and guestpass with credentials that have SELECT and INSERT rights on the guestbook database.

When the servlet receives a POST request, it pulls the form parameters. Fields marked with an asterisk in the HTML form are mandatory; the servlet checks them and returns an error message if any are missing. For the vehicle checkboxes, the servlet assigns “yes” if the parameter exists (i.e., the box was checked) and “no” otherwise. This logic keeps the database entries consistent regardless of how many boxes the user selects.

The servlet’s destroy() method closes the JDBC connection when Tomcat shuts down the servlet. Properly closing resources is a good habit, especially in a long‑running environment. If the connection is lost or the database becomes unreachable, the servlet will throw an exception that can be handled more gracefully in a production build.

Connecting the Form and Deploying the App

The front‑end for this guestbook is a plain HTML form that submits user input to the servlet. The form must use the POST method and point its action URL to the servlet’s mapping. In Tomcat, you define the mapping in the web.xml file inside the WEB-INF directory. Add the following snippet:

Prompt
<servlet></p> <p> <servlet-name>GuestbookServlet</servlet-name></p> <p> <servlet-class>GuestbookServlet</servlet-class></p> <p></servlet></p> <p><servlet-mapping></p> <p> <url-pattern>/guestbook</url-pattern></p> <p></servlet-mapping></p>

Once the mapping is in place, the form can send data to http://localhost:8080/guestbook. The following HTML demonstrates a simple form with fields for the user’s email, name, company, and vehicle preferences. The required fields are clearly marked. The form’s style is minimal, but you can enhance it with CSS or JavaScript as needed.

Prompt
<!DOCTYPE html></p> <p><html lang="en"></p> <p><head></p> <p> <meta charset="UTF-8"></p> <p> <title>Guestbook Form</title></p> <p></head></p> <p><body style="background:#9999FF"></p> <p> <h1 style="color:#000099">Guestbook Demo</h1></p> <p> <p style="color:#000099">Please fill in the form below to add an entry to the guestbook.</p></p> <p> <form action="http://localhost:8080/guestbook" method="post"></p> <p> <label>Email address: <span style="color:red'>*</span><br></p> <p> <input type="email" name="Email" required></label><br></p> <p> <label>First name: <span style="color:red'>*</span><br></p> <p> <input type="text" name="FirstName" required></label><br></p> <p> <label>Last name: <span style="color:red'>*</span><br></p> <p> <input type="text" name="LastName" required></label><br></p> <p> <label>Company:<br></p> <p> <input type="text" name="Company"></label><br></p> <p> <fieldset></p> <p> <legend>Select the VW models you like:</legend></p> <p> <label><input type="checkbox" name="golf"> VW Golf</label><br></p> <p> <label><input type="checkbox" name="jetta"> VW Jetta</label><br></p> <p> <label><input type="checkbox" name="passat"> VW Passat</label><br></p> <p> <label><input type="checkbox" name="cabrio"> VW Cabrio</label><br></p> <p> </fieldset></p> <p> <input type="submit" value="Submit"></p> <p> </form></p> <p></body></p> <p></html></p>

Save this file as guestbook.html and place it in the webapps/ROOT directory of your Tomcat installation. Now open a web browser, navigate to http://localhost:8080/guestbook.html, and try submitting the form. If everything is wired correctly, you should see a thank‑you message and the new record should appear in the MySQL table.

When you deploy to a production environment, consider the following best practices: move database credentials out of the source code into a secure configuration file or environment variable; enable SSL between the servlet and the database; and use connection pooling to improve performance. For a small demo or a learning exercise, the straightforward approach shown here keeps the focus on the core concepts: establishing a JDBC connection, handling form data, and persisting it with a servlet.

That completes the round‑trip from a user’s browser to the database via a Java servlet. The steps illustrate how to prepare the development environment, design a simple schema, write the servlet, and tie everything together with an HTML form. You now have a working guestbook that demonstrates database connectivity in Java, ready to be extended or customized for your own projects.

Suggest a Correction

Found an error or have a suggestion? Let us know and we'll review it.

Share this article

Comments (0)

Please sign in to leave a comment.

No comments yet. Be the first to comment!

Related Articles