Java Ee 7 Development With Netbeans 8
Java Ee 7 Development With Netbeans 8
P U B L I S H I N G
pl
$ 49.99 US
30.99 UK
Sa
m
C o m m u n i t y
David R. Heffelfinger
Java EE 7 Development
with NetBeans 8
Java EE 7 Development
with NetBeans 8
ee
D i s t i l l e d
Java EE 7 Development
with NetBeans 8
Develop professional enterprise Java EE applications quickly and
easily with this popular IDE
E x p e r i e n c e
David R. Heffelfinger
Chapter 7, Messaging with JMS and Message-driven Beans, explains Java EE messaging
technologies such as the Java Message Service (JMS) and Message-driven Beans (MDB),
covering NetBeans' features that simplify application development taking advantage of
these APIs.
Chapter 8, Java API for JSON Processing, explains how to process JSON data using the
new JSON-P Java EE API.
Chapter 9, Java API for WebSocket, explains how to use the new Java API for
WebSocket to develop web-based applications featuring full duplex communication
between the browser and the server.
Chapter 10, RESTful Web Services with JAX-RS, covers RESTful web services with the
Java API for RESTful Web Services, including coverage of how NetBeans can
automatically generate RESTful web services and both Java and JavaScript RESTful web
service clients.
Chapter 11, SOAP Web Services with JAX-WS, explains how NetBeans can help us easily
develop SOAP web services based on the Java API for the XML Web Services (JAXWS) API.
Introduction
Obtaining NetBeans
Installing NetBeans
Introduction
NetBeans is an Integrated Development Environment (IDE) and platform.
Although initially, the NetBeans IDE could only be used to develop Java
applications, as of version 6, NetBeans supports several programming languages,
either through built-in support, or by installing additional plugins. Programming
languages natively supported by NetBeans include Java, C, C++, PHP, HTML, and
JavaScript. Groovy, Scala, and others are supported via additional plugins.
In addition to being an IDE, NetBeans is also a platform. Developers can use
NetBeans' APIs to create both NetBeans plugins and standalone applications.
[8]
Chapter 1
Obtaining NetBeans
NetBeans can be obtained by downloading it from http://www.netbeans.org.
[9]
Description
Java SE
Java EE
C/C++
Chapter 1
NetBeans Bundle
Description
All
To follow the examples in this book, either the Java EE or the All bundle is needed.
The screenshots in this book were taken with the Java EE bundle.
NetBeans may look slightly different if the All bundle is used,
particularly, some additional menu items might be seen.
Windows
Linux (x86/x64)
Mac OS X
The NetBeans download page should detect the operating system being used to
access it, and the appropriate platform should be selected by default. If this is not
the case, or if you are downloading NetBeans with the intention of installing it in
another workstation on another platform, the correct platform can be selected from
the drop down labeled appropriately enough as Platform.
Once the correct platform has been selected, we need to click on the appropriate
Download button for the NetBeans bundle we wish to install; for Java EE
development, we need either the Java EE, or the All bundle. NetBeans will
then be downloaded to a directory of our choice.
[ 11 ]
Installing NetBeans
NetBeans requires a Java Development Kit (JDK) Version 1.7 or newer to be
available before it can be installed.
Since this book is aimed at experienced Java developers, we will not
spend much time explaining how to install and configure the JDK. We
can safely assume that the target market for the book is more than likely
to have a JDK installed. Installation instructions for the Java Development
Kit can be found at http://docs.oracle.com/javase/7/docs/
webnotes/install/index.html.
NetBeans installation varies slightly between the supported platforms. In the following
few sections we explain how to install NetBeans on each supported platform.
Microsoft Windows
For Microsoft Windows platforms, NetBeans is downloaded as an executable
file named something like netbeans-8.0-javaee-windows.exe (exact name
depends on the version of NetBeans and the NetBeans bundle that was selected
for download). To install NetBeans on Windows platforms, simply navigate to the
folder where NetBeans was downloaded and double-click on the executable file.
Mac OS X
For Mac OS X, the downloaded file is called something like netbeans-8.0-javaeemacosx.dmg (exact name depends on the NetBeans version and the NetBeans bundle
that was selected for download). In order to install NetBeans, navigate to the location
where the file was downloaded and double-click on it.
[ 12 ]
Chapter 1
Linux
For Linux, NetBeans is downloaded in the form of a shell script. The name of the file
will be similar to netbeans-8.0-javaee-linux.sh (exact name will depend on the
version of NetBeans and the selected NetBeans bundle).
Before NetBeans can be installed on Linux, the downloaded file needs to be
made executable, which can be done using a command lineby navigating to
the directory where the NetBeans installer was downloaded and executing the
following command:
chmod +x filename.sh
Other platforms
For other platforms, NetBeans can be downloaded as a platform independent ZIP
file. The name of the ZIP file will be something like netbeans-8.0-201403101706javaee.zip (exact filename may vary, depending on the exact version of NetBeans
downloaded and the NetBeans bundle that was selected).
To install NetBeans on one of these platforms, simply extract the ZIP file to any
suitable directory.
Installation procedure
Even though the way to execute the installer varies slightly between platforms, the
installer behaves in a similar way between most of them.
One exception is the platform independent ZIP file, in which there is
essentially no installer. Installing this version of NetBeans consists of
extracting the ZIP file to any suitable directory.
[ 13 ]
After executing the NetBeans installation file for our platform, we should see a
window similar to the one illustrated in the following screenshot.
The pack shown may vary depending on the NetBeans bundle that was downloaded.
The preceding screenshot is for the Java EE bundle.
At this point, we should click on the button labeled Next> to continue the installation.
[ 14 ]
Chapter 1
NetBeans is dual licensed, licenses for NetBeans include the GNU Public License
(GPL) Version 2 with the classpath exception, and the Common Development and
Distribution License (CDDL). Both of these licenses are approved by the Open
Source Initiative (OSI).
To continue installing NetBeans, click on the checkbox labeled I accept the terms in
the license agreement and click on the button labeled Next>.
[ 15 ]
NetBeans comes bundled with JUnit, a popular Java unit testing framework. JUnit's
license differs from the NetBeans license, so it needs to be accepted separately.
Clicking the Next> button takes us to the next step in the installation wizard:
At this point the installer will prompt us for a NetBeans installation directory, and
for a JDK to use with NetBeans. We can either select new values for these or retain
the provided defaults.
Once we have selected the appropriate installation directory and JDK, we need to
click on the button labeled Next> to continue the installation.
NetBeans uses the JAVA_HOME environment variable to populate
the JDK's directory location.
[ 16 ]
Chapter 1
The installer will now prompt us for an installation directory for the GlassFish
application server, as well as for the JDK to use for GlassFish; we can either enter
a custom directory or accept the default values and then click on Next>.
[ 17 ]
If we chose to install Tomcat, the installer will prompt us for a Tomcat installation
directory. Again, we can either enter a custom directory or accept the default values
and then click on Next>.
At this point, the installer will display a summary of our choices. After reviewing the
summary, we need to click on the button labeled Install to begin the installation.
[ 18 ]
Chapter 1
As the installation begins, the installer starts displaying a progress bar indicating the
progress of installation.
After NetBeans and all related components have been installed, the installer indicates
a successful installation, giving us the option to contribute anonymous usage data as
shown in the preceding screenshot. After making our selection we can simply click
on the Finish button to exit the installer.
On most platforms, the installer places a NetBeans icon on the desktop; the icon
should look like the following:
[ 19 ]
Once NetBeans starts, we should see a page with links to demos, tutorials, and
sample projects, among others.
[ 20 ]
Chapter 1
Every time NetBeans is launched, it shows the default start page as illustrated in the
preceding screenshot. If we don't want this page to be displayed automatically every
time NetBeans is started, we can disable this behavior by un-checking the checkbox
labeled as Show on Startup at the top of the page. We can always get the start page
back by going to Help | Start Page.
[ 21 ]
[ 22 ]
Chapter 1
2. Next, we need to right-click on the node labeled Servers in the tree inside
the Services window, and then select Add Server... from the resulting
pop-up menu.
3. Then we need to select the server to install from the list in the resulting
window, and click on the button labeled Next>.
[ 23 ]
5. Finally, we need to select a domain, host, and port for our application server,
then click on the Finish button.
[ 24 ]
Chapter 1
The Services window should now display our newly added application server:
[ 25 ]
We then need to select a JAR file containing the JDBC driver for our RDBMS,
NetBeans guesses the name of the driver class containing the JDBC driver. If more
than one driver class is found in the JAR file, the correct one can be selected from the
drop-down menu labeled Driver Class. We need to click on the OK button to add
the driver to NetBeans as shown in the following screenshot:
[ 26 ]
Chapter 1
Once we have followed the preceding procedure, our new JDBC driver is displayed
in the list of registered drivers.
[ 27 ]
Then we need to enter the JDBC URL, username, and password for our database.
After clicking on the Next> button, NetBeans will ask us to select a database schema.
In this case, we select PUBLIC from the drop-down menu.
[ 28 ]
Chapter 1
In the next step in the wizard, we are allowed to enter a user-friendly name for our
database connection, or we can simply accept the default value.
After clicking on the Finish button, our database is shown in the list of databases in
the Services window. We can connect to it by right-clicking on it, selecting Connect
from the resulting pop-up menu, then entering our username and password for the
database (if we chose not to allow NetBeans to remember the password when we
added the database).
[ 30 ]
Chapter 1
After clicking on the Next> button, we are prompted to enter a project location in the
next pop-up window. In this case, the default value is sensible.
Once we click on the Finish button, our new project is displayed in the
Projects window:
[ 31 ]
At this point, we should see the output of the build script. Also, both the integrated
GlassFish application server and the integrated JavaDB RDBMS system should
automatically start.
[ 32 ]
Chapter 1
If our browser is displaying a page similar to the preceding one shown, then we can
be certain that NetBeans and GlassFish are working properly and we are ready to
start developing our own Java EE applications.
Code completion
The NetBeans code editor includes a very good code completion feature,
for example, if we wish to create a private variable, we don't need to type the
whole private word, we can simply write the first three letters (pri), then hit
Ctrl + Space and NetBeans will complete the word private for us.
[ 33 ]
Code completion also works for variable types and method return values, for
example, if we want to declare a variable of type java.util.List, we simply need
to type the first few characters of the type, then hit Ctrl + Space NetBeans will try to
complete with variable types in any of the packages we have imported in our class.
In order to make NetBeans attempt to complete with any type in the classpath, we
need to hit Ctrl + Space again.
As we can see in the preceding screenshot, NetBeans displays JavaDoc for the class
we selected from the code completion options. Another time-saving feature is that
the class we selected from the options is automatically imported into our code.
Once we have the type of our variable, we can hit Ctrl + Space right after the variable
and NetBeans will suggest variable names.
[ 34 ]
Chapter 1
When we want to initialize our variable to a new value, we can simply hit Ctrl +
Space again and a list of valid types is shown as options for code completions
as demonstrated in the following screenshot:
[ 35 ]
[ 36 ]
Chapter 1
Notice how the JavaDoc for the selected method is automatically displayed.
Code templates
Code templates are abbreviations for frequently used code snippets. To use a
code template, we simply type it into the editor and hit the Tab key to expand the
abbreviations into the full code snippet it represents.
For example, typing sout and pressing the Tab key will expand into
System.out.println("");, with the caret placed between the two double quotes.
[ 37 ]
Some of the most useful code templates are listed in the following table, please note
that code templates are case sensitive.
Abbreviation
Psf
fore
Description
ifelse
Generate an if-else
conditional statement.
if (boolVar) {
} else {
}
psvm
soutv
System.out.println("boolVar =
" +
boolVar);
Generate a System.out.
println() statement
displaying the value of a
variable.
trycatch
try {
Generate a try-catch
block.
whileit
while (iterator.hasNext()) {
Object object =
iterator.next();
}
[ 38 ]
Chapter 1
To see the complete list of code templates, click on Tools | Options, click on the
Editor icon, then on the Code Templates tab.
We can add our own templates by clicking on the New button. We will be prompted
for the template's abbreviation. Once we enter it, our new template will be added to
the template list and will automatically be selected. We can then enter the expanded
text for our template in the Expanded Text tab.
[ 39 ]
Code templates can be used not only for Java but for HTML, CSS, and all other
editors in NetBeans. To view/edit templates for other languages, simply select the
desired language from the Language drop-down menu under the Code Templates
tab as indicated in the following screenshot:
Keyboard shortcuts
NetBeans offers several keyboard shortcuts that allow very fast navigation between
source files. Memorizing these keyboard shortcuts allows us to develop code a lot
more effectively than relying on the mouse.
Some of the most useful NetBeans' keyboard shortcuts are listed in
this section, but this list is by no means exhaustive. The complete
list of NetBeans' keyboard shortcuts can be obtained by clicking on
Help | Keyboard Shortcuts Card.
[ 40 ]
Chapter 1
One useful keyboard shortcut that allows us to quickly navigate within a large Java
file is Ctrl + F12. This keyboard shortcut switches focus to the Navigator window,
which displays an outline of the current Java file and shows all its methods and
member variables.
When the Navigator window has focus, we can simply start typing to narrow down
the list of member variables and methods shown. This keyboard shortcut makes it
very fast to navigate through large files.
Hitting Alt + F12 will open the Hierarchy window, which outlines the class hierarchy
of the current Java class.
[ 41 ]
Another useful keyboard shortcut is Alt + Insert. This keyboard shortcut can be
used to generate frequently used code such as that for constructors, getter and
setter methods, among others.
Sometimes, we would like to know all the places in our project where a specific
method is invoked. Hitting Alt + F7 while the method is highlighted allows us to
easily find out this information.
[ 42 ]
Chapter 1
Sometimes navigating through all the files in a project can be a bit cumbersome,
especially if we know the name of the file we want to open but we are not sure of
its location. Luckily, NetBeans provides the Shift + Alt + O keyboard shortcut that
allows us to quickly open any file in our project:
One last thing worth mentioning, even though it is not strictly a keyboard shortcut, a
very useful feature of the NetBeans editor is that left-clicking on a method or variable
while pressing Ctrl will turn the method or variable into a hyperlink. Clicking on this
hyperlink will result in NetBeans taking us to the method or variable declaration.
When there is a warning in our code, NetBeans will alert us in two ways, it will
underline the offending line with a squiggly yellow line, and it will place the
following icon in the left margin of the offending line:
The light bulb in the icon indicates that NetBeans has a suggestion on how to fix the
problem. Moving the caret to the offending line and hitting Alt + Enter, as discussed
in the previous section, will result in NetBeans offering one or more ways of fixing
the problem.
[ 44 ]
Chapter 1
Similarly, when there is a compilation error, NetBeans will underline the offending
line with a red squiggly line, and place the following icon on the left margin of
said line.
Again, the light bulb indicates that NetBeans has suggestions on how to fix
the problem. Hitting Alt + Enter in the offending line will allow us to see the
suggestions that NetBeans has.
NetBeans not only provides visual cues for errors in our code, it also provides other
cues, for example, placing the caret next to an opening or closing brace will highlight
both the opening and closing brace, as shown in the populateList() method. This
is demonstrated in the previous screenshot.
If one of our methods overrides a method from a parent class, the following icon will
be placed in the left margin next to the method declaration:
The icon is an upper case "O" inside a circle, the O stands for "override".
Similarly, when one of our methods is an implementation of a method declared
on an interface, the following icon will be placed in the left margin of the
method declaration.
The icon is an uppercase "I" inside a green circle, which stands for "implements".
NetBeans also provides visual cues in the form of fonts and font colors, for example,
static methods and variables are shown in italics, member variables are shown in
green, and Java reserved keywords are shown in blue.
Another nice feature of the NetBeans editor is that highlighting a method or variable
highlights it everywhere it is used in the currently open file.
[ 45 ]
The accelerated HTML5 development support feature works "out of the box"
with the embedded WebKit browser. To test it, select the embedded WebKit browser,
then run the application we deployed earlier in this chapter in the Deploying our
first application section. It will run inside NetBeans when using the embedded
WebKit browser.
[ 46 ]
Chapter 1
Number:
<h:inputText id="inputGuess" value="#{game.guess}"
required="true" size="3"
disabled="#{game.number eq game.guess}"
validator="#{game.validateNumberRange}">
</h:inputText>
<h:commandButton id="GuessButton" value="Guess"
action="#{game.check}"
disabled="#{game.number eq game.guess}"/>
<h:commandButton id="RestartButton" value="Reset"
action="#{game.reset}" immediate="true" />
<h:outputText id="Higher" value="Higher!"
[ 47 ]
Replace the string Number with the string Your Guess, so that the markup now looks
like this:
<h:panelGrid border="1" columns="5" style="font-size: 18px;">
Your Guess:
<h:inputText id="inputGuess" value="#{game.guess}"
required="true" size="3"
disabled="#{game.number eq game.guess}"
validator="#{game.validateNumberRange}">
</h:inputText>
<h:commandButton id="GuessButton" value="Guess"
action="#{game.check}"
disabled="#{game.number eq game.guess}"/>
<h:commandButton id="RestartButton" value="Reset"
action="#{game.reset}" immediate="true" />
<h:outputText id="Higher" value="Higher!"
rendered="#{game.number gt game.guess and
game.guess ne 0}" style="color: red"/>
<h:outputText id="Lower" value="Lower!"
rendered="#{game.number lt game.guess and
game.guess ne 0}" style="color: red"/>
</h:panelGrid>
Save the file, and without redeploying the application or reloading the page,
go back to the embedded browser window. Our change will be reflected on
the rendered page.
[ 48 ]
Chapter 1
[ 49 ]
Clicking on the button labeled Go to Chrome Web Store takes us directly to the
download page for the NetBeans Connector plugin:
Clicking on the button labeled Free at the upper-right corner results in a pop-up
window displaying the permissions for the NetBeans connector plugin:
[ 50 ]
Chapter 1
Clicking on the Add button automatically installs the plugin. We can then run our
project on the Chrome browser and any changes we make to the markup will be
instantly reflected on the browser.
As we can see in this screenshot, when running our application through the
NetBeans connector, Chrome displays a message alerting us of the fact.
Summary
In this chapter, we learned how to download and install NetBeans.
We also learned how to set up NetBeans with third-party Java EE application servers
and with third-party relational database systems, including how to register a JDBC
driver for the RDBMS in question.
We built and deployed our first Java EE application by using one of the sample
projects included by NetBeans.
Finally, we covered some of the NetBeans' features such as code completion, code
templates, keyboard shortcuts, and visual cues that allow us to do our job more
effectively as software developers.
[ 51 ]
www.PacktPub.com
Stay Connected: