FeaturesPluginsDocs & SupportCommunityPartners

NetBeans IDE 4.0 Coin Flip Tutorial

The Coin Flip application that you will build in this tutorial will show you how to do the following:

This application uses the JavaServer Pages Standard Tag Library (JSTL) to fetch dynamic data.

This tutorial can be completed in 30 minutes.


NetBeans 4.0 Quick Start Guide for Web Applications

Starting with NetBeans 4.0 or Java for the first time? See the NetBeans 4.0 Quick Start Guide for Web Applications. Once you have completed it, you will be ready to build on your knowledge with this tutorial!


Setting Up a Project


Creating the storyboard

This sample project simulates flipping a coin and tracks the results.


Initial screen with flip and reset buttons, second screen with number and percentage of heads and tails

This application will implement the storyboard by storing the information in a bean, using a servlet to do the processing, and using a JSP page for the user interface.

Creating a new web application

  1. Choose File > New Project. Under Categories, select Web. Under Projects, select Web Application and click Next.
  2. Under Project Name, enter CoinFlip. Change the Project Location to any directory on your computer. From now on, we will refer to this directory as $PROJECTHOME.
  3. Leave the Set as Main Project checkbox checked and notice that the Context Path is /CoinFlip.
  4. Click Finish. The IDE creates the $PROJECTHOME/CoinFlip project folder. The project folder contains all of your sources and project metadata, such as the project Ant script. The CoinFlip project opens in the IDE. You can view its logical structure in the Projects window and its file structure in the Files window.

Configuring the compilation class path

  1. We will use tags from the JSTL 1.1 library in our JavaServer Pages page. Therefore, we need to add the JSTL 1.1 library to our project's classpath. Right-click the CoinFlip project node in the Projects window and choose Properties.
  2. Select Compiling Sources and click Add Library. Your libraries, as well as those that are bundled with NetBeans 4.0 are displayed. JSTL 1.1 is one of the bundled libraries.
  3. Select JSTL 1.1 and click Add Library.
  4. Click OK to close the Project Properties dialog box.

Creating and Editing Java Source Code


Creating a Java Package, a JavaBeans Component, and a Java Servlet

  1. Expand the CoinFlip project node and the Source Packages node. Note the Source Packages node only contains an empty default package node.
  2. Right-click the Source Packages node and choose New > File/Folder. Under Categories, select JavaBeans Objects. Under File Types, select JavaBeans Component and click Next. Enter TossesBean in the Class Name text box and enter org.me.coin in the Package Name text box. Click Finish. TossesBean.java opens in the Source Editor.
  3. Right-click the org.me.coin package node and choose New > File/Folder. Under Categories, select Web. Under File Types, select Servlet and click Next. Enter Flip in the Class Name text box and make sure that the org.me.coin package is selected in the Package Name combo box. Click Next. Notice that the IDE will add servlet mappings to your web.xml file. Click Finish. Flip.java opens in the Source Editor.

Editing the JavaBeans Component

  1. Expand the org.me.coin package node and the TossesBean.java node.
  2. Expand the class TossesBean node and the Fields node. Right-click the sampleProperty field and choose Delete from the contextual menu. Do the same for the PROP_SAMPLE_PROPERTY field.
  3. Expand the Methods node and delete the getSampleProperty and setSampleProperty methods.
  4. Right-click the Bean Patterns node and choose Add > Property from the contextual menu. The Add Property Pattern dialog box appears. We will create four properties, each consisting of a field, a return statement and a set statement. Note that the NetBeans 4.0 Quick Start Guide for Web Applications describes how you can do this via refactoring. Do the following in the Add Property Pattern dialog box:
    • Enter heads in the Name text box, select int in the Type combo box. Check the Generate Field checkbox, the Generate Return Statement checkbox, and the Generate Set Statement checkbox. Click Ok.
    • Now repeat the process and add the following properties with their return and set statements:
      • int tails
      • double pct_heads
      • double pct_tails
  5. In the Source Editor, do the following:

    • Add these methods to the bottom of the TossesBean class:
          public void reset() {
             setHeads(0);
             setTails(0);
          }
      
          private void setPcts() {
             if (this.heads > 0 || this.tails > 0) {
               if (this.heads == 0) {
                  this.pct_tails = 1.0;
               }
               else if (this.tails == 0) {
                  this.pct_heads = 1.0;
               }
               else {
                  this.pct_heads = ((1.0 * this.heads) / (this.heads + this.tails));
                  this.pct_tails = ((1.0 * this.tails) / (this.heads + this.tails));
              }
            }
            else {
              this.pct_heads = 0.0;
              this.pct_tails = 0.0;
            }
          }
      
    • Add this statement to the end of the TossesBean() constructor:
    •    this.reset();
    • Add this statement to the end of the setHeads method, but before the return statement:
    •    setPcts();
    • Add this statement to the end of the setTails method, but before the return statement:
    •    setPcts();
  6. Right-click anywhere in the Source Editor and choose Reformat Code from the contextual menu.
  7. Press F9 to compile the file. When you are able to compile the file without errors, the Output window shows you that the source file is copied to the build directory. Close the file by pressing Ctrl-F4.

Editing the Java Servlet

  1. Expand the org.me.coin package node and double-click the Flip.java node. Flip.java opens in the Source Editor.
  2. In the Source Editor, do the following:
    • Add this statement to the import section at the top:
         import java.util.Random;

    • Add this statement to the top of the class body:
         private Random generator = new Random();

    • Add this method to the class body:
         private int flipCoin() {
             return Math.abs(generator.nextInt() % 2);
         }
    • Replace the processRequest method body with the following code:
         HttpSession session = request.getSession();
         TossesBean tossesInfo = (TossesBean) session.getAttribute("tossesInfo");
         if ("Reset".equals(request.getParameter("action"))) {
             tossesInfo.reset();
         }
         else {
             int result = flipCoin();
             if (result == 0) {
                 tossesInfo.setHeads(tossesInfo.getHeads() + 1);
             }
             else {
                 tossesInfo.setTails(tossesInfo.getTails() + 1);
             }
         }
         RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
         rd.forward(request, response);
    • In the getServletInfo method, replace "Short description" with a description of the servlet.
  3. Right-click anywhere in the Source Editor and choose Reformat Code from the contextual menu.
  4. Press F9 to compile the file. When you are able to compile the file without errors, the Output window shows you that the source file is copied to the build directory. Close the file by pressing Ctrl-F4.

Creating and Editing JavaServer Pages Files


Editing the default JavaServer Pages File

  1. Expand the CoinFlip project node and the Web Pages node. Notice the IDE has created a default JavaServer Pages page, index.jsp, for you.
  2. Double-click index.jsp. It opens in the Source Editor.
  3. In the Source Editor, create a taglib directive as follows:
    • Open up a line under the last %@page directive, and type <%@t. The code completion box should open and display <%@taglib>. Press Enter. If the code completion box does not appear, press Ctrl-Space.
    • Press the Space bar. The code completion box opens and displays all the attributes for the taglib directive. If the code completion box does not open, press Ctrl-Space to manually open it.
    • Use the arrow keys to select prefix in the code completion box and press Enter.
    • Press the Space bar again and press Enter to add the uri attribute.
    • Insert fmt between the quotation marks for the prefix.
    • Place the cursor between the quotation marks for the uri and press Ctrl-Space. The code completion box should open and display all the web module's tag libraries. If the code completion box does not open, make sure that you included the JSTL 1.1 tag library as described in the "Obtain required resources" activity above, and press Ctrl-Space to manually open it.
    • Use the arrow keys to select http://java.sun.com/jsp/jstl/fmt in the code completion box and press Enter. The taglib directive should look like the following line:
           <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
  4. In the <body> section, type <jsp:u and press Enter when the code completion box appears. If the box does not appear, press Ctrl-Space. Use code completion to add the id, scope, and class attributes such that the line reads as follows:
         <jsp:useBean id="tossesInfo" scope="session" class="org.me.coin.TossesBean" />
  5. Add the following form after the useBean statement:
         <form action="Flip" method="post">
         <table>
            <tr>
               <th class="align-left">
                   <font color="${(tossesInfo.heads) gt (tossesInfo.tails) ? 'green' : 'red'}">
                    Heads
                   </font>
               </th>
               <td><fmt:formatNumber value="${tossesInfo.heads}"/></td>
    	   <td><fmt:formatNumber value="${tossesInfo.pct_heads}" type="percent" /></td>
            </tr>
            <tr>
               <th class="align-left">
                   <font color="${(tossesInfo.tails) gt (tossesInfo.heads) ? 'green' : 'red'}">
                   Tails
                   </font>
               </th>
    	   <td><fmt:formatNumber value="${tossesInfo.tails}"/></td>
               <td><fmt:formatNumber value="${tossesInfo.pct_tails}" type="percent" /></td>
           </tr>
           <tr>
               <td align='center'>
                  <input type="submit" name="action" value="Flip Coin">
               </td>
               <td></td>
               <td align='center'>
                  <input type="submit" name="action" value="Reset">
               </td>
           </tr>
        </table>
        </form> 
  6. Press Ctrl-Shift-F to format the file.
  7. Press Ctrl-S to save the file.

Compiling and Running a Project


Building a project

  • Choose Build > Build Main Project (F11). The CoinFlip project is compiled. Notice that you can right-click a project node in the Projects window and choose Build Project. Just the chosen project is built.

Running the main project

  1. Choose Run > Run Main Project (F6) from the Run menu. Double-click the Output window to maximize it so you can see all the output. Note that Ant builds CoinFlip.war first and then compiles the project using it. Finally, it deploys the web application using your default server.
  2. Select the Files window and expand the project node. The build class files are in the build folder. The build WAR file is in the dist folder.
  3. Press F6 to run the program again. Nothing new needs to be compiled, but the program is run.

Generating Javadoc

  • Select the project node and choose Generate Javadoc for Project. Javadoc output appears in the Output window, and your web browser opens displaying the Javadoc.

Debugging a Project


Debugging a project

  1. Select the Flip.java tab in the Source Editor, place the caret in Flip, and press Alt-G. NameHandler.java opens in the Source Editor.
  2. Go to the processRequest method and place the caret anywhere inside HttpSession session = request.getSession();. Then press Ctrl-F8 to set a breakpoint.
  3. Choose Run > Debug Main Project (F5). The IDE opens the Debugger windows and runs the project in the debugger until the breakpoint is reached.
  4. Select the Local Variables window and expand the this node. The array of strings contains the phrase you entered as the command arguments.
  5. Click Continue (Ctrl-F5) on the main menu to step through the program and watch the name being constructed. When the program ends, the debugger windows close.

Next Steps


Midnight Cookie Company Tutorial

This tutorial shows you how to build, deploy, and execute a web application that contains JavaServer Pages pages and Java servlets and that uses tags from the JSTL tag library. It also shows how to use the HTTP monitor to view the requests and responses between the server and the web browser.

Bookmark this page

del.icio.us furl simpy slashdot technorati digg
Companion
Projects:
MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Virtual Box - full virtualizer  Open ESB - The Open Enterprise Service Bus Powered by