Creating a Simple Web Application in NetBeans...

来源:百度文库 编辑:神马文学网 时间:2024/04/29 00:51:48
原文:http://www.netbeans.org/kb/55/mysql-webapp.html
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 which we‘ll take a closer look at while structuring our web application. This tutorial is designed for beginners who have a basic understanding of Java programming and web development, and are looking for a more hands-on approach to apply their knowledge.
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 theConnecting to a MySQL Database tutorial and assumes that you already have a connection to a MySQL database created and configured in the NetBeans IDE. You also require table data that is included inifpwafcad.sql. This SQL file creates two tables, counselors and subjects, then populates them with sample data. Save this file to a local directory, then open it in NetBeans and run it on your MySQL database. For our purposes, the database we are working in is named test.
Expected duration: 40 minutes
The following topics are covered below:
Getting the SoftwarePlanning the StructureCreating a New ProjectPreparing the Web PagesDeploying to the ServerImplementing the Data LayerImplementing the Logic LayerImplementing the Presentation LayerNext Steps
Getting the Software
Before we begin, make sure you have the following software installed on your computer:
NetBeans IDE 5.5 (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 the IDE. However, if you are planning on developing applications in NetBeans, the application server offers a lot of support for tools and technologies that can make a developer‘s life easier. Find out more by visiting theSJSAS 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 we 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. We 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 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 subjects and counselors 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 above scenario, we are developing 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

Lets start by creating a new project in the IDE:
Fire up NetBeans 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 to be working with. For our purposes, leave all other settings at their defaults and click Finish.
Note: If you downloaded the SJSAS but haven‘t yet registered it in NetBeans, you can easily 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, take a look at 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, take a look at 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. We can start by creating placeholders for these two pages. This means that we‘ll add the HTML now, then add the JSP-specific code once the Logic Layer has been implemented.
Implementing the Welcome Page
Let‘s start by converting index.jsp into IFPWAFCAD‘s welcome page:
Make sure index.jsp is opened in the Source Editor. If not, double-click it from IFPWAFCAD > Web Pages > index.jsp in the Projects window. Then in the Source Editor, change the title to IFPWAFCAD Homepage. Now, for the body, replace what you‘ve got with the following code:

Welcome to IFPWAFCAD, the International Former Professional
Wrestlers‘ Association for Counseling and Development!



IFPWAFCAD offers expert counseling in a wide range of fields.

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

Select a subject:

This basically creates a simple form inside a table. Later, when we implement the JSP code, we 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 we are about to create.
Implementing the Response Page
To create a placeholder for response.jsp, do the following:
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. 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:
Now, in the Source Editor change the title to something meaningful for the time being like "(Chosen Subject)". Next, replace the template‘s body with the following code:

(Chosen Subject)


Description: (subject description)
Counselor: (counselor‘s name)
member since: (a date)
Contact Details: email: <(an email address)>
phone: <(a telephone number)>

This creates an HTML template for the output that will be generated once we 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 get an idea of what the application‘s going to look like for the user, let‘s deploy what we‘ve got so far to the web server so that we can see the pages in a browser. Note that our JSP pages don‘t contain any JSP code yet, so for now you could simply change the extensions to .htm and open them individually in a browser. However, we will need the web server to compile the JSP code, as well as the Java classes for the Logic Layer, so we might as well start using the web server.
Whether you are running NetBeans‘ 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:
From the Projects window, right-click the project node and choose Deploy Project. NetBeans automatically starts the server (if it has not already been started), compiles 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. 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 we 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 we consider coding in the middle Logic Layer, let‘s get the Data Layer ready. This can be easily broken down into a few simple subtasks:
Preparing the Database in NetBeansSetting up a JDBC Connection PoolReferencing the JDBC Resource from the ApplicationAdding the Database Driver‘s JAR File to the Server
Preparing the Database in NetBeans
After completing theConnecting 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, counselors and subjects, containing sample data generated fromifpwafcad.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, we need to create a JDBC resource (also called a data source). 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
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. Enter the user name and password for a user that has been assigned to the "admin" role. If you need to verify this information, you can 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:
Once you‘re 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:
JNDI Name: jdbc/connectionPool Data Source URL: jdbc:mysql://localhost:3306/test JDBC Driver Class: com.mysql.jdbc.Driver User Name: root Password: nbuser
To gain a better understanding about what is being done here, take a look at 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 finally 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:
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. In the General Attributes pane, select the Create New JDBC Connection Pool radio button, then enter jdbc/connectionPool for JNDI Name below. Leave all other settings at their defaults and click Next. Then click Next again through the Additional Properties Pane. In the Choose Database Connection pane, note that a connection pool name is automatically provided based on the JNDI name we specified above. Make sure the Extract from Existing Connection radio button is selected, and select the database connection we are using (jdbc:mysql://localhost:3306/test) from the drop-down list. Click Next. 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 the both the data source and connection pool we just created:

Although we just created a data source and connection pool in the project, we still need to register them with the application server. To do so:
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. 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. 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 Application
We now need to reference the JDBC resource we just created from the web application. This means we have to access both the web application‘s general deployment descriptor (web.xml), as well as the server-specific deployment descriptor for the server we are using (content.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:
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 we gave when adding the data source to the server above (jdbc/connectionPool). For Description, enter the datasource URL (jdbc:mysql://localhost:3306/test). Leave all other fields that are filled by default and click Finish. 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 tags are now included: jdbc:mysql://localhost:3306/test [root on Default schema] jdbc/connectionPool javax.sql.DataSource Container Shareable
Now, depending on whether you‘re using Tomcat or SJSAS, do the following to reference the JDBC resource in the server-specific deployment descriptor:
Bundled Tomcat Web Server
In the Projects window, expand the Web Pages > META-INF subfolder and double-click content.xml. The file displays in the Source Editor. Add the following code between the tag, then save the file:
Sun Java System Application Server
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. Now, enter the following tags to the document, e.g. following the closing tag: jdbc/connectionPool jdbc/connectionPool
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 theConnecting to a MySQL Database tutorial, you are usingMySQL 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, 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 we have the Data Layer prepared, let‘s start putting the Java classes in place. As shown in thefigure 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). Let‘s proceed according to these two functions:
Interfacing the JSP PagesInterfacing 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 subjects 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:
In the Projects window, right-click the project node and choose New > Java Class.... The New Java Class wizard opens. Enter SubjectName for the Class Name text field. We 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:
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: private String id; private String name; // create setter methods public void setId(String id){ this.id=id; } public void setName(String name){ this.name=name; } // create getter methods public String getId(){ return id; } public String getName(){ return name; }
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:
In the Projects window, again 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. 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: String subjectName; String description; String counselorID; String firstName; String nickName; String lastName; String telephone; String email; String memberSince; // create setter methods public void setSubjectName(String subject) { this.subjectName=subject; } public void setDescription(String desc) { this.description=desc; } public void setCounselorID(String conId) { this.counselorID=conId; } public void setFirstName(String first) { this.firstName=first; } public void setNickName(String nick) { this.nickName=nick; } public void setLastName(String last) { this.lastName=last; } public void setTelephone(String phone) { this.telephone=phone; } public void setEmail(String email) { this.email=email; } public void setMemberSince(String mem){ this.memberSince=mem; } // create getter methods public String getSubjectName() { return subjectName; } public String getDescription() { return description; } public String getCounselorName() { String counselorName = firstName + " " + nickName + " " + lastName; return counselorName; } public String getMemberSinceDate() { return memberSince; } public String getTelephone() { return telephone; } public String getEmail() { return email; }
Interfacing the Database
AccessDB.java
We 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 we are tackling the coding of AccessDB.java in a piecemeal fashion, you can download a working version of AccessDB.javahere. 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:
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. Now, 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 radio button is selected and click Finish. The following code is generated in the Source Editor: private DataSource getJdbcConnectionPool() throws NamingException { 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, NetBeans automatically imports the following classes from the javax.sql and javax.naming packages: import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource;
We can now begin coding the database queries that the class performs for both JSP pages. Let‘s start with the query for index.jsp, which involves retrieving the ID‘s and names for all subjects listed in the subjects table:
In the Source Editor for AccessDB.java, enter the following string variable to an area just beneath the class declaration: private static String sqlSubject="SELECT * FROM subjects WHERE subjects_id = ?";
The SQL query allows us to specify what data we want to pull from the database. Now, add the following getSubjectName() method to the class. This basically 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: // get subject names from database public static List getSubjectName() throws Exception{ // connection instance Connection connection=null; // instance of SubjectName used to retain retrieved data SubjectName subName=null; // list to hold all instances of SubjectName List list=new ArrayList(); try { // connect to database DataSource dataSource=getJdbcConnectionPool(); connection=dataSource.getConnection(); // prepare the SQL query to get subject name and id PreparedStatement stat = connection.prepareStatement(sqlSubjectName); // set up the result set to retain all queried data ResultSet rs = stat.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("subjects_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{ connection.close(); return list; } }
Now we can add the code for the query coming from response.jsp. This follows the same 2-step pattern as what was just demonstrated above for index.jsp, i.e. we create an appropriate SQL query, then we create a method to query the database and retain the data. In this case however, we need to create 2 queries: the first accesses the subjects 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 follows through by using the counselorsid_fk from the returned subject row to match the counselor ID from the counselors table:
In the Source Editor for AccessDB.java, enter the following 2 string variables to an area just beneath the class declaration: private static String sqlSubject="SELECT * FROM subjects WHERE subjects_id = ?"; private static String sqlCounselor="SELECT * FROM counselors WHERE counselors_id = ?"; Now, 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: // get subject data and counselor data for corresponding subject public static SubjectCounselor getSubCounselor(String subjectID) throws Exception{ // instance of SubjectCounselor used to retain data SubjectCounselor subCon=new SubjectCounselor(); // connection instance Connection connection=null; try { // connect to database DataSource dataSource=getJdbcConnectionPool(); connection=dataSource.getConnection(); // prepare the SQL query to get subject data PreparedStatement stat=connection.prepareStatement(sqlSubject); stat.setString(1, subjectID); ResultSet rs = stat.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("counselors_idfk"); // prepare the SQL query to get counselor data stat = connection.prepareStatement(sqlCounselor); stat.setString(1, counselorID); rs=stat.executeQuery(); // this assumes there is only one row in the result set rs.next(); // 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 subCon.setSubjectName(subjectName); subCon.setDescription(description); subCon.setCounselorID(counselorID); subCon.setFirstName(firstName); subCon.setNickName(nickName); subCon.setLastName(lastName); subCon.setTelephone(telephone); subCon.setEmail(email); subCon.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 subCon; } }
We‘ve 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 thedownloadable version prior to continuing. The only remaining task is to add the JSP code to our web pages, allowing us to display the data maintained in the instances of SubjectName and SubjectCounselor.
We now return to the index.jsp and response.jsp placeholders that we created earlier on in the tutorial. Adding JSP code enables our pages to generate content dynamically, i.e. based on user input. To do this, we need to undertake the following 3 steps:
Adding the JSTL Library to the Project‘s Compilation ClasspathAdding taglib Directives to the JSP PagesAdding 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, we are using tags from theJavaServer Pages Standard Tag Library (JSTL) to access and display data taken from the Logic Layer. This library comes bundled with the IDE. We 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
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 should 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
Do nothing! We do not need to take any action to add the JSTL library to the project‘s compilation classpath. 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
Now, regardless of what server we are using, we need to add the necessary taglib directives to JSP pages:
Open both index.jsp and response.jsp in the Source Editor. Add the following directive to both pages: <%@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. We can now simply uncomment the directive by removing the <%-- --%> tags:

Adding the Code
Finally, let‘s tackle the code according to each page. Essentially, all that‘s required is to access the list of SubjectNames (for index.jsp) and the SubjectCounselor instance (for response.jsp), then display the data in our HTML.
index.jsp
Add the following code somewhere to the top of the file, e.g. just above the HTML doctype declaration: <% List subjNames=AccessDB.getSubjectName(); %> <% request.setAttribute("subjNames", subjNames); %>
We 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 we insert a loop in the HTML form to extract the contents of subName). Add the following JSP import statements to the page: <%@ page import="org.*" %> <%@ page import="java.util.List" %>
The first import allows the page to access all classes contained in the org package we created in the project. The second defines the List class used for the variable we just declared. Now, in the HTML form, between the
Here is our 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 we added a taglib directive forabove. 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
Add the following code somewhere to the top of the file, e.g. just above the HTML doctype declaration: <%-- get the value from the form --%> <% String subjectID = request.getParameter("subject_id"); %> <%-- create an instance of SubjectCounselor using form value --%> <% SubjectCounselor subCon= AccessDB.getSubCounselor(subjectID); %> <%-- create variables to hold data from SubjectCounselor --%> <% String name = subCon.getSubjectName(); %> <% String description = subCon.getDescription(); %> <% String counselor = subCon.getCounselorName(); %> <% String memberSince = subCon.getMemberSinceDate(); %> <% String telephone = subCon.getTelephone(); %> <% String email = subCon.getEmail(); %>
Here we are creating a string variable to hold the subject_id, the value sent from the form from index.jsp. Then, we declare and set a variable for SubjectCounselor to hold the data returned from calling the getSubCounselor() method of AccessDB. Finally, we declare and set a bunch of string variables to hold the data contained in that SubjectCounselor instance. These string variables are what we will access directly from the HTML in the page. Add the following JSP import statement to the page: <%@ page import="org.*" %>
As we did for index.jsp above, we must allow the page to access all classes contained in the org package of our project. Now, in the HTML, replace all the text we previously included in parentheses with the following JSP calls to display the variables. Changes are shown below in bold: <%= name %>

<%= name %>


Description: <%= description %>
Counselor: <%= counselor %>
member since: <%= memberSince %>
Contact Details: email: <%= email %>
phone: <%= telephone %>

Prior to sending this page back to the client browser, the server inserts all values for JSP variables directly into the HTML. We are therefore now able to access data directly from the Data Layer in our response page. 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:

Send Us Your Feedback
Next Steps
This concludes the Creating a Simple Web Application in NetBeans Using MySQL tutorial. This tutorial has demonstrated how to create a simple distributed web application that connects to a MySQL database. It also demonstrated how to construct an application using a basic three-tier architecture, and used JSP as a means of displaying back-end data to the client browser.
While building the application itself may have seemed like a lot of work for such a small payload, you now have a distributed framework in place, meaning that you are now well positioned for maintaining application data, as well as modifying or eventually expanding the application to a larger scale.
For related or more advanced tutorials, see the following resources:
Connecting to a MySQL Database in NetBeans 5.5. Covers the basics of working with a MySQL database in the NetBeans IDE.Introduction to the Struts Web Framework. The Struts framework enables you to create maintainable, extensible, and flexible web applications based on standard technologies, such as JSP pages, resource bundles, and XML.GUI Building in the NetBeans IDE. A quick-start guide demonstrating the process of creating graphical user interfaces with the NetBeans IDE.Securing a NetBeans Application in NetBeans 5.5. Describes the basics of adding security to a web application that is deployed to either the Tomcat Server or the Sun Java System Application Server.Connecting a GUI to a Java DB Database with NetBeans IDE. A guide to the process of connecting an application GUI to a Java DB database.