MANAGED SERVICES RESOURCE WEB SITE  
  MOREnet logo
Home | E-mail Services | Web Site Management | Managed CMS | Managed LMS | SecondWeb | SSL Certificates | Manager Application |
 Home >  Web Site Management >  Java Application Server >  JavaServer Pages >  Tutorial: Creating Your First Database-enabled Web Application
     
JavaServer Pages  
     
  JSP Tag Libraries  
  Tutorial:Creating Your First Database-enabled Web Application  
  MOREnet Example Web Application  
     

View the printer friendly version of this document

Tutorial: Creating Your First Database-enabled Web Application

Revised: August 01, 2011

Contents

Overview

When you complete this tutorial, you should understand the steps required to begin development of a new web application, including the query and display of data from a MySQL database.

Prerequisites

  1. Complete the Local Development installations for Apache, the Java 2 SDK, MySQL, Apache, and Tomcat. These are available on the kinetic Resources website at this URL:

    http://kinetic.more.net/web/javaserver/localdev/

  2. Start MySQL, Tomcat, and Apache.
  3. Ensure that the MOREnet example is working with the database. Visit the following URL and click the 'MySQL, JDBC, JNDI and JSTL Example' link:

    http://localhost:8080/morenet/

  4. Click the TEST link in the last bullet item. The JSP will execute and, if configured properly, display a page of results. In the middle of the page you should see a table with 'numb_field' and 'char_field' headings, following by data such as '2' and 'Hi Mom'. If you see this page, the connection between the JSP web application, Tomcat, and MySQL is working perfectly and you may continue to the next section.

If you do not see the result page or if a Tomcat exception page displays, you've missed a step during the installation procedures. Inspect the following:

  • Ensure that Apache, Tomcat and MySQL are running.
  • Can you run the examples that come with Tomcat? If not, something is wrong in your tomcat installation. Review the Tomcat installation procedures described on the Resources site. Is there anything suspicious in your Tomcat logs?
  • Ensure that you completed all of the MySQL setup procedures described on the Resources site and try to login to the MySQL monitor.

Creating a New Web Application

The Resources site provides another document, Web Application Overview, that details many of the things you'll be doing in this tutorial. You may want to review it before you continue.

  1. Use Windows Explorer to view the C:\WebPublish\localhost\www directory. This is the directory where you install web applications. Each application is installed in a separate directory. For example, the MOREnet-provided application is located in the morenet directory.
  2. Create a new directory named myfirstapp. You'll save files for your new web application in this directory. Note that this directory name becomes part of the URL to access your web application.
  3. Create the myfirstapp\WEB-INF\ directory. Every web application must have a WEB-INF directory. Inside this directory you'll save configuration files that describe and configure your web application for Tomcat. Note that Tomcat will not serve the content of this directory, so all of its contents are essentially hidden to users of your web application.
  4. Create your first web.xml file in the myfirstapp\WEB-INF\directory. This is the Web Application Deployment Descriptor that configures your web application for Tomcat. Since it is an XML file, it contains only text, so you can create the file in Notepad or Wordpad and save it as a text file. At this point the file should be empty.
  5. Using your text editor, add the following text to the top of the web.xml file:

    <?xml version="1.0" encoding="ISO-8859-1"?>
    
    <!DOCTYPE web-app
        PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">
    

    The first statement identifies the document as an XML document, and the second references the DTD that defines the document ruleset. Note the URL in the DOCTYPE declaration. The DTD is an XML document as well. You can actually view this DTD with a text editor to learn more about the rules for a web.xml file. Note that if you visit the URL with Internet Explorer, it will complain about the structure of the DTD, even though it is a valid, well-formed XML. Just save the file to your desktop and view it with a text editor if you'd like to view the file.

  6. Every web.xml file must contain a <web-app> element as its root element. All of the other elements that configure your web application are nested within the opening <web-app> and closing </web-app> elements. Add these elements to the bottom of your file.
  7. Add a <description> element to describe your application. If you were to provide this application to others, they could review the description for more information about your web application. Make this the first element within the <web-app> element. You should now see the following in your web.xml file:

    <?xml version="1.0" encoding="ISO-8859-1"?>
    
    <!DOCTYPE web-app
        PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">
    
    <web-app>
      <description>My first web application</description>
    </web-app>
  8. Your web.xml file is complete. Save it. The source for your file is available for download in web0.xml. You can save this file and use it, or compare it to the file you created. Note that if you use this file, you must rename it to web.xml. If you just click this link, your browser may attempt to interpret the XML in this file. Use your browser's 'save link as' or 'save target as' feature to save the file if you want to use it.
  9. Create the myfirstapp\WEB-INF\lib\ directory. Most web applications contain a lib directory, but it is not mandatory. The lib directory is where you can store Java source files, including Java libraries, servlets, beans, tag libraries and other supporting Java classes packaged in JAR files (java archive). You'll be using a custom tag library later in this tutorial, so you must create this directory to store the tag library's JAR file.
  10. Create your first file, helloworld.html, in the myfirstapp directory. In addition to files that create dynamic content, such as JavaServer Pages (JSP), web applications can contain HTML files that provide static web content. Using a text editor like Notepad or Wordpad, create helloworld.html and save it with the following contents:

    <html>
      <body>
        <h1>Hello, World</h1>
      </body>
    </html>
    


    The source for your file is available for download in helloworld.html . You can save this file and use it, or compare it to the file you created. Note that if you just click this link, your browser will interpret the HTML in the file. Use your browser's 'save link as' or 'save target as' feature to save the file if you want to use it.

    You now have a complete web application. Although it only contains supporting files and a file with static web content, you have the basic structure of every web application you will create.

  11. Before you can access your application in a web browser, you must instruct Tomcat to start the application. If Tomcat had been stopped, it would have automatically started the application as it started. Because of this, you could just stop and restart Tomcat to start the application. However, using the Tomcat Manager is easier than stopping Tomcat and this is also the process you would use on a production server.

    To start the web application, visit the Tomcat Manager (http://localhost:8080/manager/html) and scroll down to the 'Install directory or WAR file located on server' section. In the WAR or Directory URL option, type myfirstapp and click Install. Tomcat will report 'OK - Installed application at context path /myfirstapp' in the Message section at the top of the page. The application is installed and started.
  12. Visit the following URL to request the helloworld.html file in your web application:

    http://localhost:8080/myfirstapp/helloworld.html

Creating a WAR File

Now that you've created your first web application, you may want to share your work with a colleague. Java web applications are typically distributed in a WAR file. WAR files are similar to ZIP files in that they contain a compressed archive of a set of files. In fact, WAR files use ZIP compression. However, unlike ZIP files, WAR files always maintain the directory structure information and that information is optional in a ZIP file.

Tomcat can take a WAR file and extract its contents, and since the WAR file maintains the directory structure, Tomcat extracts the files into the appropriate directories. Follow this procedure to create a WAR file for your myfirstapp application using the Jar utility provided by Java:

  1. Open a DOS command prompt, and then navigate to the C:\WebPublish\localhost\www\myfirstapp directory.
  2. Issue the following command and press Enter:

    jar cvf ..\myfirstapp.war *.*

    This command instructs the Jar utility to create a new archive; use verbose output--as the files are added to the archive, the Jar utility displays them on your screen; name the archive myfirstapp.war and save it in the parent directory; and include all files in the current directory. Note that directories are recursed automatically by the Jar utility.

    Note: When Tomcat unarchives a WAR file, it places its content in a directory with the same name of the archive. If you share this application with others, their Tomcat application servers will extract the files into myfirstapp directories as well. In this fashion, it exactly replicates your web application regardless of where you install the web application.
  3. To ensure that you don't lose the work you've done in case there is a problem with your WAR file, first make a copy of the existing web application. Use Windows Explorer to copy the contents of C:\WebPublish\localhost\www\myfirstapp directory and place the copy in a safe place.
  4. Stop and remove the existing web application. Visit the Tomcat Manager (http://localhost:8080/manager/html) and stop the existing web application by clicking the Stop link to the right of the myfirstapp path name. When the Tomcat Manager reports OK - Stopped application at context path /myfirstapp, click the Remove link. This deletes the C:\WebPublish\localhost\www\myfirstapp directory and its subdirectories.
  5. Install your .war file using the Tomcat Manager. When you made the .war file, it was saved in the parent directory of the web application. This directory, C:\WebPublish\localhost\www, is where you can place web applications to install them using the Tomcat Manager. If you had created the .war file in a different location, you could copy it to this directory and use the Tomcat Manager to install it. Alternately, you could also use the 'Upload a WAR file to install' feature of the Tomcat Manager to upload and install your .war file from any location. In this case, the .war file already exists in the proper location. To install the web application, type myfirstapp.war in the WAR or Directory URL option in the Tomcat Manager and click Install. The Manager reports OK - Installed application at context path /myfirstapp when the application is installed and lists the application in the Applications area.
  6. Visit this URL, as you did above, to test your application:

    http://localhost:8080/myfirstapp/helloworld.html

Creating your First JavaServer Page (JSP)

Now that you have a solid foundation for your web application, complete this section to install and use the Request JSP custom tag library to produce some dynamic output in a JSP. Follow these steps:

  1. Copy the Request custom tag library files into your web application. Custom tag libraries include a TLD file and a JAR file. The TLD describes the tag library to the servlet container (Tomcat) and the JAR file contains an archive of supporting Java class files that provide the tag library functionality. The TLD is placed in your web application's WEB-INF\ directory, and the JAR file is placed in the WEB-INF\lib\ directory.

    You may get tag libraries in ZIP files, JAR files, or as a set of uncompressed files (only use tag libraries from reputable sources!). The Request tag library is available from the The Jakarta Project. Download a binary distribution of the custom tag libary and save it to a temporary location. Use an unzip program like WinZip to extract the .zip archive of the tag library to a temporary location.

    Use Windows Explorer to view the contents of the unarchived tag library. Copy the request.tld file to the WEB-INF directory in your web application. Copy the request.jar file to the \WEB-INF\lib\ directory in your web application.
  2. You'll be using the Request JSP custom tag library in your JSP. Although it isn't mandatory to describe the custom tag library in your web.xml file, doing this allows you to consistently reference a tag library in a web application, and this is important as you develop more complex JSP web applications. This will be discussed in more detail later in this document when you start using the custom tag library.

    Use a text editor to open the \WEB-INF\web.xml file from your web application. Type the following between the </description> and </web-app> elements:

      <taglib>
        <taglib-uri>request</taglib-uri>
        <taglib-location>/WEB-INF/request.tld</taglib-location>
      </taglib>
    
    Note that the <taglib> element contains <taglib-uri> and <taglib-location> elements. These describe the taglib to Tomcat, and we'll refer to these later in the tutorial when you start using custom tag libraries.

  3. Save the web.xml file and close your text editor.

    The source for your file is available for download in web1.xml. You can use this file or just compare it to the file you created. Note that if you use this file, you must rename it to web.xml. If you just click this link, your browser may attempt to interpret the XML in this file. Use your browser's 'save link as' or 'save target as' feature to save the file if you want to use it.
  4. Reload your web application with the Tomcat Manager. Tomcat loads the web.xml file for each web application upon startup or upon instruction to reload the application. To reload your web application with the modification to web.xml, click the Reload link to the right of the application name in the Tomcat Manager. If you don't do this, Tomcat will continue using the original values from your web.xml file that it loaded into memory.
  5. Create myrequest.jsp in the myfirstapp directory (the root of your web application). Like HTML, JavaServer Pages are just text files, so you can create this file with Wordpad or Notepad and save it with the .jsp filename extension.
  6. Copy and paste the following text into your file:

    <!doctype html public "-//w3c//dtd html 4.0 transitional//en">
    
    <%@ taglib uri="request" prefix="req" %>
    
    <html>
    <head>
       <title>My Request Taglib Example</title>
    </head>
    <body>
    
    </body>
    </html>
    
    Mostly this is standard HTML. Note the taglib directive, however. Remember earlier when you included the taglib elements in your web.xml file? The uri in the directive above exactly matches the taglib-uri in your web.xml. This is intentional (and useful). By using the same name, Tomcat knows that for a specific taglib directive in a JSP, it should find the corresponding taglib-uri and taglib-location specified in the web.xml element.

    The usefulness of this mapping relates to maintenance of your JSPs. For example, if a tag library changed names, including a change in the TLD file name, you could just modify the web.xml elements as appropriate and the tags in your JSPs would work without any modifications!

    The prefix is the actual prefix you use to denote the tag library in your JSP. This name is up to you. It's only restriction is that it must be unique in your JSP.
  7. Use some of the Request custom tags to generate some dynamic output. If you're familiar with HTTP headers, the Request tag library contains some interesting tags that allow you to access the headers. For example, type the following after the taglib directive to display the User-Agent header, if it exists, when someone accesses your JSP:

    <p>
    Does User-Agent Header exist?
    <req:existsHeader name="User-Agent">
       User-Agent=<req:header name="User-Agent"/>
    </req:existsHeader>
    <req:existsHeader name="User-Agent" value="false">
       Header User-Agent does not exist.
    </req:existsHeader>
    </p>
    

    Note: The 'req' in each tag matches the prefix you defined for the tag library at the top of the page. If this prefix does not match a prefix defined in a taglib directive, the JSP compiler in Tomcat throws an error when you attempt to access the JSP. Likewise, if the tag name, such as 'existsHeader', does not exist in the tag library, the compiler stops compiling and throws an error.

    This snippet of code examines if the header exists. If so, it displays the header. If the header doesn't exist, it displays a message that it doesn't exist.

    Tomcat maintains lots of information about HTTP requests, and the Request tag library allows you to easily access this information. For example, add the following code snippet to report if the request is for a secure site:

    <p>
    Is this request secure?
    <req:isSecure>Session is using HTTPS.</req:isSecure>
    <req:isSecure value="false">Session is not using 
      HTTPS.</req:isSecure>
    </p>
    

  8. Save the JSP and close your text editor. The source for your file is available for download in myrequest.txt. Use your browser's 'save link as' or 'save target as' feature if you'd like to use it and then rename it to myrequest.jsp.
  9. Access your JSP by typing the following your web browser:

    http://localhost:8080/myfirstapp/myrequest.jsp

Creating a MySQL Database Table

In the next section you'll create a JSP that queries a database and displays results. Before you can do this, you'll need a database table with some initial data. Typically, you'll create tables for your web applications in MySQL and let your web applications manipulate the data. In this way, you can establish the tables and insert any initial data required by your application. Complete these steps to create the 'mydata' table in MySQL and insert some sample data:

  1. Open a DOS/Command Prompt window.
  2. Use the cd command to navigate to the \mysql\bin\ directory.
  3. Type mysql -u local -p and press ENTER to sign in to the MySQL monitor as the 'local' user. It will prompt you for a password; type the password for the 'local' user.
  4. Type use local; and press ENTER to instruct MySQL to use the 'local' database for commands you'll enter in the following steps.
  5. Type create table mydata ( id int, fruit varchar(40) ); and press ENTER. This command creates the 'mydata' table, with a column named id that will contain integer data, and a column named fruit that will contain character strings up to 40 characters long.
  6. Type insert into mydata VALUES ( '1','Apple'); and press ENTER. This inserts a row of data, with '1' in the first column and 'Apple' in the second column.
  7. Type insert into mydata VALUES ( '2','Orange'); and press ENTER. This inserts another row of data.
  8. Type insert into mydata VALUES ( '3','Peach'); and press ENTER. Once again, you've inserted another row of data.
  9. Type exit and press ENTER to exit the MySQL monitor;

Querying a MySQL Database and Displaying a Result Set with a JSP

Querying a database and displaying a result set is a common task in web applications. Complete the following procedure to create your first JSP that performs this task:

  1. Copy the DBTags custom tag library files into your web application. Like the Request tag library, it is available from the The Jakarta Project. Download a binary distribution of the custom tag libary and save it to a temporary location. Use an unzip program like WinZip to extract the .zip archive of the tag library to a temporary location.

    Use Windows Explorer to view the contents of the unarchived tag library. Copy the dbtags.tld file to the WEB-INF directory in your web application. Copy the dbtags.jar file to the \WEB-INF\lib\ directory in your web application.
  2. Add the configuration settings to web.xml for the DBTags JSP custom tag library. Open the \WEB-INF\web.xml file in a text editor and type the following below the </taglib> element for the Request tag library:

        <taglib>
        <taglib-uri>dbtags</taglib-uri>
        <taglib-location>/WEB-INF/dbtags.tld</taglib-location>
      </taglib>
    

  3. Save the web.xml file and close your text editor. The source for your file is available for download in web2.xml. You can use this file or just compare it to the file you created. If you use it, remember to rename it web.xml. If you just click this link, your browser may attempt to interpret the XML in the file. Use your browser's 'save link as' or 'save target as' feature to save the file if you want to use it.

  4. Use the Tomcat Manager to reload your web application so that Tomcat loads the new web.xml file.
  5. Create database.jsp in the \myfirstapp directory (the root of your web application) with Wordpad or Notepad and save it with the .jsp filename extension.
  6. Copy and paste the following text into your file:

    <!doctype html public "-//w3c//dtd html 4.0 transitional//en">
    
    <%@ taglib uri="dbtags" prefix="sql" %>
    
    <html>
    <head>
       <title>My DBTags Taglib Example</title>
    </head>
    <body>
    
    
    </body>
    </html>
    
    As you did before, you've declared the taglib at the top of the page and given it a prefix; in this JSP you'll denote each DBTags tag with an SQL prefix. And, like the Request tag library in the previous example, you've already configured the corresponding <taglib> elements for this tag library in your web.xml file.
  7. When you installed MySQL, you created a user named 'localweb' and gave it a password. When you installed the Tomcat application server, you specified the same password for the 'localweb' user. Let's review these configuration settings that were created when you did this:

    <!-- JNDI JDBC DataSource Resource for using MySQL dB -->
    <Resource name="jdbc/data" auth="CONTAINER"
              type="javax.sql.DataSource"/>
    <ResourceParams name="jdbc/data">
       <parameter><name>user</name><value>localweb</value></parameter>
       <parameter><name>password</name><value>yourlocalwebpassword</value></parameter>
       <parameter><name>driverClassName</name>
         <value>org.gjt.mm.mysql.Driver</value></parameter>
       <parameter><name>driverName</name>
         <value>jdbc:mysql://localhost/data</value>
       </parameter>
    </ResourceParams>	
    
    These configuration settings establish a JNDI resource for your database in Tomcat. Specifying a JNDI resource for your database allows you to conveniently use the resource name ('jdbc/data') within your applications. In addition, it provides a measure of security since the username and password for access to your database is abstracted out of your JSP pages. For example, to establish a connection to your database in your JSP, copy and paste the following statement:

    <sql:connection id="conn1" jndiName="java:/comp/env/jdbc/data"/>
    
    <sql:closeConnection conn="conn1"/>
    
    The first statement creates a connection named 'conn1' using the JNDI resource named 'jdbc/data'. Note that the full resource name is 'java:/comp/env/jdbc/data'. The 'java:/comp/env/' prefix is required before the beginning of the resource name. The second statement closes the connection established in the first statement. In the following steps you'll be inserting additional statements between these two.
  8. Create a prepared statement for your database query. Copy and paste the following between the <sql:connection.../> and <sql:closeConnection/>tags:

    <sql:preparedStatement id="stmt1" conn="conn1">

    </sql:preparedStatement>

  9. Create a query for all of the rows in the 'mydata' database table that you created with the MySQL monitor in the previous section, and then display the results in a table. Copy and paste the following into your JSP between the preparedStatement tags:

    <table>
    <tr><th>id</th><th>fruit</th></tr>
      <sql:query>
        select * from mydata
      </sql:query>
      <sql:resultSet id="rset1">
        <tr>
          <td><sql:getColumn position="1"/></td>
          <td><sql:getColumn position="2"/></td>
        </tr>
      </sql:resultSet>
      </table>
    
    This snippet of code produces an HTML table structure, selects all columns in the mydata table (* is a wildcard in SQL), and displays each row of data in an HTML table row.
  10. Your JSP is finished. Save it and close your text editor. The source for your file is available for download in database.txt. You can save this file and use it, or compare it to the file you created. Use your browser's 'save link as' or 'save target as' feature to save the file if you want to use it and then rename it database.jsp.
  11. Visit the following URL to run the JSP that you created:

    http://localhost:8080/myfirstapp/database.jsp

    You should see the following results:
idfruit
1Apple
2Orange
3 Peach

Creating Bigger and Better Database-enabled Web Applications

In this example, you learned the following:

  • How to create the directory structure for developing a web application in Tomcat.
  • Where to place custom taglib files, such as the TLD and JAR files.
  • How to create a file of static HTML in your web application.
  • How to configure a web.xml file to meet the minimum needs of a new web application.
  • How to create a simple database table with the MySQL monitor.
  • How to create a JSP that uses the DBTags tag library to query a database and display results.
  • How to create a WAR file for distributing your web application.
  • How to access your new application in a web browser.

Creating bigger and better web applications that communicate with a database requires some additional review and practice. The following should help:

  • You can specify more complex configuration settings in your web.xml files. An overview of installing and configuring web applications is available here:

    http://kinetic.more.net/web/javaserver/webapps/install.shtml

  • Review the DBTags documentation. In the example, you only queried the database and displayed the results. The tag library supports other tags that you'll need for more complex interactions with the database. Review the documentation on the The Jakarta Project web site.
  • Querying the database requires an understanding of the query language. If you're new to SQL, the following URL provides a good jump-start:

    http://www.w3schools.com/sql/

  • Review the MySQL documentation. As you begin to create more complex tables for your data, you'll want to know more about the types of data that MySQL supports and how to manipulate this data:

    http://www.mysql.com/documentation/