
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.
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
- Choose File > New Project. Under Categories, select Web.
Under Projects, select Web Application and click Next.
- 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.
- Leave the Set as Main Project checkbox checked and notice
that the Context Path is /CoinFlip.
- 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
- 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.
- 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.
- Select JSTL 1.1 and click Add Library.
- 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
- Expand the CoinFlip project node and the Source Packages
node. Note the Source Packages node only contains an empty default
package node.
- 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.
- 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
- Expand the org.me.coin package node and the
TossesBean.java node.
- 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.
- Expand the Methods node and delete the getSampleProperty
and setSampleProperty methods.
- 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
- In the Source Editor, do the following:
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();
- Right-click anywhere in the Source Editor and choose Reformat Code from the contextual menu.
- 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
- Expand the org.me.coin package node and double-click the Flip.java node. Flip.java
opens in the Source Editor.
- 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.
- Right-click anywhere in the Source Editor and choose Reformat Code from the contextual menu.
- 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
- Expand the CoinFlip project node and the Web Pages node.
Notice the IDE has created a default JavaServer Pages page, index.jsp,
for you.
- Double-click index.jsp. It opens in the Source
Editor.
- In the Source Editor, create a taglib directive as follows:
- 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" />
- 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>
- Press Ctrl-Shift-F to format the file.
- 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
- 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.
- 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.
- 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
- 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.
- Go to the
processRequest method and place the caret anywhere
inside HttpSession session = request.getSession();. Then press Ctrl-F8
to set a breakpoint.
- Choose Run > Debug Main Project (F5). The IDE opens the Debugger
windows and runs the project in the debugger until the breakpoint is
reached.
- Select the Local Variables window and expand the this node. The
array of strings contains the phrase you entered as the command arguments.
- 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
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.
|
Related Documents
Quickly create, build, and deploy a simple HelloWeb
web application.
A short guide to getting your existing web applications
into NetBeans IDE 4.0.
Transition guide for NetBeans IDE 3.6 users.
A complete list of docs for NetBeans IDE 4.0.
|