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

Connecting to a MySQL Database in NetBeans IDE

Embed Size (px)

Citation preview

Connecting to a MySQL Database in NetBeans IDEContributed 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 SoftwareBefore you begin, make sure you have the following software installed on your computer: 1. 2. 3. 4. NetBeans IDE 5.5 (download) Java SE Development Kit (JDK) version 5.0 or higher (download) MySQL database (download) 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 DatabaseIf 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 InstanceNow 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 IDEIn 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 ConnectionYou 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 ( appears broken ( ) when there is no connection.

) when you are connected to a database. Likewise, it

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 TablesNow 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 Dialog1. 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] [checked] [checked]

[checked] id name description

SMALLINT 0 VARCHAR VARCHAR 50 500

counselor_idfk SMALLINT 0

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

Name Description 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 ( created, starting with the primary key ( ): ) display under Tables in the Database explorer. Beneath the table node there are the columns (fields) you

Using the SQL Editor1. 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 ( window: ) 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

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 DataIn 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', '[email protected]', '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 ScriptAnother 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 MySQLContributed 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 SoftwareBefore 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 StructureSimple 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. 2. 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. 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 PagesThe 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. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.

IFPWAFCAD offers expert counseling in a wide range of fields.
Welcome to IFPWAFCAD, the International Former Professional
Wrestlers' Association for Counseling and Development!

14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30.


To view the contact details of an IFPWAFCAD certified former
professional wrestler in your area, select a subject below:
Select a subject: Marriage Guidance Financial Consultancy

31.

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. 2.

Right-click the IFPWAFCAD project node in the Projects window and choose New > JSP. The New JSP File dialog opens. 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. 5.

In the Source Editor, change the title temporarily to something like "(Chosen Subject)". Next, replace the template's body with the following code:

6. 7. 8. 9. 10. 11. 12. 13. 14.
(Chosen Subject)
Description: (subject description)

15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26.

Counselor: (counselor's name)
member since: (a date) Contact Details: email:
phone:

27.

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 ServerTo 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 LayerBefore coding in the middle Logic Layer, prepare the Data Layer. This step is divided into a few subtasks: 1. 2. 3. 4. Preparing the Database in NetBeans IDE Setting up a JDBC Connection Pool Referencing the JDBC Resource from the Application 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 PoolIn 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 Server1. 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 o o o o

JNDI Name: jdbc/connectionPool Data Source URL: jdbc:mysql://localhost:3306/MyNewDatabase JDBC Driver Class: com.mysql.jdbc.Driver User Name: root 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. 4.

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. 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 ApplicationYou 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. 2. 3. 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. 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. 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. 5. 6. 7. 8. 9. jdbc:mysql://localhost:3306/MyNewDatabase [root on Default schema] jdbc/connectionPool javax.sql.DataSource Container Shareable

10.

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 Server1. 2. In the Projects window, expand the Web Pages > META-INF subfolder and double-click context.xml. The file displays in the Source Editor. Add the following tag, then save the file (changes made in bold):

3. 4. 5.

6.

Sun Java System Application Server1. 2. 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. Click Edit As XML in the upper right corner of the editor. The file displays in XML format. Enter the following tags to the document, e.g. following the closing tag:

3. 4. 5. jdbc/connectionPool jdbc/connectionPool

6.

Adding the Database Driver's JAR File to the ServerAdding 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 LayerNow 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 thesetwo functions: 1. 2. Interfacing the JSP Pages Interfacing the Database

Interfacing the JSP PagesSubjectName.javaSubjectName.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 instancevariables 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. 10. } 11. 12. public void setName(String name){ 13. this.name = name; this.id = id;

14. } 15. 16. // create getter methods 17. public String getId(){ 18. 19. } 20. 21. public String getName(){ 22. 23. } return name; return id;

SubjectCounselor.javaSubjectCounselor.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 formin 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. 2.

In the Projects window, right-click the project node and choose New > Java Class. The New Java Class wizard opens. 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. 17. } 18. 19. public void setDescription(String desc) { 20. 21. } 22. 23. public void setCounselorID(String counsId) { 24. 25. } 26. 27. public void setFirstName(String first) { 28. 29. } 30. 31. public void setNickName(String nick) { 32. 33. } this.nickName = nick; this.firstName = first; this.counselorID = counsId; this.description = desc; this.subjectName = subject;

34. 35. public void setLastName(String last) { 36. 37. } 38. 39. public void setTelephone(String phone) { 40. 41. } 42. 43. public void setEmail(String email) { 44. 45. } 46. 47. public void setMemberSince(String mem){ 48. 49. } 50. 51. // create getter methods 52. public String getSubjectName() { 53. 54. } 55. 56. public String getDescription() { 57. 58. } 59. return description; return subjectName; this.memberSince = mem; this.email = email; this.telephone = phone; this.lastName = last;

60. public String getCounselorName() { 61. 62. 63. 64. } 65. 66. public String getMemberSinceDate() { 67. 68. } 69. 70. public String getTelephone() { 71. 72. } 73. 74. public String getEmail() { 75. 76. } return email; return telephone; return memberSince; String counselorName = firstName + " " + nickName + " " + lastName;

return counselorName;

Interfacing the DatabaseAccessDB.javaYou 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. 2. In the Projects window, right-click the project node and choose New > Java Class. The New Java Class wizard opens. 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. 6. 7. } Context c=new InitialContext(); return (DataSource) c.lookup("java:comp/env/jdbc/connectionPool");

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. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. try { // connect to database DataSource dataSource = getJdbcConnectionPool(); connection = dataSource.getConnection(); // list to hold all instances of SubjectName List list = new ArrayList(); // instance of SubjectName used to retain retrieved data SubjectName subName = null; // connection instance Connection connection = null;

21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46.

// prepare the SQL query to get subject name and id PreparedStatement ps = connection.prepareStatement(sqlSubjectName);

// set up the result set to retain all queried data ResultSet rs = ps.executeQuery();

// now loop through the rows from the generated result set while(rs.next()){ // declare an instance of SubjectName to match // returned data with class' instance variables subName = new SubjectName(); String subject_id = rs.getString("subject_id"); String name = rs.getString("name"); // set the data to the variables subName.setId(subject_id); subName.setName(name); // finally, add the subName instance to the list list.add(subName); }

} catch(Exception e){ System.out.println(e.getMessage());

// close the connection so it can be returned to // the connection pool then return the list } finally{

47. 48. 49. 50. } }

connection.close(); return list;

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 o o

The List interface used as the method's returned object requires the definition from java.util. The ArrayList class is employed to implement List, and you require this class to hold all instances of SubjectName.

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. 9. // instance of SubjectCounselor used to retain data SubjectCounselor subCoun = new SubjectCounselor();

10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. // prepare the SQL query to get counselor data ps = connection.prepareStatement(sqlCounselor); ps.setString(1, counselorID); rs = ps.executeQuery(); // this assumes there is only one row in the result set rs.next(); // prepare the SQL query to get subject data PreparedStatement ps = connection.prepareStatement(sqlSubject); ps.setString(1, subjectID); ResultSet rs = ps.executeQuery(); // this assumes there is only one row in the result set rs.next(); // match all returned fields with the below variables String subjectName = rs.getString("name"); String description = rs.getString("description"); String counselorID = rs.getString("counselor_idfk"); try { // connect to database DataSource dataSource = getJdbcConnectionPool(); connection = dataSource.getConnection(); // connection instance Connection connection = null;

36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61.

// match all returned fields with the below variables String firstName = rs.getString("first_name"); String nickName = rs.getString("nick_name"); String lastName = rs.getString("last_name"); String telephone = rs.getString("telephone"); String email = rs.getString("email"); String memberSince = rs.getString("member_since");

// finally set all variables to their // equivalents in the SubjectCounselor instance subCoun.setSubjectName(subjectName); subCoun.setDescription(description); subCoun.setCounselorID(counselorID); subCoun.setFirstName(firstName); subCoun.setNickName(nickName); subCoun.setLastName(lastName); subCoun.setTelephone(telephone); subCoun.setEmail(email); subCoun.setMemberSince(memberSince); } catch(Exception e){ System.out.println(e.getMessage()); } finally{ // close the connection so it can be returned to the // connection pool then return the SubjectCounselor instance connection.close(); 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 maintainedin the instances of SubjectName and SubjectCounselor.

Implementing the Presentation LayerIf 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. 2. 3. Adding the JSTL Library to the Project's Compilation Classpath Adding taglib Directives to the JSP Pages Adding the Code

Adding the JSTL Library to the Project's Compilation ClasspathIn 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 Server1. 2. 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. 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 ServerYou 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 PagesRegardless 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.

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 CodeFinally, 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.jsp1. Add the following code somewhere to the top of the file, e.g. just above the HTML doctype declaration:

2. 3. 4. 5. 6. 7. 8. 9.

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 aloop in the HTML form to extract the contents of subName). 10. Add the following JSP import statements to the page:

11. 12.

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 tags, replace the tags with the following code (changes made in bold):

14. 15. 16. 17. ${subName.name}

18.

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.jsp1. Add the following code somewhere to the top of the file, e.g. just above the HTML doctype declaration:

2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.

14. 15. 16. 17.

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.

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. 22. 23. 24. 25. 26. 27. 28. 29. 30.

31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47.

Description:
Counselor:
member since: Contact Details: email:
phone:

48.

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: