This document describes how to create a simple web application that connects to a MySQL database server. It also covers some basic ideas and technologies in web development, such as JavaServer Pages (JSP), JavaServer Pages Standard Tag Library (JSTL), the Java Database Connectivity (JDBC) API, and two-tier, client-server architecture. This tutorial is designed for beginners who have a basic understanding of web development and are looking to apply their knowledge using a MySQL database.
MySQL is a popular Open Source database management system commonly used in web applications due to its speed, flexibility and reliability. MySQL employs SQL, or Structured Query Language, for accessing and processing data contained in databases.
This tutorial continues from the Connecting to a MySQL Database tutorial and assumes that you have already created a MySQL database named MyNewDatabase, which you have registered a connection for in the NetBeans IDE. The table data used in that tutorial is contained in ifpwafcad.sql and is also required for this tutorial. This SQL file creates two tables, Subject and Counselor, then populates them with sample data. If needed, save this file to your computer, then open it in the NetBeans IDE and run it on the MySQL database named MyNewDatabase.
Contents

To follow this tutorial, you need the following software and resources.
Notes:
Simple web applications can be designed using a two-tier architecture, in which the application communicates directly with a data source using the Java Database Connectivity API. A user's requests are sent to a database, and the results are sent directly back to the user. Two-tier architectures can be easily mapped to a client-server configuration, where a user's browser serves as the client, and a remote database reachable over the Internet corresponds to the server.
The application you build in this tutorial involves the creation of two JavaServer Pages. In each of these pages, you add basic HTML to implement a simple interface, followed by SQL tags provided by JSTL technology in order to query the database. Consider the following client-server scenario.
The welcome page (index.jsp) presents the user with a simple HTML form. When a client requests the index.jsp page, the JSP code contained therein is parsed, and data from the Subject database table is gathered, added to the page, and sent to the client. The user makes a selection in the provided HTML form and submits, which causes the client to make a request for response.jsp. When response.jsp is parsed, data from both the Subject and Counselor tables is gathered and inserted into the page. Finally, the page is returned to the client and the user views data based upon his or her selection.
In order to implement the scenario described above, you develop a simple application for a fictitious organization named IFPWAFCAD, or The International Former Professional Wrestlers' Association for Counseling and Development. The application enables a user to choose a counseling subject from a drop-down list (index.jsp), then retrieves data from the MySQL database and returns the information to the user (response.jsp).


Create a new project in the IDE:
Begin by preparing a simple interface for the two pages. Both index.jsp and response.jsp implement an HTML table to display data in a structured fashion. index.jsp also requires an HTML form that includes a drop-down list.
Make sure index.jsp is opened in the Source Editor. If it is not already open, double-click index.jsp from IFPWAFCAD > Web Pages in the Projects window.

<table border="0">
<thead>
<tr>
<th>IFPWAFCAD offers expert counseling in a wide range of fields.</th>
</tr>
</thead>
<tbody>
<tr>
<td>To view the contact details of an IFPWAFCAD certified former
professional wrestler in your area, select a subject below:
</td>
</tr>
For the bottom row of the table, drag and drop an HTML form from the Palette into the page, directly between the second pair of <td> tags. In the Action text box, type in response.jsp, then click OK. Type in the following text between the <form> tags of the form you just created:
<strong>Select a subject:</strong>
Drag and drop a drop-down list from the Palette to a point just after the text you just added. In the Insert Drop-down dialog that displays, type in subject_id for the Name text field, and click OK. Note that the code snippet for the drop-down list is added to the form.
<body>
<h2>Welcome to <strong>IFPWAFCAD</strong>, the International Former
Professional Wrestlers' Association for Counseling and Development!
</h2>
<table border="0">
<thead>
<tr>
<th>IFPWAFCAD offers expert counseling in a wide range of fields.</th>
</tr>
</thead>
<tbody>
<tr>
<td>To view the contact details of an IFPWAFCAD certified former
professional wrestler in your area, select a subject below:
</td>
</tr>
<tr>
<td>
<form action="response.jsp">
<strong>Select a subject:</strong>
<select name="subject_id">
<option></option>
</select>
<input type="submit" value="submit" name="submit" />
</form>
</td>
</tr>
</tbody>
</table>
</body>
To view this page in a browser, right-click in the Source Editor and choose Run File (Shift-F6). When you do this, the JSP page is automatically compiled and deployed to your server. The IDE opens your default browser to display the page from its deployed location.
In order to prepare the interface for response.jsp you must first create the file in your application. Note that most of the content that displays in this page is generated dynamically using JSP technology. Therefore, in the following steps you add placeholders which you will later substitute for the JSP code.
In the Source Editor, change the title to IFPWAFCAD - {placeholder}. Remove the <h1>Hello World!</h1> (or <h1>JSP Page</h1> if you are working in NetBeans 6.0 or 6.1) line between the <body> tags, then copy and paste the following HTML table into the body of the page:
<table border="0">
<thead>
<tr>
<th colspan="2">{placeholder}</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Description: </strong></td>
<td><span style="font-size:smaller; font-style:italic;">{placeholder}</span></td>
</tr>
<tr>
<td><strong>Counselor: </strong></td>
<td>{placeholder}
<br>
<span style="font-size:smaller; font-style:italic;">
member since: {placeholder}</span>
</td>
</tr>
<tr>
<td><strong>Contact Details: </strong></td>
<td><strong>email: </strong>
<a href="mailto:{placeholder}">{placeholder}</a>
<br><strong>phone: </strong>{placeholder}
</td>
</tr>
</tbody>
</table>
To view this page in a browser, right-click in the Source Editor and choose Run File (Shift-F6). The page is compiled, deployed to your server, and opened in your default browser. Your response.jsp page should display similar to the following.
Create a simple stylesheet that enhances the interface display.
body {
font-family: Verdana, Arial, sans-serif;
font-size: smaller;
padding: 50px;
color: #555;
}
h1, h2 {
text-align: left;
letter-spacing: 6px;
font-size: 1.4em;
color: #be7429;
font-weight: normal;
width: 450px;
}
table {
width: 580px;
padding: 10px;
background-color: #c5e7e0;
}
th {
text-align: left;
border-bottom: 1px solid;
}
td {
padding: 10px;
}
a:link {
color: #be7429;
font-weight: normal;
text-decoration: none;
}
a:link:hover {
color: #be7429;
font-weight: normal;
text-decoration: underline;
}
Link the stylesheet to index.jsp and response.jsp:
<link rel="stylesheet" type="text/css" href="style.css">
This document assumes that you understand how the stylesheet functions, and how it affects corresponding HTML elements found in index.jsp and response.jsp.
When working with CSS in the IDE, you can take advantage of the CSS Style Builder and CSS Preview. Together, these tools provide extensive support for creating style rules and viewing elements when coupled with style attributes.
For example, place your cursor within the h1, h2 rule in style.css, then open CSS Preview (Window > Other > CSS Preview):
CSS Preview demonstrates how an element renders in a browser. Also note that the preview automatically refreshes as you make changes to a rule, providing a real-time textual representation of style elements from the IDE.
The most efficient way to implement communication between the server and database is to set up a database connection pool. Creating a new connection for each client request can be very time-consuming, especially for applications that continuously receive a large number of requests. To remedy this, numerous connections are created and maintained in a connection pool. Any incoming requests that require access to the application's data layer use an already-created connection from the pool. Likewise, when a request is completed, the connection is not closed down, but returned to the pool.
Both GlassFish and Tomcat contain Database Connection Pooling (DBCP) libraries that provide connection pooling functionality in a way that is transparent to you as a developer. In either case, you need to configure a JNDI Datasource for the server that creates an interface which your application can use for connection pooling. Depending on whether you are using GlassFish or Tomcat, do the following:
The IDE provides enhanced support for GlassFish, enabling you to specify resources using a wizard:
By completing the wizard, you declared a new datasource and connection pool for the application. In the Projects window, open the newly created Server Resources > sun-resources.xml file and note that, within the <resources> tags, a jdbc resource and connection pool have been declared containing the values you previously specified.
To confirm that a new datasource and connection pool are indeed registered with GlassFish, you can deploy the project to the server, then locate the resources in the IDE's Services window:

Configure a JNDI Datasource in Tomcat by adding a declaration for your resource to the application's context.xml file. This is the application's context container, which enables you to specify application meta-data necessary for the server in order to deploy and run the application. There are various locations where you can specify context elements, such as your server's global $CATALINA_HOME/conf/context.xml file. By adding resource declarations to your application's context.xml file however, you limit the resource to that application, and do not need to configure anything within the server itself. For more information, see the Apache Tomcat Configuration Reference.
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/IFPWAFCAD">
<Resource name="jdbc/IFPWAFCAD" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="nbuser" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/MyNewDatabase"/>
</Context>
For a more thorough explanation of JNDI DataSource configuration, including a description of the parameters used in the above resource declaration, refer to the Apache Tomcat 6.0 JNDI Datasource HOW-TO.You need to reference the JNDI resource you just configured from the web application. To do so, you can create an entry in the application's deployment descriptor (web.xml).
Deployment descriptors are XML-based text files that contain information describing how an application is to be deployed to a specific environment. For example, they are normally used to specify application context parameters and behavioral patterns, security settings, as well as mappings for servlets, filters and listeners.
Do the following to reference the JNDI Datasource in the application's deployment descriptor.

<resource-ref>
<description>Database for IFPWAFCAD application</description>
<res-ref-name>jdbc/IFPWAFCAD</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
Adding the database driver's JAR file is another step that is vital to enabling the server to communicate with your database. Ordinarily, you would need to locate your database driver's installation directory and copy the mysql-connector-java-5.x-bin.jar file from the driver's root directory into the library folder of the server you are using. Fortunately, the IDE is able to detect at deployment whether the JAR file has been added - and if not, it does so automatically.
In order to demonstrate this, deploy your application to the server you are using. In the Projects window, choose Deploy (or Undeploy and Deploy) from the right-click menu of the project node and, depending on the server you are using, do the following.

If you return to the index.jsp and response.jsp placeholders created earlier in the tutorial, you can add JSP and JSTL code to enable pages to generate content dynamically, i.e., based on user input. To do so, you need to perform the following 3 steps:
In order to make better use of the JSP resources at your disposal, you can make use of the JavaServer Pages Standard Tag Library (JSTL) to access and display data taken from the Logic Layer. This library comes bundled with the IDE. You therefore need to make sure the JSTL library is added to the web project's compilation classpath, then add the relevent taglib directives to each of the JSP pages. This allows the server we are using to identify the tags when it reads them from the JSP pages. Depending on whether you are using GlassFish or Tomcat, do the following:
Do nothing! GlassFish includes the JSTL library by default. You can verify this by expanding the Libraries > GlassFish node. The appserv-jstl.jar file defines all standard tags in the JSTL library.
Regardless of what server you are using, you need to add the necessary taglib directives to JSP pages:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
Finally, add the code to each page. Both pages require that you implement an SQL query that utilizes the JSTL <sql:query> tags and the datasource created earlier in the tutorial.
In order to dynamically display the contents of the form in index.jsp, you need to access all names from the Subject database table:
<sql:query var="subjects" dataSource="jdbc/IFPWAFCAD">
SELECT subject_id, name FROM Subject
</sql:query>
The JSTL <sql:query> tags enable you to use SQL query language directly in a JSP page. A resultset is generated from the query, and the acquired data can then be inserted into the page using an iterator tag (<c:forEach>) from the JSTL core library. Replace the empty <option> tags in the HTML form with the following iterator (changes in bold):
<select name="subject_id">
<c:forEach var="subject" items="${subjects.rows}">
<option value="${subject.subject_id}">${subject.name}</option>
</c:forEach>
</select>
The forEach tag loops through all id and name values from the generated resultset, and inserts each pair into the HTML option tags. In this manner, the form's drop-down list is populated with data. Save changes (Ctrl+S), then right-click in the Source Editor and choose Run File (Shift-F6). The file is compiled and deployed to the server, and index.jsp renders in the browser. The drop-down list now contains subject names that were retrieved from the database:
For response.jsp, you need to access data from both the Subject and Counselor tables that correspond to the id submitted by the user. This is accomplished using an SQL query and the datasource created earlier in the tutorial:
<sql:query var="counsSubjRs" maxRows="1" dataSource="jdbc/IFPWAFCAD">
SELECT s.name, s.description, c.first_name, c.nick_name,
c.last_name, c.member_since, c.telephone, c.email
FROM Subject as s, Counselor as c
WHERE c.counselor_id = s.counselor_idfk
AND s.subject_id = ? <sql:param value="${param.subject_id}"/>
</sql:query>
A resultset named counsSubjRs is generated from the above SQL query, which contains all data associated with the subject_id submitted by the user. Note that data from the Counselor table is acquired by mapping counselor_idfk from Subject to counselor_id from Counselor. Add the following declaration beneath the SQL query from the previous step:
<c:set var="counsSubj" scope="request" value="${counsSubjRs.rows[0]}"/>
The <c:set> tag enables you to set the resultset to a scoped variable, so that you can retrieve its contents at a later stage. In the HTML, replace all placeholders with JSP code that allows you to retrieve and display the data held in the counsSubj resultset (Changes below shown in bold):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="style.css">
<title>${counsSubj.name}</title>
</head>
<body>
<table>
<tr>
<th colspan="2">${counsSubj.name}</th>
</tr>
<tr>
<td><strong>Description: </strong></td>
<td><span style="font-size:smaller; font-style:italic;">${counsSubj.description}</span></td>
</tr>
<tr>
<td><strong>Counselor: </strong></td>
<td><strong>${counsSubj.first_name} ${counsSubj.nick_name} ${counsSubj.last_name}</strong>
<br><span style="font-size:smaller; font-style:italic;">
<em>member since: ${counsSubj.member_since}</em></span></td>
</tr>
<tr>
<td><strong>Contact Details: </strong></td>
<td><strong>email: </strong>
<a href="mailto:${counsSubj.email}">${counsSubj.email}</a>
<br><strong>phone: </strong>${counsSubj.telephone}</td>
</tr>
</table>
</body>
</html>
Whether you are using the GlassFish application server or Tomcat, the process for deploying your project is the same. If you installed GlassFish or Tomcat through the IDE download, your server is already registered in the IDE. If you need to make any changes to server settings, or would like to register a different server with the IDE, choose Tools > Servers from the main menu to open the Server Manager.
To deploy the IFPWAFCAD project to the server:
To run the application:

This concludes the Creating a Simple Web Application Using a MySQL Database tutorial. This document demonstrated how to create a simple web application that connects to a MySQL database. It also demonstrated how to construct an application using a basic two-tier architecture, and utilized JSTL and JSP technologies as a means of accessing and displaying data dynamically.
For related or more advanced tutorials, see the following resources:
You are viewing a mobilized version of this site...
View original page here