Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

download Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

of 18

Transcript of Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    1/18

    Creating a Simple Web Application Using a MySQL Database

    his document describes how to create a simple web application that connects to a MySQL database server. It also coversome basic ideas and technologies in web development, such as JavaServer Pages (JSP), JavaServer Pages Standard Tagibrary (JSTL), the Java Database Connectivity (JDBC) API, and two-tier, client-server architecture. This tutorial is designed foreginners who have a basic understanding of web development and are looking to apply their knowledge using a MySQLatabase.

    MySQL is a popular Open Source database management system commonly used in web applications due to its speed, flexibilitynd reliability. MySQL employs SQL, or Structured Query Language, for accessing and processing data contained in databases.

    his tutorial continues from the Connecting to a MySQL Database tutorial and assumes that you have already created a MySQLatabase named MyNewDatabase, which you have registered a connection for in the NetBeans IDE. The table data used in that

    utorial is contained in ifpwafcad.sql and is also required for this tutorial. This SQL file creates two tables, Subject andounselor, then populates them with sample data. If needed, save this file to your computer, then open it in the NetBeans

    DE and run it on the MySQL database named MyNewDatabase.

    Contents

    Planning the Structure

    Creating a New Project

    Preparing the Interface

    Setting up a Connection Pool

    Setting up a JNDI Datasource

    Referencing the Datasource from the Application

    Adding the Database Driver's JAR File to the Server

    Adding Dynamic Logic

    Adding the JSTL Library to the Project's Classpath

    Adding taglib Directives to the JSP Pages

    Adding JSP and JSTL Code

    Deploying and Running the Project

    See Also

    To follow this tutorial, you need the following software and resources.

    Software or Resource Version Required

    NetBeans IDE version 6.x Java

    Java Development Kit (JDK) version 5 or 6

    MySQL database server version 5.x

    MySQL Connector/J JDBC Driver version 5.x

    GlassFish application serveror

    Tomcat servlet container

    V2 UR2 or V3 Prelude

    version 6.x

    Notes:

    The NetBeans IDE 6.1 with Glassfish and MySQL Bundle Download provides you with an all-in-one package of softwarerequired for this tutorial.

    The Java download bundle enables you to optionally install the GlassFish application server and the Apache Tomcatservlet container 6.0.x. You must install one of these to work through this tutorial.

    The MySQL Connector/J JDBC Driver, necessary for communication between Java platforms and the MySQL databaseprotocol, is included in NetBeans IDE 6.x.

    If you need to compare your project with a working solution, you can download the sample application.

    Planning the Structure

    imple web applications can be designed using a two-tier architecture, in which the application communicates directly with aata source using the Java Database Connectivity API. A user's requests are sent to a database, and the results are sentirectly back to the user. Two-tier architectures can be easily mapped to a client-server configuration, where a user's browsererves as the client, and a remote database reachable over the Internet corresponds to the server.

    he application you build in this tutorial involves the creation of two JavaServer Pages. In each of these pages, you add basicHTML to implement a simple interface, followed by SQL tags provided by JSTL technology in order to query the database.Consider the following client-server scenario.

    http://www.netbeans.org/files/documents/4/1851/IFPWAFCAD.ziphttp://www.netbeans.org/files/documents/4/1851/IFPWAFCAD.ziphttp://java.sun.com/javase/downloads/index.jsphttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#seeAlsohttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#deployinghttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#deployinghttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#deployinghttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingCodehttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingJSTLhttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingLogichttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#referencinghttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#settingUpConnPoolhttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#planninghttp://www.netbeans.org/files/documents/4/1358/ifpwafcad.sqlhttp://www.mysql.com/http://java.sun.com/products/jsp/jstl/http://www.netbeans.org/files/documents/4/1851/IFPWAFCAD.ziphttp://dev.mysql.com/downloads/connector/j/http://download.netbeans.org/netbeans/6.1/mysql_bundle/http://dev.mysql.com/downloads/mysql/http://java.sun.com/javase/downloads/index.jsphttp://www.netbeans.org/downloads/index.htmlhttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#seeAlsohttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#deployinghttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingCodehttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingTaglibhttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingJSTLhttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingLogichttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingJarhttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#referencinghttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#settingUphttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#settingUpConnPoolhttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#preparinghttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#creatinghttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#planninghttp://testwww.netbeans.org/kb/60/ide/mysql.htmlhttp://www.netbeans.org/files/documents/4/1358/ifpwafcad.sqlhttp://www.mysql.com/http://java.sun.com/products/jsp/jstl/http://java.sun.com/products/jsp
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    2/18

    he welcome page (index.jsp) presents the user with a simple HTML form. When a client requests the index.jsp page, the

    SP code contained therein is parsed, and data from the Subject database table is gathered, added to the page, and sent tohe client. The user makes a selection in the provided HTML form and submits, which causes the client to make a request foresponse.jsp. When response.jsp is parsed, data from both the Subject and Counselor tables is gathered and inserted into

    he page. Finally, the page is returned to the client and the user views data based upon his or her selection.

    Creating a New Projectn order to implement the scenario described above, you develop a simple application for a fictitious organization namedFPWAFCAD, or The International Former Professional Wrestlers' Association for Counseling and Development. The applicationnables a user to choose a counseling subject from a drop-down list (index.jsp), then retrieves data from the MySQL

    atabase and returns the information to the user (response.jsp).

    index.jsp

    response.jsp

  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    3/18

    Create a new project in the IDE:

    1. Choose File > New Project (Ctrl-Shift-N; -Shift-N on Mac) from the main menu. Under Categories select Java Web (If

    you are using NetBeans 6.0 or 6.1, select Web); under Projects select Web Application. Click Next.2. In Project Name, enter IFPWAFCAD.

    3. Step through the wizard leaving all other settings at their defaults. Specify the server you want to use by selecting fromthe Server drop-down menu. Do not select a framework. When you reach the final panel of the wizard, click Finish.

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

    Editor. index.jsp serves as the welcome page for the application. The new project is structured according to Sun Java

    BluePrints guidelines.

    Preparing the Interface

    Begin by preparing a simple interface for the two pages. Both index.jsp and response.jsp implement an HTML table to

    isplay data in a structured fashion. index.jsp also requires an HTML form that includes a drop-down list.

    index.jspMake 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.

    1. In the Source Editor, change the text between the tags to IFPWAFCAD Homepage.

    2. Change the text between the tags ( tags if you are using NetBeans 6.0 or 6.1) to Welcome to

    IFPWAFCAD, the International Former Professional Wrestlers' Association for Counseling and

    Development!.

    Note: For further content, you can either add HTML elements to the page using the IDE's palette, as

    demonstrated below, or just copy and paste the code provided in step 8 directly into your index.jsp page.

    3. Open the IDE's Palette by choosing Window > Palette (Ctrl-Shift-8;-Shift-8 on Mac) from the main menu. Hoveryour pointer over the Table icon from the HTML category and note that the code snippet for the item displays.

    http://java.sun.com/blueprints/code/projectconventions.html
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    4/18

    Click the icon, and drag and drop a table into the page in the Source Editor, to a point just after the (or

    tags). In the Insert Table dialog that displays, specify the following values then click OK:

    Rows: 2

    Columns: 1

    Border Size: 0

    The HTML table code is generated and added to your page.

    4. Add the following content to the table heading and the cell of the first table row (new content in bold):

    5. For the bottom row of the table, drag and drop an HTML form from the Palette into the page, directly between thesecond pair of tags. In the Action text box, type in response.jsp, then click OK.

    6. Type in the following text between the tags of the form you just created:

    7. Drag and drop a drop-down list from the Palette to a point just after the text you just added. In the Insert Drop-down dialog that displays, type in subject_id for the Name text field, and click OK. Note that the code snippet for

    the drop-down list is added to the form.

    The number of options for the drop-down is currently not important. Later in the tutorial you will add JSTL tags thatdynamically generate options based on the data gathered from the Subject database table.

    8. Add a submit button to the form by dragging a button from the Palette to a point just after the drop-down list youjust added. Enter submit for both the Label and Name text fields, then click OK.

    9. To format your code, right-click in the Source Editor, and choose Format (Alt-Shift-F; Ctrl-Shift-F on Mac). Yourcode is automatically formatted, and should now look similar to the following:

    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:

  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    5/18

    To view this page in a browser, right-click in the Source Editor and choose Run File (Shift-F6). When you do this,the JSP page is automatically compiled and deployed to your server. The IDE opens your default browser to displaythe page from its deployed location.

    response.jspIn order to prepare the interface for response.jsp you must first create the file in your application. Note that most of the

    content that displays in this page is generated dynamically using JSP technology. Therefore, in the following steps you add

    placeholders which you will later substitute for the JSP code.

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

    2. In the JSP File Name field, enter response. Note that Web Pages is currently selected for the Location field,

    meaning that the file will be created in the project's web directory. This is the same location as where the

    index.jsp welcome page resides.

    3. Accept any other default settings 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.

    Welcome to IFPWAFCAD, the International Former

    Professional Wrestlers' Association for Counseling and Development!

    IFPWAFCAD offers expert counseling in a wide range of fiel ds.

    To view the contact details of an IFPWAFCAD certified form er

    professional wrestler in your area, select a subject below :

    Select a subject:

    http://testwww.netbeans.org/images/articles/65/web/mysql-webapp/browser-output.png
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    6/18

    4. In the Source Editor, change the title to IFPWAFCAD - {placeholder}.

    5. Remove the Hello World! (or JSP Page if you are working in NetBeans 6.0 or 6.1) line

    between the tags, then copy and paste the following HTML table into the body of the page:

    To view this page in a browser, right-click in the Source Editor and choose Run File (Shift-F6). The page iscompiled, deployed to your server, and opened in your default browser. Your response.jsp page should display

    similar to the following.

    {placeholder}

    Description: {placeholder}

    Counselor: {placeholder}


    member since: {placeholder}

    Contact Details: email:

    {placeholder}
    phone: {placeholder}

  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    7/18

    style.cssCreate a simple stylesheet that enhances the interface display.

    1. Right-click the IFPWAFCAD project node in the Projects window and choose New > Other. In the New File wizard,make sure Web is selected under Categories, then choose Cascading Style Sheet and click Next.

    2. Type style for CSS File Name and click Finish. The IDE creates an empty CSS file and places it in the same project

    location as index.jsp and response.jsp. Note that a node for style.css now displays within the project in the

    Projects window, and the file opens in the Source Editor.

    3. In the Source Editor, add the following content to the style.css file:

    body {font-family: Verdana, Arial, sans-serif;font-size: smaller;padding: 50px;color: #555;

    }

    h1, h2 {text-align: left;letter-spacing: 6px;font-size: 1.4em;color: #be7429;font-weight: normal;width: 450px;

    }

    table {width: 580px;padding: 10px;background-color: #c5e7e0;

    }

    th {text-align: left;border-bottom: 1px solid;

    }

    td {padding: 10px;

    }

    a:link {color: #be7429;font-weight: normal;text-decoration: none;

    }

    a:link:hover {color: #be7429;font-weight: normal;text-decoration: underline;

    }

    http://testwww.netbeans.org/images/articles/65/web/mysql-webapp/browser-response-page.png
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    8/18

    4. Link the stylesheet to index.jsp and response.jsp:

    In both pages, add the following line between the tags:

    This document assumes that you understand how the stylesheet functions, and how it affects corresponding HTMLelements found in index.jsp and response.jsp.

    When working with CSS in the IDE, you can take advantage of the CSS Style Builder and CSS Preview. Together,these tools provide extensive support for creating style rules and viewing elements when coupled with style attributes.

    For example, place your cursor within the h1, h2 rule in style.css, then open CSS Preview (Window > Other > CSS

    Preview):

    CSS Preview demonstrates how an element renders in a browser. Also note that the preview automatically refreshes as youmake changes to a rule, providing a real-time textual representation of style elements from the IDE.

    Setting up a Connection Pool

    he most efficient way to implement communication between the server and database is to set up a database connection pool.Creating a new connection for each client request can be very time-consuming, especially for applications that continuouslyeceive a large number of requests. To remedy this, numerous connections are created and maintained in a connection pool.

    Any incoming requests that require access to the application's data layer use an already-created connection from the pool.ikewise, when a request is completed, the connection is not closed down, but returned to the pool.

    1. Setting up a JNDI Datasource

    2. Referencing the Datasource from the Application

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

    Setting up a JNDI DatasourceBoth GlassFish and Tomcat contain Database Connection Pooling (DBCP) libraries that provide connection poolingfunctionality in a way that is transparent to you as a developer. In either case, you need to configure aJNDIDatasourcefor the server that creates an interface which your application can use for connection pooling. Depending on whether youare using GlassFish or Tomcat, do the following:

    GlassFish

    The IDE provides enhanced support for GlassFish, enabling you to specify resources using a wizard:

    1. In the Projects window, right-click the Server Resources node and choose New > Other. The New File wizard opens.Under Categories, select GlassFish. Under File Types, select JDBC Resource. Click Next.

    2. Under General Attributes, choose the Create New JDBC Connection Pool option, then in the JNDI Name text field,type in jdbc/IFPWAFCAD . Click Next.

    3. Click Next again to skip Additional Properties, then in Step 4, type in IfpwafcadPool for JDBC Connection Pool

    Name. Make sure the Extract from Existing Connection option is selected, and choosejdbc:mysql://localhost:3306/MyNewDatabase from the drop-down list. Click Next.

    http://java.sun.com/products/jndi/http://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingJarhttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#referencinghttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#settingUphttp://testwww.netbeans.org/images/articles/65/web/mysql-webapp/css-preview.png
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    9/18

    Note: The wizard detects any database connections that have been set up in the IDE. Therefore, you need

    to have already created a connection to the MyNewDatabase database at this point. You can verify what connections

    have been created by opening the Services window (Ctrl-5; -5 on Mac) and looking for connection nodes ( )under the Databases category.

    4. Accept any other default settings within the wizard, then click Finish.

    By completing the wizard, you declared a new datasource and connection pool for the application. In the Projects window,open the newly created Server Resources > sun-resources.xml file and note that, within the tags, a jdbc

    resource and connection pool have been declared containing the values you previously specified.

    To confirm that a new datasource and connection pool are indeed registered with GlassFish, you can deploy the

    project to the server, then locate the resources in the IDE's Services window:

    1. In the Projects window, right-click the IFPWAFCAD project node and choose Deploy (or Undeploy and Deploy). Theserver starts up if not already running, and the project is compiled and deployed to it.

    2. Open the Services window (Ctrl-5) and expand the Servers > GlassFish > Resources > JDBC > JDBC Resources andConnection Pools nodes. Note that the new datasource and connection pool are now displayed:

    Tomcat

    Configure a JNDI Datasource in Tomcat by adding a declaration for your resource to the application's context.xml file.

    This is the application's context container, which enables you to specify application meta-data necessary for the server inorder to deploy and run the application. There are various locations where you can specify context elements, such as yourserver's global $CATALINA_HOME/conf/context.xml file. By adding resource declarations to your application's

    context.xml file however, you limit the resource to that application, and do not need to configure anything within the

  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    10/18

    server itself. For more information, see the Apache Tomcat Configuration Reference.

    1. From the Projects window, open the application's context container in the Source Editor by double-clicking the WebPages > META-INF > context.xml file.

    2. Add the following tags (changes below in bold) as a declaration for the JNDI resource:

    Notice that the declaration is using root and nbuser as your database's username and password. For a more

    thorough explanation of JNDI DataSource configuration, including a description of the parameters used in the aboveresource declaration, refer to the Apache Tomcat 6.0 JNDI Datasource HOW-TO.

    Referencing the Datasource from the ApplicationYou need to reference the JNDI resource you just configured from the web application. To do so, you can create an entryin the application's deployment descriptor(web.xml).

    Deployment descriptors are XML-based text files that contain information describing how an application is to be deployed toa specific environment. For example, they are normally used to specify application context parameters and behavioralpatterns, security settings, as well as mappings for servlets, filters and listeners.

    Do the following to reference the JNDI Datasource in the application's deployment descriptor.

    1. In the Projects window, expand the Web Pages > WEB-INF subfolder and double-click web.xml. A graphical editor

    for the file displays in the Source Editor.

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

    3. For Resource Name, enter the resource name that you gave when configuring the JNDI Datasource for the serverabove (jdbc/IFPWAFCAD). The Description field is optional, but you can enter a human-readable description of the

    resource, e.g., Database for IFPWAFCAD application. Note that the default resource type is

    javax.sql.DataSource . Leave all fields that are provided 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. Notice that the following tags are now included:

    Database for IFPWAFCAD applicationjdbc/IFPWAFCADjavax.sql.DataSourceContainerShareable

    http://testwww.netbeans.org/images/articles/65/web/mysql-webapp/deployment-descriptor.pnghttp://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.htmlhttp://tomcat.apache.org/tomcat-6.0-doc/config/context.html
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    11/18

    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 yourdatabase. Ordinarily, you would need to locate your database driver's installation directory and copy the mysql-

    connector-java-5.x-bin.jar file from the driver's root directory into the library folder of the server you are using.

    Fortunately, the IDE's server management is able to detect at deployment whether the JAR file has been added - and ifnot, it does so automatically.

    In order to demonstrate this, open the Servers window (Choose Tools > Servers). For both GlassFish and Tomcat, the IDEprovides a JDBC driver deployment option. If the option is enabled, it initiates a check to determine whether any driversare required for the server's deployed applications. In the case of MySQL, if the driver is required and it is missing, the

    IDE's bundled driver is deployed to the appropriate location on the server.

    Note: If you are using GlassFish V3, the JDBC driver deployment option is notenabled by default.

    Depending on the server you are using, do the following.

    GlassFish V3

    1. Select GlassFish V3 in the left pane.

    2. In the main pane, select the Enable JDBC Driver Deployment option.

    3. Before you close the window, make a note of the GlassFish installation directory. This is indicated in the Domainsfolder text field.

    4. Click Close to exit the Servers window.

    5. On your computer, navigate to the GlassFish installation directory and drill into the domains > domain1 > lib

    subfolder.

    6. Deploy your project to the server. In the IDE's Projects window, choose Deploy (or Undeploy and Deploy) from theright-click menu of the project node. You can view progress in the IDE's Output window (Ctrl-4; -4 on Mac). Theoutput indicates that the MySQL driver is deployed to a location in the GlassFish server.

    Now, if you return to the domain1/lib subfolder on your computer, you can see that the mysql-connector-java-

    http://testwww.netbeans.org/images/articles/65/web/mysql-webapp/glassfish-v3-output-win.pnghttp://testwww.netbeans.org/images/articles/65/web/mysql-webapp/glassfish-v3-servers-win.png
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    12/18

    5.x-bin.jar file has been automatically added.

    When you connect to GlassFish in the IDE, you are actually connecting to an instance of the applicationserver. Each instance runs applications in a unique domain, and so here the JAR file is located in domain1, which is

    the default domain created upon installing GlassFish. Note that the Domain Name text field in the Servers windowindicates the name of the domain your server is using.

    GlassFish V2

    1. Select GlassFish V2 in the left pane.

    2. Click on the Options tab in the main pane. Notice that the JDBC Driver(s) Deployment Enabled option is selected by

    default.

    3. Locate the GlassFish installation directory. You can do this by clicking the Connection tab and noting the path listedin the Domains folder text field.

    4. Click Close to exit the Servers window.

    5. On your computer, navigate to the GlassFish installation directory and drill into the domains > domain1 > lib

    subfolder. If you have already deployed your project to the server, you will find that the mysql-connector-java-

    5.x-bin.jar file is added here. If not, deploy your project now (next step).

    6. In the Projects window, choose Deploy (or Undeploy and Deploy) from the right-click menu of the project node. Youcan view progress in the IDE's Output window (Ctrl-4; -4 on Mac). The output indicates that the MySQL driver isdeployed to a location in the GlassFish server.

    Now, if you return to the domain1/lib subfolder on your computer, you can see that the mysql-connector-java-

    http://testwww.netbeans.org/images/articles/65/web/mysql-webapp/glassfish-v2-output-win.pnghttp://testwww.netbeans.org/images/articles/65/web/mysql-webapp/glassfish-v2-servers-win.png
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    13/18

    5.x-bin.jar file has been automatically added.

    When you connect to GlassFish in the IDE, you are actually connecting to an instance of the applicationserver. Each instance runs applications in a unique domain, and so here the JAR file is located in domain1, which is

    the default domain created upon installing GlassFish. You can verify this by viewing the Domain Name text field inthe Connection tab.

    Tomcat

    1. Open the Servers window by choosing Tools > Servers from main menu.

    2. Select Tomcat 6.0 in the left panel, then click the Deployment tab in the main pane. Notice that the Enable JDBC

    driver deployment option is selected by default.

    3. Click the Classes tab. This tab displays all of the JAR files contained in the server's lib folder. If you have already

    deployed your project to the server, you will find that the mysql-connector-java-5.x-bin.jar file is listed here.

    If not, click Close to exit the Servers window, and deploy your project now (next step).

    4. In the Projects window, choose Deploy (or Undeploy and Deploy) from the right-click menu of the project node. Youcan view progress in the IDE's Output window (Ctrl-4; -4 on Mac). The output indicates that the MySQL driver isdeployed to /lib in the Tomcat server.

    5. Reopen the Servers window (Tools > Servers) and view the JAR files listed under the Classes tab. You can see thatthe MySQL driver has been automatically added.

    http://testwww.netbeans.org/images/articles/65/web/mysql-webapp/tomcat-output-win.pnghttp://testwww.netbeans.org/images/articles/65/web/mysql-webapp/tomcat-servers-win-depl.png
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    14/18

    Adding Dynamic Logic

    f you return to the index.jsp and response.jsp placeholders created earlier in the tutorial, you can add JSP and JSTL code

    o enable pages to generate content dynamically, i.e., based on user input. To do so, you need to perform the following 3teps:

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

    2. Adding taglib Directives to the JSP Pages

    3. Adding JSP and JSTL Code

    Adding the JSTL Library to the Project's ClasspathIn order to make better use of the JSP resources at your disposal, you can make use of the JavaServer Pages StandardTag Library (JSTL) to access and display data taken from the Logic Layer. This library comes bundled with the IDE. Youtherefore need to make sure the JSTL library is added to the web project's compilation classpath, then add the releventtaglib directives to each of the JSP pages. This allows the server we are using to identify the tags when it reads them

    from the JSP pages. Depending on whether you are using GlassFish or Tomcat, do the following:

    GlassFish V3 and Tomcat

    1. In the Projects window, right-click the project's Libraries node and choose Add Library. Select the JSTL 1.1 libraryand click Add Library. The IDE contains the JSTL 1.1 library by default, and allows you to add it to a project'sclasspath in this manner.

    http://java.sun.com/products/jsp/jstl/http://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingCodehttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingTaglibhttp://testwww.netbeans.org/kb/60/web/mysql-webapp.html#addingJSTLhttp://testwww.netbeans.org/images/articles/65/web/mysql-webapp/tomcat-servers-win-classes.png
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    15/18

    2. Expand the Libraries node and note that two new JAR files have been added: the JSTL library's standard.jar , and

    the jstl.jar. You can further expand the standard.jar file to view JSTL's four basic areas of functionality.

    The JSTL library includes four basic areas of functionality:

    core: common, structural tasks such as iteration

    and conditionals

    fm t: internationalization and locale-sensitiveformatting tags

    sq l: SQL tags

    xm l: manipulation of XML documents

    GlassFish V2

    Do nothing! GlassFish includes the JSTL library by default. You can verify this by expanding the Libraries > GlassFish node.GlassFish V2 contains the appserv-jstl.jar file, which 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 directives to the top of both

    pages:

    http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/x/tld-summary.htmlhttp://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/sql/tld-summary.htmlhttp://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/fmt/tld-summary.htmlhttp://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/c/tld-summary.html
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    16/18

  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    17/18

    A resultset named counsSubjRs is generated from the above SQL query, which contains all data associated with

    the subject_id submitted by the user. Note that data from the Counselor table is acquired by mapping

    counselor_idfk from Subject to counselor_id from Counselor.

    2. Add the following declaration beneath the SQL query from the previous step:

    The tag enables you to set the resultset to a scoped variable, so that you can retrieve its contents at a

    later stage.

    3. In the HTML, replace allplaceholders with JSP code that allows you to retrieve and display the data held in the

    counsSubjresultset (Changes below shown in bold):

    Deploying and Running the Project

    Whether you are using the GlassFish application server or Tomcat, the process for deploying your project is the same. If younstalled GlassFish or Tomcat through the IDE download, your server is already registered in the IDE. If you need to make anyhanges to server settings, or would like to register a different server with the IDE, choose Tools > Servers from the main

    menu to open the Server Manager.

    o deploy the IFPWAFCAD project to the server:

    From the Projects window, right-click the project node and choose Deploy (If you are using NetBeans 6.0 or 6.1,choose Undeploy and Deploy). The IDE compiles the project, starts the server, then deploys the project to it. You cansee 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 Services window (Ctrl-5) and expandthe Servers node. All servers that are registered in the IDE are listed here. For GlassFish, expand Applications > Web

    Applications to view the application. For Tomcat, expand Web Applications to view the IPFWAPCAD application.

    o run the application:

    In the Projects window, right-click the IFPWAFCAD project node and choose Run. The index.jsp page opens in the

    IDE's default browser.

    NetBeans 6.5 now provides a Compile on Save feature. Simply saving a file triggers the IDE to recompile anddeploy it to the server automatically. That way, compilation and deployment take place entirely in the background.Thus, when you run a project, you can be sure the deployment contains the latest changes.

    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:

    ${counsSubj.name}

    ${counsSubj.name}

    Description: ${counsSubj.description

    Counselor: ${counsSubj.first_name} ${counsSubj.nick_name} ${counsSubj.last_nam


    member since: ${counsSubj.member_since}

    Contact Details: email:

    ${counsSubj.email}
    phone: ${counsSubj.telephone}

    http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/c/set.html
  • 8/6/2019 Testwww_ Creating a Simple Web Application Using a MySQL Database - NetBeans IDE 6.x Tutorial

    18/18

    Send Us Your Feedback

    See Also

    his concludes the Creating a Simple Web Application Using a MySQL Database tutorial. This document demonstrated how toreate a simple web application that connects to a MySQL database. It also demonstrated how to construct an applicationsing a basic two-tier architecture, and utilized JSTL and JSP technologies as a means of accessing and displaying data

    ynamically.

    or related or more advanced tutorials, see the following resources:

    Connecting to a MySQL Database in NetBeans IDE. Covers the basics of working with a MySQL database in the IDE.

    NetBeans IDE Tutorial for Web Applications. An in-depth tutorial describing how to build a web application within thecontext of a typical web development cycle.

    Introduction to the Spring Framework. An introductory tutorial describing how to create an MVC web application usingthe Spring Framework in the IDE.

    http://testwww.netbeans.org/kb/60/web/quickstart-webapps-spring.htmlhttp://testwww.netbeans.org/kb/60/web/tutorial-webapps.htmlhttp://testwww.netbeans.org/kb/60/ide/mysql.htmlhttp://testwww.netbeans.org/about/contact_form.html?to=3&subject=Feedback:%20Creating%20Web%20App%20MySQL