You are on page 1of 47

Connecting to a MySQL Database in NetBeans IDE

Contributed and maintained by Troy Giunipero .

This document demonstrates how to configure MySQL on your system and set up a connection to the database from NetBeans IDE. Once connected, you can begin
working with MySQL in the IDE's Database explorer by creating new tables, populating tables with data, and running SQL queries on database structures and content.
This tutorial is designed for beginners with a basic understanding of database management and application development, who want to apply their knowledge in working
with MySQL in NetBeans IDE.

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.

Note: This document uses the NetBeans IDE 5.5 Release. If you are using NetBeans IDE 6.5, see Connecting to a MySQL Database.

Expected duration: 25 minutes

The following topics are covered below:

 Getting the Software


 Installing and Configuring the Database
 Creating a Database Instance
 Registering the Database in NetBeans IDE
 Creating Database Tables
 Working with Table Data
 Running an SQL Script
 Next Steps
Getting the Software
Before you begin, make sure you have the following software installed on your computer:

1. NetBeans IDE 5.5 (download)


2. Java SE Development Kit (JDK™) version 5.0 or higher (download)
3. MySQL database (download)
4. JDBC Driver for MySQL (download)

Note: As an alternative to downloading the IDE and JDK separately, consider downloading the Java SE Development Kit 6u1 with NetBeans IDE 5.5 Bundle.

Installing and Configuring the Database


If you already have the MySQL database set up and running on your machine, please skip ahead to Registering the Database in NetBeans IDE. By way of example, this
tutorial demonstrates how to run the MySQL Community Server on Windows XP. To get the MySQL server running:

1. Run the self-extracting file. The MySQL Setup Wizard opens to guide you through the installation process. Accept all default settings.
2. Upon completing installation, allow the MySQL wizard to immediately configure the server by making sure the Configure the MySQL Server Now checkbox is
selected. This will allow an instance of the server to be created, which will run as a Windows service on your machine.
3. In the MySQL Server Instance Configuration wizard, select Standard Configuration. Click Next. When you arrive at the step allowing you to set Windows
options, select the Include Bin Directory in Windows PATH checkbox. This will later allow you to perform a simple check to make sure the MySQL service is up
and running:

4. Set the root password to: nbuser. Finally, click Execute to allow the wizard to generate the server instance on your computer. If you encounter any problems,
refer to the MySQL Reference Manual included in your installation or the online documentation.
Before continuing further, it is important to understand the components found in MySQL's root directory:

 The bin subdirectory contains the scripts for executing utilities and setting up the environment.
 The data subdirectory contains all database instances, including their data.
 The Docs subdirectory contains the MySQL Reference Manual.
 The share subdirectory contains localization files, including character sets and language packages.
 The my.ini file is the configuration file that was generated by the Configuration wizard, and contains information such as the port being listened on, path to
installation directory, path to database root, and default character set.

Creating a Database Instance


Now that the MySQL database server is installed and configured, you can create a database instance which you will later connect to in NetBeans IDE. To create a new
database instance:

1. Open up the MySQL Command Line Client from your Start > All Programs > MySQL menu. The Command Line client displays prompting you to enter your
root password.
2. Enter the password specified above (nbuser), and a brief welcome message displays, introducing you to the MySQL monitor.
3. Type create database MyNewDatabase; at the prompt. You should receive a Query OK message, indicating that the new database has been created.
4. To verify that MyNewDatabase has indeed been created, type show databases; at the prompt. A list is displayed, showing all databases maintained by the server.
Note that MyNewDatabase is listed:

Registering the Database in NetBeans IDE


Now that you have the database server installed and configured, and have created a new database, you can register the MySQL server in NetBeans IDE. Begin by
examining the functionality offered by the Database explorer located in the IDE's Runtime window (Ctrl+5). The Database explorer is represented by the Databases

node ( ). From this interface you can connect to databases, view current connections, add database drivers, as well as create, browse or edit database structures.

You can use the Database explorer to register MySQL in the IDE. There are two simple steps that need to be performed:

1. Adding the Driver to the IDE


2. Creating a Database Connection

Adding the Driver to the IDE

In order to allow NetBeans IDE to communicate with a database, you need to employ a Java-based driver. Generally speaking, drivers in NetBeans IDE use the JDBC
(Java Database Connectivity) API to communicate with databases supporting SQL. The JDBC API is contained in the java.sql Java package. A driver therefore serves
as an interface that converts JDBC calls directly or indirectly into a specific database protocol.

In this tutorial, you are using the MySQL Connector/J driver, which is a pure Java implementation of the JDBC API, and communicates directly with the MySQL
server using the MySQL protocol. To add the driver to the IDE:

1. If you have just downloaded the driver, first extract it to a location on your computer. Set the root directory to: C:\mysql-connector-java-5.0.5.
2. In the IDE, in the Database explorer from the Runtime window (Ctrl+5) expand the Databases node and right-click the Drivers node. Choose New Driver. The
New JDBC Driver dialog opens.
3. Click the Add button in the top right corner. Navigate to the driver's root directory and select the driver's jar file (e.g. mysql-connector-java-5.0.5-bin.jar).
Click Open. The New JDBC Driver dialog should look like this:

4. Click OK. In the Runtime window expand the Databases > Drivers nodes and note that a new MySQL driver node is displayed:
Note: While you just made the database driver available to the IDE, you have not yet made it available to any specific application. At this stage, you can use the IDE to
access and modify the database, but cannot do so from an application yet. This is covered in the follow-up tutorial Creating a Simple Web Application in NetBeans IDE
using MySQL.

Creating a Database Connection

You can now set up a connection to the database through the appropriate driver. Make sure your database service is running prior to continuing. You can do so by
performing the following simple test:

1. Open a Windows command shell (from the Start menu, choose Run and type cmd in the text field). A command line window displays.
2. At the prompt, type sc query MySQL and press Enter. The Windows sc command allows you to query the state of services. The output should indicate that the
current state of the MySQL service is RUNNING:

If the service is STOPPED, you can start it by either typing sc start MySQL at the command line prompt, or using the Windows Services GUI (Start > Control
Panel > Administrative Tools > Services).

Now, in NetBeans IDE, create a connection to MyNewDatabase:

1. In the Runtime window (Ctrl+5) choose Connect Using from the right-click menu of the driver you just added. The New Database Connection dialog opens.
2. In the Basic Setting tab, enter the Database's URL in the corresponding text field. The URL is used to identify the type and location of a database server. In this
example, you need to specify the host name (i.e. the location of the server), the port number on which the database communicates, and the name of the database
instance being used. In this case you can enter: jdbc:mysql://localhost:3306/MyNewDatabase.
3. For User Name and Password, enter root, and nbuser respectively:

4. Click OK, then click OK again to exit the dialog. A new Connection node displays in the Runtime window's Database explorer under the Databases node:
You are now connected to MyNewDatabase in the IDE. Note that the new connection node icon appears whole ( ) when you are connected to a database. Likewise, it

appears broken ( ) when there is no connection.

At later stages, when working with databases through the Database explorer, you may need to manually connect to a database. You can do so by right-clicking the
broken database connection node and choosing Connect.

Creating Database Tables


Now that you have connected to the database, you can begin exploring how to create tables, populate them with data, and modify data maintained in tables. This allows
you to take a closer look at the functionality offered by the Database explorer, as well as NetBeans IDE's support for SQL files. As an example, you can prepare the
database for use in the web application developed in the follow-up tutorial Creating a Simple Web Application in NetBeans IDE using MySQL.

The MyNewDatabase database that you are using is currently empty. In NetBeans IDE it is possible to add a database table by either using the Create Table dialog, or by
inputting an SQL query and running it directly from the SQL editor. Here you can explore both methods:

1. Using the Create Table Dialog


2. Using the SQL Editor

Using the Create Table Dialog

1. In the Database explorer, expand the MyNewDatabase connection node ( ) and note that there are three subfolders: Tables, Views and Procedures. Right-click
the Tables node and choose Create Table. The Create Table dialog opens.
2. In the Table Name text field, type Subject.
3. In the first row displayed, select the Key check box. You are specifying the primary key for your table. All tables found in relational databases must contain a
primary key. Note that when you select the Key check box, the Index and Unique check boxes are also automatically selected and the Null check box is deselected.
This is because primary keys are used to identify a unique row in the database, and by default form the table index. Because all rows need to be identified,
primary keys cannot contain a Null value.
4. For Column Name, enter id. For Data Type, select SMALLINT from the drop-down list. Then click the Add Column button.
5. Repeat this procedure by specifying all remaining fields, as shown in the table below:

Key Index Null Unique Column name Data type Size

[checked] [checked] [checked] id SMALLINT 0

[checked] name VARCHAR 50

[checked] description VARCHAR 500

[checked] counselor_idfk SMALLINT 0

6. You are creating a table named Subject that will hold the following data for each record:

o Name
o Description
o Counselor ID

When you are sure that your Create Table dialog contains the same specifications as those shown above, click OK. The IDE generates the Subject table in the

database, and you see a new Subject table node ( ) display under Tables in the Database explorer. Beneath the table node there are the columns (fields) you

created, starting with the primary key ( ):

Using the SQL Editor

1. In the Database explorer, right-click the Tables node beneath the MyNewDatabase connection node and choose Execute Command. A blank canvas opens in the
SQL Editor in the main window.
2. In the SQL Editor, type in the following query. This is a table definition for the Counselor table you are about to create:
3. CREATE TABLE Counselor (
4. id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
5. first_name VARCHAR (50),
6. nick_name VARCHAR (50),
7. last_name VARCHAR (50),
8. telephone VARCHAR (25),
9. email VARCHAR (50),
10. member_since DATE DEFAULT '0000-00-00',
11. PRIMARY KEY (id)
12. );

Note: Queries formed in the SQL Editor are parsed in Structured Query Language (SQL). SQL adheres to strict syntax rules which you should be familiar with
when working in the IDE's Editor. Upon running a query, feedback from the SQL engine is generated in the Output window indicating whether execution was
successful or not.

13. Click the Run SQL ( ) button in the task bar at the top (or, press Ctrl+Shift+E to execute the query). You should receive the following message in the Output
window:

14. To verify changes, right-click the Tables node in the Database explorer and choose Refresh. The Refresh option updates the Database explorer's UI component to
the current status of the specified database. This step is necessary when running queries from the SQL Editor in NetBeans IDE. Note that the new Counselor

table node ( ) now displays under Tables in the Database explorer.

Working with Table Data


In order to work with table data, you can make use of the SQL Editor in NetBeans IDE. By running SQL queries on a database, you can add, modify and delete data
maintained in database structures. To add a new record (row) to the Counselor table, do the following:

1. Choose Execute Command from the Counselor table node in the Database explorer. A blank canvas opens in the SQL Editor in the main window.
2. In the SQL Editor, type in the following query:
3. INSERT INTO Counselor
VALUES (1, 'Ricky', '"The Dragon"', 'Steamboat','334 612-5678', 'r_steamboat@ifpwafcad.com', '1996-01-01')

4. Click the Run SQL ( ) button in the task bar at the top, or press Ctrl+Shift+E to execute the query. You should receive a message in the Output window
indicating that the query was executed successfully.
5. To verify that the new record has been added to the Counselor table, in the Database explorer, right-click the Counselor table node and choose View Data. A new
SQL Editor pane opens in the main window. When you choose View Data, a query to select all the data from the table is automatically generated in the upper
region of the SQL Editor. The results of the statement are displayed in a table view in the lower region. In this example, the Counselor table displays. Note that a
new row has been added with the data you just supplied from the SQL query:

Running an SQL Script


Another way to manage table data in NetBeans IDE is by running an external SQL script directly in the IDE. If you have created an SQL script elsewhere, you can
simply open it in NetBeans IDE and run it in the SQL Editor.

For demonstrative purposes, download ifpwafcad.sql and save it to a location on your computer. This script creates two tables similar to what you just created above
(Counselor and Subject), and immediately populates them with data. To run this script on MyNewDatabase:

1. Choose File > Open File (Ctrl+O) from the IDE's main menu. In the file browser navigate to the location where you previously saved ifpwafcad.sql and click
Open. The script automatically opens in the SQL Editor.
2. Make sure your connection to MyNewDatabase is selected from the Connection drop-down box in the tool bar at the top of the Editor:
3. Click the Run SQL ( ) button in the SQL Editor's task bar. The script is executed against the selected database, and any feedback is generated in the Output
window.
4. To verify changes, right-click the MyNewDatabase connection node in the Runtime window and choose Refresh. The Refresh option updates the Database
explorer's UI component to the current status of the specified database. Note that the two new tables from the SQL script now display as a table nodes under
MyNewDatabase in the Database explorer.
5. To view the data contained in the new tables, choose View Data from the right-click menu of a selected table node. In this manner, you can compare the tabular
data with the data contained in the SQL script to see that they match.

Creating a Simple Web Application in NetBeans IDE Using MySQL

Contributed and maintained by Troy Giunipero .

This document describes how to create a simple distributed web application that connects to a MySQL database. It also covers some basic ideas and technologies in web
development, such as Java Server Pages and three-tier architecture. This tutorial is designed for beginners who have a basic understanding of Java programming and web
development and are looking to apply their knowledge using MySQL.

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 already have a connection to a MySQL database created and configured in NetBeans
IDE. The table data that is included in ifpwafcad.sql. is also required for this tutorial. This SQL file creates two tables, Counselor and Subject, then populates them with sample

data. Save this file to a local directory, then open it in NetBeans and run it on the MySQL database. In this tutorial, the database we are working in is named MyNewDatabase.

Note: This document uses the NetBeans IDE 5.5 Release. If you are using NetBeans IDE 6.x, see Creating a Simple Web Application using a MySQL Database.

Expected duration: 40 minutes


The following topics are covered below:

 Getting the Software

 Planning the Structure

 Creating a New Project

 Preparing the Web Pages

 Deploying to the Server

 Implementing the Data Layer

 Implementing the Logic Layer

 Implementing the Presentation Layer

 Next Steps

Getting the Software

Before you begin, make sure you have the following software installed on your computer:

 NetBeans IDE 5.5 (download)

 Java SE Development Kit (JDK™) version 5.0 or higher (download)

 MySQL database (download)

 JDBC Driver for MySQL (download)


 Sun Java System Application Server (download)

Note: The Sun Java System Application Server (SJSAS) is not strictly required to work through this tutorial, as you can use Tomcat, which is a web server that comes bundled with

NetBeans IDE. However, if you are planning on developing applications in the IDE, the application server offers a lot of support for tools and technologies that can make a
developer's life easier. Consider downloading the Java EE 5 Tools Bundle, which includes SJSAS, NetBeans IDE, as well as the Java SE Development Kit. Find out more by visiting
the SJSAS product page.

Planning the Structure

Simple web applications are often designed using a three-tier architecture, in which the user interface, the functional process logic, and the data access and storage are all

maintained independently from each other. In other words, each of the three tiers, or layers, represents a module which can be run on its own platform (hence the term
'distributed').

For the application you are building in this tutorial, the Presentation Layer, or user interface, can be represented by JSP pages which prepare the HTML that is sent to the client
browser. You can code the middle, or Logic, layer with a few simple Java classes. Finally, the Data Layer can be implemented using several tables in a MySQL database. Consider
the following client-server scenario:
A welcome page (index.jsp) displays in a browser containing a simple form allowing a visitor to specify data. When a request is passed to the server containing the data, a JSP

page is accessed (response.jsp), which immediately passes the specified data to SubjectCounselor.java so that the information retrieval process can begin. The Java class

processes the data and employs AccessDB.java to prepare an SQL query to be sent to the database. AccessDB.java then connects to the database and subsequently retrieves data

from the Subject and Counselor tables, as specified by the SQL query. Finally, the return trip is initiated, and the retrieved data is included in response.jsp which forms the

server's response to the client.

Creating a New Project


In order to implement the scenario described above, you will 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):

index.jsp response.jsp

Create a new project in the IDE by performing the following steps:

1. Launch NetBeans IDE and choose New Project (Ctrl+Shift+N) from the File menu. Under Categories select Web; under Projects select Web Application. Click Next.

2. In Project Name, enter IFPWAFCAD. From the Server drop-down list, select the server you plan work with. Leave all other settings at their defaults and click Finish.

Note: If you downloaded the SJSAS but have not yet registered it in NetBeans IDE, you can do so by clicking the Manage button to the right of the Server drop-down list.

The Server Manager opens, enabling you to register the new server. For more information, refer to Registering a Sun Java System Application Server Instance from the

IDE's Help Contents (F1).

The IDE creates a project template for the entire application, and opens an empty JSP page ( index.jsp) in the Source Editor. To gain a better understanding of the

structure of the project template, refer to About Structuring Web Source Files from the IDE's Help Contents (F1).
Preparing the Web Pages

The application's Presentation Layer consists of two JSP pages: the welcome page and the response page that returns the specified data to the user. You can start by creating

placeholders for these two pages. This means that you will add the HTML now, and add the JSP-specific code once the Logic Layer has been implemented.

Implementing the Welcome Page

Convert index.jsp into IFPWAFCAD's welcome page:

1. 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. Then, in the

Source Editor, change the title to IFPWAFCAD Homepage.

2. For the body, replace what is listed with the following code:

3. <body>
4. <br>
5. <h2 align="center">Welcome to IFPWAFCAD, the International Former Professional
6. <br>Wrestlers' Association for Counseling and Development!</h2>
7.
8. <br><br>
9. <table width="55%" align="center">
10. <tr>
11. <td><strong>IFPWAFCAD offers expert counseling in a wide range of fields.</strong></td>
12. </tr>
13. <tr>
14. <td><br>To view the contact details of an IFPWAFCAD certified former
15. <br>professional wrestler in your area, select a subject below:</td>
16. </tr>
17. <tr>
18. <td>
19. <form action="response.jsp" method="post">
20. <br>
21. <strong>Select a subject:</strong>
22. <select name="subject_id" size="1" >
23. <option value="1">Marriage Guidance</option>
24. <option value="2">Financial Consultancy</option>
25. </select>
26. <input type="submit" name="submit" value="submit">
27. </form>
28. </td>
29. </tr>
30. </table>
31. </body>

This creates a simple form inside a table. Later, when you implement the JSP code, you will replace the sample subjects with a loop that grabs all subject names directly

from the database. Also, note that the form submits to the response.jsp page that you are about to create.

Implementing the Response Page


To create a placeholder for response.jsp, do the following:

1. Right-click the IFPWAFCAD project node in the Projects window and choose New > JSP. The New JSP File dialog opens.

2. In the JSP File Name field, enter response. Note that Web Pages is currently selected for the Location field, meaning that the file will be created in the same directory as the
welcome page.

3. Accept all other defaults and click Finish. A template for the new response.jsp page is generated and opens in the Source Editor. A new JSP node also displays under Web

Pages in the Projects window:

4. In the Source Editor, change the title temporarily to something like "(Chosen Subject)".

5. Next, replace the template's body with the following code:

6. <body>
7. <br>
8. <h2 align="center">(Chosen Subject)</h2>
9. <br>
10. <table width="60%" align="center" cellpadding="10">
11. <tr>
12. <td valign="top" width="25%"><strong>Description: </strong></td>
13. <td><em>(subject description)</em><br></td>
14. </tr>
15. <tr>
16. <td valign="top"><strong>Counselor: </strong></td>
17. <td><span style="font-size:large"><strong>(counselor's name)</strong></span>
18. <br><span style="align:center">
19. <em>member since: (a date)</em></span></td>
20. </tr>
21. <tr>
22. <td valign="top"><strong>Contact Details: </strong></td>
23. <td><strong>email: </strong><a href="mailto:<(an email address)>"><(an email address)></a>
24. <br><strong>phone: </strong><(a telephone number)></td>
25. </tr>
26. </table>
27. </body>

This creates an HTML template for the output that will be generated once you code in the JSP. Note that all of the fields above that are enclosed in parentheses will be

generated dynamically by accessing the Data Layer.

Deploying to the Server

To understand what the application is going to look like for the user, deploy what you have so far constructed to the web server in order to see the pages in a browser. Note that
the JSP pages do not contain any JSP code yet, so for now you could simply change the extensions to .htm and open them individually in a browser. However, you will need the

web server to compile the JSP code as well as the Java classes for the Logic Layer, so you might as well start using the web server.
Whether you are running NetBeans IDE's bundled Tomcat or SJSAS, once you have the server registered in the IDE, the process for deploying an application is the same. If you
need to make any changes to server settings in the IDE, choose Tools > Server Manager from the main menu to open the Server Manager.

To deploy the application to the server:

1. From the Projects window, right-click the project node and choose Deploy Project. NetBeans IDE automatically starts the server (if it has not already been started),

compiles it and then deploys the project to it. You can see any output generated in the Output window. The output should complete with a BUILD SUCCESSFUL message.

To check that the application has indeed been deployed to the server, open the Runtime window (Ctrl+5) and expand the Servers node. The servers that are registered in
the IDE are listed here. For Tomcat, expand Web Applications to view the IPFWAPCAD application compiled on the server. For SJSAS, expand Applications > Web

Applications to view the application.

2. To run the project, back in the Projects window choose Run Project from the right-click menu of the project node. The index.jsp page opens in the IDE's default browser.

Tip: If you had simply chosen Run Project to begin with, the application would have automatically been compiled and deployed to the server prior to opening in a browser.

Implementing the Data Layer

Before coding in the middle Logic Layer, prepare the Data Layer. This step is divided into a few subtasks:

1. Preparing the Database in NetBeans IDE

2. Setting up a JDBC Connection Pool

3. Referencing the JDBC Resource from the Application

4. Adding the Database Driver's JAR File to the Server

Preparing the Database in NetBeans IDE


After completing the Connecting to a MySQL Database tutorial, you will already have a connection to a MySQL database registered in the IDE. You should also have two tables,
Counselor and Subject, containing sample data generated from ifpwafcad.sql.

Setting up a JDBC Connection Pool

In order to specify how the web server allows an application to communicate with the database, we need to set up a database connection pool. A database connection pool is

basically a group of reusable connections that a server maintains for a specific database. Web applications requesting a connection to a database obtain that connection from the
pool. When an application closes a connection, the connection is returned to the pool.

In order to set up a connection pool on the server, a JDBC resource (also called a data source) must first be created. A JDBC resource provides applications with a connection to a
database. Depending on whether you're using Tomcat or SJSAS, do the following:

Bundled Tomcat Web Server


1. Access the Tomcat Administration tool from the Runtime window by expanding the Servers > Bundled Tomcat > Web Applications nodes (if necessary, start the server first
by choosing Start from the server node's right-click menu). Then right-click the /admin node and choose Open in Browser. The login page opens in the IDE's default

browser.

2. Enter the user name and password for a user that has been assigned to the "admin" role. If you need to verify this information, check the tomcat-users.xml file in the conf

folder located in the server's base directory. You can find out the base directory by opening the Server Manager (Tools > Server Manager), selecting Tomcat from the left

pane and viewing the entry for the Catalina Base field under the Connection tab:
3. Once you are logged in, choose Resources > Data Sources from the left column. In the main window that displays, choose Create New Data Source from the Data Source

Actions drop-down menu. Enter the following values in the corresponding fields:

o JNDI Name: jdbc/connectionPool

o Data Source URL: jdbc:mysql://localhost:3306/MyNewDatabase

o JDBC Driver Class: com.mysql.jdbc.Driver

o User Name: root

o Password: nbuser

To gain a better understanding of this process, see About Connection Pools in the IDE's Help Contents (F1).
When you are sure that your entered values match those in the screenshot below, click Save. Then click Commit Changes, and Log Out.

Sun Java System Application Server

Setting up a JDBC connection pool is slightly easier on SJSAS because it can be done entirely within NetBeans IDE:

1. In the Projects window, right-click the project node and choose New > File/Folder.... Under Categories select Sun Resources; under File Types select JDBC Resource. Click
Next.
2. In the General Attributes pane, select the Create New JDBC Connection Pool option, then enter jdbc/connectionPool for the JNDI Name below. Leave all other settings at

their defaults and click Next. Then click Next again through the Additional Properties Pane.

3. In the Choose Database Connection pane, note that a connection pool name is automatically provided based on the JNDI name specified above. Make sure the Extract from
Existing Connection option is selected, and select the database connection you are using ( jdbc:mysql://localhost:3306/MyNewDatabase) from the drop-down list. Click

Next.

4. In the Add Connection Pool Properties pane, leave all settings at their defaults and click Finish. The new data source and connection pool are created in the project. You can

verify this by expanding the Server Resources node to view both the data source and connection pool just created:

Although you just created a data source and connection pool in the project, it is still necessary to register them with the application server. To do so:

1. Choose Register from the right-click menus of both data source and connection pool nodes. In the JDBC Resource Registration dialog that displays, click Register, then click
Close.

2. To verify that the JDBC resource and connection pool have indeed been created on the server, you can switch to the Runtime window and choose View Admin Console from
the right-click menu of the Sun Java System Application Server node. The Administration login page opens in the IDE's default browser.
3. Login to the console (by default, user name and password are: admin, adminadmin). Select Resources from the left column, then in the main window click JDBC.

4. Now, when you explore both the JDBC Resources and Connection Pools pages, you should see the newly created data source ( jdbc/connectionPool) and connection pool

(connectionPool).

Referencing the JDBC Resource from the Application

You now need to reference the JDBC resource you just created from the web application. This means you have to access both the web application's general deployment descriptor
(web.xml), as well as the server-specific deployment descriptor for the server you are using (context.xml for Tomcat; sun-web.xml for SJSAS).

Deployment descriptors are XML documents that contain information describing how an application should be deployed. For example, they are normally used to specify location and
optional parameters of servlets and JSP files, as well as implement basic security features for your application. For more information, see Configuring Web Application Deployment
Descriptors in the IDE's Help Contents (F1).

To reference the JDBC resource in the general deployment descriptor:

1. In the Projects window, expand the Web Pages > WEB-INF subfolder and double-click web.xml. A graphical editor for the file displays in the Source Editor.

2. Click the References tab located along the top of the Source Editor. Expand the Resource References heading, then click Add.... The Add Resource Reference dialog opens.

3. For Resource Name, enter the JNDI name you gave when adding the data source to the server above (jdbc/connectionPool). For Description, enter the data source URL

(jdbc:mysql://localhost:3306/MyNewDatabase). Leave all other fields that are filled by default and click OK. The new resource is added under the Resource References

heading:
To verify that the resource is now added to the web.xml file, click the XML tab located along the top of the Source Editor you'll see that the following < resource-ref> tags

are now included:

4. <resource-ref>
5. <description>jdbc:mysql://localhost:3306/MyNewDatabase [root on Default schema]</description>
6. <res-ref-name>jdbc/connectionPool</res-ref-name>
7. <res-type>javax.sql.DataSource</res-type>
8. <res-auth>Container</res-auth>
9. <res-sharing-scope>Shareable</res-sharing-scope>
10. </resource-ref>

Depending on whether you are using Tomcat or SJSAS, perform the following steps to reference the JDBC resource in the server-specific deployment descriptor:

Bundled Tomcat Web Server


1. In the Projects window, expand the Web Pages > META-INF subfolder and double-click context.xml. The file displays in the Source Editor.

2. Add the following <ResourceLink> tag, then save the file (changes made in bold):
3. <?xml version="1.0" encoding="UTF-8"?>
4. <Context path="/IFPWAFCAD">
5. <ResourceLink global="jdbc/connectionPool" name="jdbc/connectionPool" type="javax.sql.DataSource"/>
6. </Context>

Sun Java System Application Server


1. In the Projects window, expand the Web Pages > WEB-INF subfolder and double-click sun-web.xml. A graphical editor for the file displays in the Source Editor.

2. Click Edit As XML in the upper right corner of the editor. The file displays in XML format. Enter the following <resource-ref> tags to the document, e.g. following the

closing </jsp-config> tag:

3. <resource-ref>
4. <res-ref-name>jdbc/connectionPool</res-ref-name>
5. <jndi-name>jdbc/connectionPool</jndi-name>
6. </resource-ref>

Adding the Database Driver's JAR File to the Server

Adding the database driver's JAR file is another step that is vital to enabling the server to communicate with your database. You need to locate your database driver's installation
directory. If you are continuing from the Connecting to a MySQL Database tutorial, you are using MySQL Connector/J which you installed to C:\ on your computer. Copy the mysql-
connector-java-5.0.5-bin.jar file in the driver's root directory and, depending on whether you are using Tomcat or SJSAS, do the following:

Bundled Tomcat Web Server

 Paste the JAR file into Tomcat's common/lib subfolder. The server is by default found within the enterprise subfolder of the IDE's installation directory. If you've already started

the server, make sure that you restart it after pasting in the JAR file, so that the server can then load it.
Sun Java System Application Server

 Locate the installation directory of SJSAS and paste the JAR file into the server's domains > domain1 > lib > ext subfolder. For example, if you installed the server to C:\, the path

is: C:\Sun\AppServer\domains\domain1\lib\ext. When you connect to the SJSAS in NetBeans IDE, you are actually connecting to an instance of the application server. Each

instance runs applications in a unique domain, and so here we need to place the JAR file in domain1, which is the default domain created upon installing SJSAS. If you've already

started the server, make sure that you restart it after pasting in the JAR file, so that the server can then load it.

Implementing the Logic Layer

Now that you have prepared the Data Layer, start putting the Java classes in place. As shown in the figure above, the Logic Layer is comprised of three classes: SubjectName.java,

SubjectCounselor.java, and AccessDB.java. These classes serve two functions: they interface with the JSP pages by responding to data requests (SubjectName.java and
SubjectCounselor.java), and they interface with the database by performing queries based on user-specified information (AccessDB.java). You can proceed according to these
two functions:

1. Interfacing the JSP Pages

2. Interfacing the Database

Interfacing the JSP Pages

SubjectName.java

SubjectName.java enables the index.jsp page to access the subject names as they are listed in the Subject table. It does this by allowing AccessDB.java to set the instance
variables id and name using the setter methods, then letting index.jsp access them using the public getter methods. To set up SubjectName.java, do the following:

1. In the Projects window, right-click the project node and choose New > Java Class. The New Java Class wizard opens.
2. Enter SubjectName for the Class Name text field. You should also create a new package to contain all Java classes for the project. For Package, type in org. Click Finish. A
template for the new class opens in the Source Editor. In the Projects window, nodes for the new package and class display from Source Packages:

3. Now, in the newly created template in the Source Editor, add the following to the body of the new SubjectName class, then save (Ctrl+S) the file:

4. private String id;


5. private String name;
6.
7. // create setter methods
8. public void setId(String id){
9. this.id = id;
10. }
11.
12. public void setName(String name){
13. this.name = name;
14. }
15.
16. // create getter methods
17. public String getId(){
18. return id;
19. }
20.
21. public String getName(){
22. return name;
23. }

SubjectCounselor.java

SubjectCounselor.java enables the response.jsp page to access subject and counselor details from the database based on the subject_id value that is received from the form
in index.jsp. Like SubjectName.java, the class does this by allowing AccessDB.java to set all instance variables using the public setter methods, then letting response.jsp

access them using the getter methods. To set up SubjectCounselor.java, do the following:

1. In the Projects window, right-click the project node and choose New > Java Class. The New Java Class wizard opens.

2. Enter SubjectCounselor for the Class Name text field. Click Finish. A template for the new class opens in the Source Editor. In the Projects window, a new class node

displays under the org package we created earlier.

3. Now, in the newly created template in the Source Editor, add the following to the body of the new SubjectCounselor class, then save (Ctrl+S) the file:

4. private String subjectName;


5. private String description;
6. private String counselorID;
7. private String firstName;
8. private String nickName;
9. private String lastName;
10. private String telephone;
11. private String email;
12. private String memberSince;
13.
14. // create setter methods
15. public void setSubjectName(String subject) {
16. this.subjectName = subject;
17. }
18.
19. public void setDescription(String desc) {
20. this.description = desc;
21. }
22.
23. public void setCounselorID(String counsId) {
24. this.counselorID = counsId;
25. }
26.
27. public void setFirstName(String first) {
28. this.firstName = first;
29. }
30.
31. public void setNickName(String nick) {
32. this.nickName = nick;
33. }
34.
35. public void setLastName(String last) {
36. this.lastName = last;
37. }
38.
39. public void setTelephone(String phone) {
40. this.telephone = phone;
41. }
42.
43. public void setEmail(String email) {
44. this.email = email;
45. }
46.
47. public void setMemberSince(String mem){
48. this.memberSince = mem;
49. }
50.
51. // create getter methods
52. public String getSubjectName() {
53. return subjectName;
54. }
55.
56. public String getDescription() {
57. return description;
58. }
59.
60. public String getCounselorName() {
61. String counselorName = firstName + " "
62. + nickName + " " + lastName;
63. return counselorName;
64. }
65.
66. public String getMemberSinceDate() {
67. return memberSince;
68. }
69.
70. public String getTelephone() {
71. return telephone;
72. }
73.
74. public String getEmail() {
75. return email;
76. }

Interfacing the Database

AccessDB.java

You can code AccessDB.java by focusing on its individual tasks: it must connect to the database, send a user-specified query, then store data received from the query. Because

you are coding AccessDB.java in piecemeal fashion, you can download a working version of AccessDB.java here. That way, if you get lost at any point, you can compare your code

with the saved version.


Let's begin by creating the file and preparing the code that enables the class to establish a connection to the connection pool we defined above:

1. In the Projects window, right-click the project node and choose New > Java Class. The New Java Class wizard opens.

2. Enter AccessDB for the Class Name text field. Click Finish. A template for the new class opens in the Source Editor. In the Projects window, a new class node displays under

the org package we created earlier.

3. In the newly created template in the Source Editor, right-click the canvas and choose Enterprise Resources > Use Database. In the Choose Database dialog, select the JNDI
name of the data source that we previously defined (jdbc/connectionPool) from the Data Source drop-down list. Make sure the Generate Inline Lookup Code option is

selected and click Finish. The following code is generated in the Source Editor:

4. private DataSource getJdbcConnectionPool() throws NamingException {


5. Context c=new InitialContext();
6. return (DataSource) c.lookup("java:comp/env/jdbc/connectionPool");
7. }

This allows the class to connect to the database using the connection pool that we defined earlier on the web server. Also note that upon creating the
getJdbcConnectionPool() method, the IDE automatically generates import statements in the Source Editor for the following classes from the javax.sql and
javax.naming API's:

You can now begin coding the database queries that the class performs for both JSP pages. Start with the query for index.jsp, which involves retrieving the names and ID's for all

subjects listed in the Subject table:


1. In the Source Editor for AccessDB.java, enter the following string variable to an area just beneath the class declaration:

2. private String sqlSubjectName = "SELECT subject_id, name FROM Subject";

The SQL query allows you to specify what data you want to pull from the database.

3. Add the following getSubjectName() method to the class. This step creates a connection to the connection pool, then connects to the database and performs the query. It

then loops through the result set returned from the database, and creates an instance of SubjectName to retain the ID and name for each returned row. Each instance is

added to a list, which is finally returned to the object calling the method:

4. // get subject names from database


5. public List getSubjectName() throws Exception{
6.
7. // connection instance
8. Connection connection = null;
9.
10. // instance of SubjectName used to retain retrieved data
11. SubjectName subName = null;
12.
13. // list to hold all instances of SubjectName
14. List list = new ArrayList();
15.
16. try {
17. // connect to database
18. DataSource dataSource = getJdbcConnectionPool();
19. connection = dataSource.getConnection();
20.
21. // prepare the SQL query to get subject name and id
22. PreparedStatement ps = connection.prepareStatement(sqlSubjectName);
23.
24. // set up the result set to retain all queried data
25. ResultSet rs = ps.executeQuery();
26.
27. // now loop through the rows from the generated result set
28. while(rs.next()){
29. // declare an instance of SubjectName to match
30. // returned data with class' instance variables
31. subName = new SubjectName();
32. String subject_id = rs.getString("subject_id");
33. String name = rs.getString("name");
34. // set the data to the variables
35. subName.setId(subject_id);
36. subName.setName(name);
37. // finally, add the subName instance to the list
38. list.add(subName);
39. }
40.
41. } catch(Exception e){
42. System.out.println(e.getMessage());
43.
44. // close the connection so it can be returned to
45. // the connection pool then return the list
46. } finally{
47. connection.close();
48. return list;
49. }
50. }

Upon adding the above code for the getSubjectName() method, notice that various errors appear in the Source Editor, underlining text in red. When you place your cursor

in the underlined text, a light bulb icon displays to the immediate left of the line. This indicates that the IDE can offer a possible solution for the error.

51. Fix all errors by either clicking the light bulb icon, or pressing Alt-Enter to open the corresponding tool tip:

There are 5 errors that you should be concerned with, and they all involve importing classes (and interfaces) into the project:

o The List interface used as the method's returned object requires the definition from java.util.

o The ArrayList class is employed to implement List, and you require this class to hold all instances of SubjectName.

o Connection, PreparedStatement, and ResultSet are all required from the java.sql API to communicate with the database.

Choose Add Import from the tool tips for each of these, and note that new import statements are automatically generated in the Source Editor:
Now you can add the code for the query coming from response.jsp. This follows the same pattern as what was just demonstrated above for index.jsp, i.e. you create an

appropriate SQL query, then you create a method to query the database and retain the data. In this case however, you need to create 2 queries: the first accesses the Subject

table and retrieves the row corresponding to the ID selected by the user from the drop-down menu in index.jsp. The second query then continues the process using the

counselor_idfk from the returned subject row to match the counselor ID from the Counselor table:

1. In the Source Editor for AccessDB.java, enter the following 2 string variables to an area just beneath the class declaration:

2. private String sqlSubject = "SELECT * FROM Subject WHERE subject_id = ?";


3. private String sqlCounselor = "SELECT * FROM Counselor WHERE counselor_id = ?";

4. Add the following getSubCounselor() method to the class. This creates a connection to the connection pool, then connects to the database and performs the 2 queries, as

described above. It then creates an instance of SubjectCounselor to retain all data that is harvested from the 2 result sets:

5. // get subject data and counselor data for corresponding subject


6. public SubjectCounselor getSubCounselor(String subjectID) throws Exception{
7.
8. // instance of SubjectCounselor used to retain data
9. SubjectCounselor subCoun = new SubjectCounselor();
10.
11. // connection instance
12. Connection connection = null;
13.
14. try {
15. // connect to database
16. DataSource dataSource = getJdbcConnectionPool();
17. connection = dataSource.getConnection();
18.
19. // prepare the SQL query to get subject data
20. PreparedStatement ps = connection.prepareStatement(sqlSubject);
21. ps.setString(1, subjectID);
22. ResultSet rs = ps.executeQuery();
23. // this assumes there is only one row in the result set
24. rs.next();
25. // match all returned fields with the below variables
26. String subjectName = rs.getString("name");
27. String description = rs.getString("description");
28. String counselorID = rs.getString("counselor_idfk");
29.
30. // prepare the SQL query to get counselor data
31. ps = connection.prepareStatement(sqlCounselor);
32. ps.setString(1, counselorID);
33. rs = ps.executeQuery();
34. // this assumes there is only one row in the result set
35. rs.next();
36. // match all returned fields with the below variables
37. String firstName = rs.getString("first_name");
38. String nickName = rs.getString("nick_name");
39. String lastName = rs.getString("last_name");
40. String telephone = rs.getString("telephone");
41. String email = rs.getString("email");
42. String memberSince = rs.getString("member_since");
43.
44. // finally set all variables to their
45. // equivalents in the SubjectCounselor instance
46. subCoun.setSubjectName(subjectName);
47. subCoun.setDescription(description);
48. subCoun.setCounselorID(counselorID);
49. subCoun.setFirstName(firstName);
50. subCoun.setNickName(nickName);
51. subCoun.setLastName(lastName);
52. subCoun.setTelephone(telephone);
53. subCoun.setEmail(email);
54. subCoun.setMemberSince(memberSince);
55. } catch(Exception e){
56. System.out.println(e.getMessage());
57. } finally{
58. // close the connection so it can be returned to the
59. // connection pool then return the SubjectCounselor instance
60. connection.close();
61. return subCoun;
62. }
63. }

You have now completed the code required for AccessDB.java, and with it all the necessary steps required to implement the Logic Layer. You may want to compare your version of

AccessDB.java with the downloadable version prior to continuing. The only remaining task is to add the JSP code to your web pages, allowing you to display the data maintained
in the instances of SubjectName and SubjectCounselor.

Implementing the Presentation Layer

If you return to the index.jsp and response.jsp placeholders created earlier in the tutorial, you can add JSP code to enable pages to generate content dynamically, i.e. based on

user input. To add JSP code, you need to perform the following 3 steps:

1. Adding the JSTL Library to the Project's Compilation Classpath

2. Adding taglib Directives to the JSP Pages

3. Adding the Code

Adding the JSTL Library to the Project's Compilation Classpath

In order to make better use of the JSP resources at our disposal, you are using tags from 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 Tomcat or SJSAS, do the following:


Bundled Tomcat Web Server
1. In the Projects window, right-click the project's Libraries node and choose Add Library. Select the JSTL 1.1 library and click Add Library.

2. Expand the Libraries node now, and you will see 2 new nodes: one for the JSTL library's standard.jar file and another for the library's jstl.jar file:

Sun Java System Application Server

You do not need to take any action to add the JSTL library to the project's compilation classpath if you are using the Sun Java System Application Server. This is because the JSTL

library is already included in the application server's library. You can verify this by expanding the Libraries > Sun Java System Application Server nodes. The appserv-jstl.jar

node defines all standard tags in the JSTL library.

Adding taglib Directives to the JSP Pages

Regardless of what server you are using, you need to add the necessary taglib directives to JSP pages:

1. Open both index.jsp and response.jsp in the Source Editor. Add the following directive to both pages:
2. <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Notice that upon creating these pages this directive was automatically generated as a comment in the JSP template. You can uncomment the directive by removing the <%--

--%> tags:

Adding the Code

Finally, add the code to each page. You need to access the list of SubjectNames (for index.jsp) and the SubjectCounselor instance (for response.jsp), and then display the data

in the HTML.

index.jsp
1. Add the following code somewhere to the top of the file, e.g. just above the HTML doctype declaration:

2. <%-- create an instance of AccessDB --%>


3. <% AccessDB accessDB = new AccessDB(); %>
4.
5. <%-- create an instance of List, then retrieve SubjectNames --%>
6. <% List subjNames = accessDB.getSubjectName(); %>
7.
8. <%-- make list accessible to page --%>
9. <% request.setAttribute("subjNames", subjNames); %>
You are declaring and setting a List variable to contain the list of SubjectNames that is returned from calling the getSubjectName() method of AccessDB. The

setAttribute() method is then applied to the subjNames variable so that it becomes accessible to the page making the request (as demonstrated below when you insert a
loop in the HTML form to extract the contents of subName).

10. Add the following JSP import statements to the page:

11. <%@ page import="org.*" %>


12. <%@ page import="java.util.List" %>

The first import allows the page to access all classes contained in the org package you created in the project. The second defines the List class used for the variable you

just declared.

13. In the HTML form, between the <select> tags, replace the <option> tags with the following code (changes made in bold):

14. <select name="subject_id" size="1" >


15. <c:forEach var="subName" items="${requestScope.subjNames}" >
16. <option value="${subName.id}">${subName.name}</option>
17. </c:forEach>
18. </select>

Here is the loop. The forEach tag fetches all values from subName and extracts the name and ID of each subject, using these to populate the form's drop-down list.

Also, note the c: prefix to the forEach tag. This references the JSTL core library which you added a taglib directive for above.
19. Save changes (Ctrl+S), then redeploy the project to the server and try running it again (F6). This time, when index.jsp displays in the browser, the subject drop-down list

should contain subject names that were retrieved from the database:

response.jsp
1. Add the following code somewhere to the top of the file, e.g. just above the HTML doctype declaration:

2. <%-- get the value from the form --%>


3. <% String subjectID = request.getParameter("subject_id"); %>
4.
5. <%-- create an instance of AccessDB --%>
6. <% AccessDB accessDB = new AccessDB(); %>
7.
8. <%-- create an instance of SubjectCounselor using form value --%>
9. <% SubjectCounselor subCoun = accessDB.getSubCounselor(subjectID); %>
10.
11. <%-- create variables to hold data from SubjectCounselor --%>
12. <% String name = subCoun.getSubjectName(); %>
13. <% String description = subCoun.getDescription(); %>
14. <% String counselor = subCoun.getCounselorName(); %>
15. <% String memberSince = subCoun.getMemberSinceDate(); %>
16. <% String telephone = subCoun.getTelephone(); %>
17. <% String email = subCoun.getEmail(); %>

Here you are creating a string variable to hold the subject_id, the value sent from the form from index.jsp. Then, you declare and set a variable for SubjectCounselor to

hold the data returned from calling the getSubCounselor() method of AccessDB. Finally, you declare and set a bunch of string variables to hold the data contained in that

SubjectCounselor instance. These string variables are what you will access directly from the HTML in the page.

18. Add the following JSP import statement to the page:

19. <%@ page import="org.*" %>

As for index.jsp above, you must allow the page to access all classes contained in the org package of our project.

20. Now, in the HTML, replace all the text previously included in parentheses with the following JSP calls to display the variables. Changes are shown below in bold:

21. <html>
22. <head>
23. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
24. <title><%= name %></title>
25. </head>
26. <body>
27. <br>
28. <h2 align="center"><%= name %></h2>
29. <br>
30. <table width="60%" align="center" cellpadding="10">
31. <tr>
32. <td valign="top" width="25%"><strong>Description: </strong></td>
33. <td><em><%= description %></em><br></td>
34. </tr>
35. <tr>
36. <td valign="top"><strong>Counselor: </strong></td>
37. <td><span style="font-size:large"><strong><%= counselor %></strong></span>
38. <br><span style="align:center">
39. <em>member since: <%= memberSince %></em></span></td>
40. </tr>
41. <tr>
42. <td valign="top"><strong>Contact Details: </strong></td>
43. <td><strong>email: </strong><a href="mailto:<%= email %>"><%= email %></a>
44. <br><strong>phone: </strong><%= telephone %></td>
45. </tr>
46. </table>
47. </body>
48. </html>

Prior to sending this page back to the client browser, the server inserts all values for JSP variables directly into the HTML. You are therefore now able to access data directly

from the Data Layer in the response page.

49. Finally, save changes (Ctrl+S), then redeploy the project to the server and try running it again (F6). When index.jsp displays in the browser, select a subject from the

drop-down list and click submit. You should now be forwarded to the response.jsp page, showing details corresponding to your selection:

You might also like