Beginning With The Java EE 6 Platform Hands-On Lab: Alexis Moussine-Pouchkine
Beginning With The Java EE 6 Platform Hands-On Lab: Alexis Moussine-Pouchkine
Hands-On Lab
Alexis Moussine-Pouchkine
Oracle Corporation
Beginning with the Java EE 6 Platform Hands-On Lab
Table of Contents
Introduction....................................................................................................................................................................3
Setup Requirements....................................................................................................................................................... 4
Summarizing Previous Episodes....................................................................................................................................6
ManagedBeans 1.0.................................................................................................................................................... 6
JPA 2.0.......................................................................................................................................................................6
Servlet 3.0................................................................................................................................................................. 6
EJB 3.1...................................................................................................................................................................... 7
Exercise 1 (JSF)............................................................................................................................................................. 8
IDE Code Completion...............................................................................................................................................9
Wire UI control to code behavior............................................................................................................................10
Exercise 2 (JAX-RS)....................................................................................................................................................13
Turn the EJB into a REST service...........................................................................................................................13
Expose a Java object as a RESTful resource.......................................................................................................... 14
Support multiple media types and use a command-line client................................................................................16
Remove web.xml.....................................................................................................................................................17
Exercise 3 (CDI).......................................................................................................................................................... 18
Introduction............................................................................................................................................................. 18
Enable CDI..............................................................................................................................................................18
Standardize on @Inject........................................................................................................................................... 19
Access from JSF facelets........................................................................................................................................ 19
Strongly-typed injection using qualifiers................................................................................................................ 20
Conclusion................................................................................................................................................................... 23
Troubleshooting........................................................................................................................................................... 24
I don't use NetBeans, how can I control GlassFish and deploy the applications?.................................................. 24
Error connection to server localhost on port 1527.................................................................................................. 25
Select deployment server........................................................................................................................................ 26
Database access credentials.....................................................................................................................................26
Accessing the Application Server (GlassFish) Admin Console.............................................................................. 27
Admin Credentials for GlassFish Server.................................................................................................................27
No project loaded in the IDE.................................................................................................................................. 28
Where can I find a list of shortcuts for the NetBeans IDE?.................................................................................... 28
Ok, get me to the solution!...................................................................................................................................... 29
Beginning with the Java EE 6 Platform Hands-On Lab
Introduction
Back in 2006, Java EE 5 had really three themes: Ease of Development, Ease of
Development and Ease of development! The new Java EE Platform version 6 builds on
these major improvements and offers substantial enhancements to existing technologies
(new features, simplifications) but also adds some new capabilities such as
BeanValidation, JAX-RS (RESTful Web Services), and the new and exciting Context and
Dependency Injection (CDI) specification.
This hands-on lab (HOL) is a (very much) stripped-down version of the material available
at http://beginningee6.kenai.com which was developed as a companion set of samples to
the “Beginning Java EE 6 with GlassFish 3” book by Antonio Goncalves (the Second
Edition of the book should be out by the time your read this). This website contains more
than a dozen examples structured as building blocks, starting with a very basic
implementation and scaling to a fully-featured web application covering the new Java EE
6 features. The website also provides everything you should need to explore further the
platform technologies – code, instructions, a forum, and a mailing list.
This lab does not do justice to Java EE 6, but will try to give you a taste of how simple yet
powerful the platform has become. It will cover mainly JavaServer Faces 2.0, JAX-RS 1.1,
and CDI 1.0 with references made to ManagedBeans, EJB 3.1, JPA 2.0, Servlet 3.0, and
more.
Beginning with the Java EE 6 Platform Hands-On Lab
Setup Requirements
The source code for this Hands-On Lab is available in the form of Maven 2 projects to
ease the portability across several development tools and environments. So there is no
requirement for the development environment other than Maven itself. For instance,
NetBeans 6.9 and above can simply open Maven projects as-is without adding any
metadata. The source code can be checked-out from the following URL :
http://kenai.com/projects/beginningee6/sources/src/show/HandsOnLab/
For situations where network access is an issue, NetBeans-specific projects are also
available (respectively called WebApplication1_JSF, WebApplication2_JAXRS, and
WebApplication3_CDI).
With the focus on Java code (vs. XML deployment descriptors) and the general CoC
theme (Convention over Configuration), support for Java EE 6 APIs and wizards in the
development environment is a plus but not an absolute requirement. As such you can
probably follow the entire HOL with a simple code editor. Having said this, NetBeans
6.9.1 is recommended for this lab as it is probably the best out-of-the-box experience for
learning Java EE 6. Eclipse 3.6 (helios), the Oracle Enterprise Pack for Eclipse (OEPE,
which contains the GlassFish 3.x plugin), or IntelliJ are all good options.
The target runtime (AppServer) for this lab is GlassFish 3.0.1 as this is both the reference
implementation for the Java EE platform as well as a production-quality open source
application server focusing on developer experience (among other things). The code
should also work on other Java EE 6 containers when they are made available. This HOL
requires a Java EE 6 Web Profile container and as such you'll notice how the Maven
projects depend on a single platform artifact called javax:javaee-web-api:jar:6.0
(version 6 of the JavaEE Web Profile) rather than expressing a set of dependencies on
individual artifacts for the JSF, JPA, Web Container, EJB Container and other runtimes.
In this lab, if you're using the Maven projects, the top level pom.xml defines three
modules (exercise1, exercise2, and exercise3), some properties for the runtime to be
used, as well as the java.net Maven repository for the artifact and plugin dependencies.
You are welcome to study these settings. A Solution/ sub-directory offers all three
projects completed. If you cannot use Maven (bad network connectivity), the three
exercises are available as three standalone NetBeans projects.
Beginning with the Java EE 6 Platform Hands-On Lab
A browser such as Firefox and a command-line HTTP client (wget, cURL) are also
required.
Once all the software is installed, you will need to open the projects from NetBeans. Point
the IDE to the main pom.xml if using the Maven projects and to the WebApplication*
directories for the standalone projects.
Beginning with the Java EE 6 Platform Hands-On Lab
This is a summary of how we got to exercise #1 of this HOL starting from a couple of
classes, no user-interface and growing from there. You are encouraged to read through
this short introduction and time-permitting to study the Java code mentioned in each of the
following paragraphs.
ManagedBeans 1.0
The application developed here manages a set of books. It uses a new component type –
a managed bean. This is a new lightweight component defined in Java EE 6 which you
can think of as a the foundation for other components (EJB, Servlet, …) which offer
additional services (transactions, security, HTTP, ...). In our case the component is
annotated with @javax.annotation.ManagedBean and generates ISBN numbers
with an interceptor logging calls to this service. Check out IsbnGenerator.java and
LoggingInterceptor.java.
JPA 2.0
Books are JPA entities which are stored in a database with attributes such as ISBN
(string), title (string), price (float), description (string), pages (integer), illustration
(boolean), and a set of tags (a collection of strings mapped to a table using a new JPA
2.0 feature). Check out Book.java.
Servlet 3.0
The initial implementation takes user input from an HTML form and passes it to a servlet
3.0 (now a POJO using the @WebServlet annotation including the mapping information
and removing altogether the need for the web.xml deployment descriptor). This servlet is
responsible for interacting with the JPA entity manager. There is no servlet in this lab as
we're using the higher-level JSF framework.
Beginning with the Java EE 6 Platform Hands-On Lab
EJB 3.1
In order to offer better separation of concerns, an EJB was introduced. The servlet retains
its web front-end responsibility of gathering the user input while the transactional EJB
component offers a clean persistence interaction removing the boiler-plate transactional
code the servlet had to deal with. Check out ItemEJB.java and see how this EJB is
packaged as part of a web application (straight into the WAR, a new feature of Java EE
6).
Another EJB is introduced as a singleton which is instantiated when the container starts
up (yet another new EJB 3.1 features) to offer a language code resolver. Check out
LanguageSingleton.java.
Both these EJBs can now be easily tested from a Java SE environment (JUnit, Maven, ...)
using the new and standard EJBContainer API.
Beginning with the Java EE 6 Platform Hands-On Lab
Exercise 1 (JSF)
With the basic features in place, it's time to put a nice face on this application with
JavaServer Faces (JSF). Make sure you've opened the appropriate project in NetBeans.
Since we use JSF, we no longer need to write our own servlet code (the JSF framework
uses a servlet under the covers), so to begin with, study the code for ItemBean.java.
This is a JSF managed bean (sometimes also called a backing bean) defined as a POJO
and annotated with @javax.faces.bean.ManagedBean and
@javax.faces.bean.RequestScoped. In earlier version of JSF, this metadata (bean
definition and scoping) was defined in the faces-config.xml deployment descriptor
which has now become optional. This makes for an empty WEB-INF directory with no
web.xml either :
The JSF managed bean uses @EJB injection to obtain references to the ItemEJB and
LanguageSingleton bean implementations.
The initList() method (an arbitrary name) is annotated with @PostConstruct which
can be applied to any method in the managed bean and where the list of books is
populated with the help of the ItemEJB abstraction once the component is created by the
container.
Part of the new features in JSF 2.0 is the use by default of Facelets, a framework used by
many in previous versions of JSF which has now become part of the standard. Facelets
entirely express views (pages) with XHTML (well-formed HTML) while binding UI
components such as text fields to the managed bean attributes and controls such as
buttons and links to the aforementioned doXYZ() methods. Such binding is done using
the Expression Language (EL) using the #{...} notation.
Also try Ctrl-clicking on itemBean, as used in the expression language and see how the
IDE takes you to the definition of the JSF managed bean, ItemBean.java in our case.
Beginning with the Java EE 6 Platform Hands-On Lab
</table>
</h:form>
Clean and build the project (right-click “Clean and Build” on the NetBeans project or mvn
clean install from the command line).
Make sure the database is started (check the troubleshooting section for how to do that).
If asked about which server to deploy to, you can chose to have the IDE remember the
setting for this particular project which will add it a Maven profile. With standalone projects
(without Maven), you may need to set the project runtime to GlassFish. For that, right-click
on the project, chose properties and in the Run section set the server to a GlassFish
instance.
Beginning with the Java EE 6 Platform Hands-On Lab
Run the project (right-click “Run” on the NetBeans project). This will cause the following to
happen :
• the GlassFish application server will be started (if not already)
• the web application (packaged as a WAR file) will be deployed to GlassFish
• a browser will be opened at the application URL:
http://localhost:8080/exercise1/newBook.faces
Exercise the application by adding a few books. These will be kept around for the rest of
the lab.
Beginning with the Java EE 6 Platform Hands-On Lab
You can control the web context URL using the runtime project properties. Right from
NetBeans, GlassFish can be controlled (started, stopped, applications deployed, ...) in the
“Servers” section of the “Services” tab :
Use the “View Server Log” option to observe application logging messages as well as for
troubleshooting information. The raw log file is located in :
GLASSFISH_HOME/glassfish/domains/domain1/logs/server.log.
Other improvements in JSF 2.0 include the introduction of composite components (you
can now write custom JSF components in a single XHTML file), new templating features
and the full integration of Ajax in the form of a standardized javascript file and a
<f:ajax> tag. The next exercise has all all three enhancements integrated, check out
source code if you'd like to know more.
Beginning with the Java EE 6 Platform Hands-On Lab
Exercise 2 (JAX-RS)
Before we get on to the RESTful Web Service part of this HOL, a few words about the
starting point for this second exercise.
you are encouraged to study the following source code (if you haven't already done so,
open the project called “Exercise2-JAX-RS” (Maven-based) or “WebApplication2”
(standalone):
• Book.java now inherits from a base class defined in Item.java
• Under “Web Pages”, resources/demo/newItem.xhtml, is a JSF composite
component introduced to manage both books and CDs (see the new newCD.xhtml
page and the updated newBook.xhtml).
• layout.xhtml illustrates how the new templating features of JSF 2.0 can be used.
• Item.java and ItemBean.java both contain BeanValidation (JSR 303, also a
need addition to Java EE 6) annotations constraining the values of the title and the
language code (with a default hard-coded error message).
@Stateless
@Interceptors
@Path("/items") // resource available from the /items path
public class ItemEJB {
and modify its getBook() method to use the following JAX-RS annotations (make sure
the imports use classes prefixed with javax.ws.rs) :
The bookKey variable will be initialized with the parameter extracted from the requested
URL (123 for instance with URL http://localhost:8080/.../items/123).
The above changes will trigger a new “RESTful Web Services” node in the NetBeans
project to appear :
Now let's try this all out and run the project to cause a redeployment. Once the page
appears in the browser, memorize a book ID and type the following address in the
browser window http://localhost:8080/exercise2/resources/items/id
and observe the XML-formatted response. The /resources path is defined in the Jersey
servlet mapping definition in web.xml for Maven-based projects. We'll see later how to go
without this web.xml deployment descriptor. For standalone projects (no Maven), there is
no web.xml and the creation of the @ApplicationPath-annotated class should be
suggested directly to you by the IDE.
Note that browsers such as safari or chrome will show unformatted XML. Use “view HTML
source” to see the formatted version. As an alternative, you can use NetBeans' “Test
RESTful Web Services” feature (right-click on the “RESTful Web Services” node) :
For the time being, trying out other MIME types will all produce XML. Also note that GET
is the only method implemented in this lab (others will cause HTTP 405 – Method not
allowed errors).
Beginning with the Java EE 6 Platform Hands-On Lab
@Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
Now redeploy the application. Now you can open a terminal window and use the cURL
tool to invoke the following commands from the command line :
1.curl http://localhost:8080/exercise2/resources/items/123
2.curl -H "Accept:application/json"
http://localhost:8080/exercise2/resources/items/123
3.curl -H "Accept:application/xml"
http://localhost:8080/exercise2/resources/items/123
Remove web.xml
Finally, as promised, to get rid of the web.xml configuration file, you can use a new
feature of JAX-RS 1.1 which is to create the following empty class in the
org.beginningee6.tutorial package :
@javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends
javax.ws.rs.core.Application {
This maps the JAX-RS (Jersey in our case) servlet to the "resources" path and web.xml
can be deleted altogether (a new feature for Servlet 3.0).
You can now run the application one more time to verify that everything is style working as
previously since this is merely a refactoring to remove XML configuration code.
Note that, as discussed earlier, deleting web.xml is not required for standalone (non-
Maven) projects.
Beginning with the Java EE 6 Platform Hands-On Lab
Exercise 3 (CDI)
Introduction
CDI or Context and Dependency Injection (JSR 299) is an exciting new addition to the
Java EE platform. From a high-level perspective it can be described as offering strongly-
typed and loosely-coupled dependency injection, automatic context management (such
as a “conversation” scope) as well as a number of other features (events, stereotypes,
etc...). This HOL exercise is an introduction to CDI and focuses on the injection part.
CDI builds on top of the annotations defined in JSR 330 (Dependency Injection for Java),
namely @Inject, @Qualifier, and @Named. We will use all three annotations in the
context of our web application running in the application server. Note that CDI is a
required component for the Java EE 6 Web Profile which means that any container
supporting this standard will be able to execute the following code.
Enable CDI
In order to have CDI available to the runtime, the artifacts deployed need to carry along a
beans.xml file (located in WEB-INF/ in our case). Throughout this lab, this file will be
empty but it needs to be present for CDI to kick in (this file is used for more advanced
use-cases such as alternatives where separation of responsibilities is a key requirement).
Using the IDE or your favorite method (Unix touch for instance), create an empty WEB-
INF/beans.xml file in your project. With NetBeans, either right-click on WEB-INF and
chose NEW > XML Document... (make sure you type “beans” for the name as the
extension will be automatically appended) or right-click on the project and chose New >
Other… > Context and Dependency Injection > beans.xml.
Beginning with the Java EE 6 Platform Hands-On Lab
Standardize on @Inject
In ItemEJB.java, replace occurrences of @Resource with @Inject and adjust imports
(right-click in the source code and select “Fix Imports” or use Ctrl+Shift+I). This
delegates to CDI the injection of the resources. The injection resolution will be calculated
at startup so any error will be caught early (as we'll soon see) rather than bogus injections
causing NullPointerExceptions at runtime.
At this point you could run the application again and understand that this is simply a
refactoring not changing the behavior in any way.
In newBook.xhtml, after the language code <h:inputText> on line #45, add the
following code (ideally using code-completion to avoid typos) :
<h:outputLabel value="#{languages.listOfValues}"/>
This uses the bean called “languages” (which was defined above with @Named) to
enumerate valid options for the two-letter language codes. Note that the @Named
annotation can be used without an attribute in which case the bean name is derived from
the Java class name.
Beginning with the Java EE 6 Platform Hands-On Lab
To start dealing with a customer, we need to inject the following attribute to the ItemBean
class (make sure you use “cust” as the variable name) :
getForbiddenToBuy()
getBuyButtonLabel()
doBuy()
The first two methods are bound from the JSF newBook.xhtml page (see lines
#128/#129) while the doBuy() method will actually place the order for a given ISBN
number (line #127).
The deployment should fail and the GlassFish log window (bring it up using a right-click
on the GlassFish node in the “Services” tab) should show a message similar to this
(press Shift+Escape to maximize/minimize the log window) :
Beginning with the Java EE 6 Platform Hands-On Lab
As you can see, the application server does not have enough information about which
specific Customer implementation it should inject as both SpecialCustomer and
DefaultCustomer both implement this interface.
To solve this we'll use a CDI Qualifier defined in Premium.java. This is a custom-
defined annotation which you can use to mark implementations and to qualify injections.
In our case we need to add @Premium to decorate the SpecialCustomer class :
You should see that the application server resolves the injection by providing the
DefaultCustomer implementation. This means that the user is not able to buy
anything and as such the UI should show disabled controls.
Beginning with the Java EE 6 Platform Hands-On Lab
Run one more time the application and see that this time the implementation used is
SpecialCustomer and that the user is indeed able to buy. There is no checkout feature
implemented here so you'll need to check the server log for actual purchasing messages.
This concludes the CDI injection part of this lab. The key take-away is the ability to
change the implementation without having to change the calling/injection code. This is the
reason CDI is being considered as loosely-coupled while the qualifier part is what makes
it strongly-typed (no string involved).
Beginning with the Java EE 6 Platform Hands-On Lab
Conclusion
Hopefully this hands-on lab will have you curious enough to go download GlassFish and
try out Java EE 6 for yourself. Start developing with Java EE 6 today!
Troubleshooting
I don't use NetBeans, how can I control GlassFish and deploy the applications?
To start GlassFish :
% $GLASSFISH_HOME/bin/asadmin start-domain
C:\> %GLASSFISH_HOME%\bin\asadmin start-domain
or :
% $GLASSFISH_HOMEbin/asadmin start-domain --verbose
C:\> %GLASSFISH_HOME%\bin\asadmin start-domain –verbose
You are also encourage to use the web admin console for deployment (need to start
GlassFish first) available at http://localhost:4848.
Port 1527 is the database (JavaDB/Derby) default port. If the database isn't already
started locally, you'll need to start it straight from the NetBeans IDE using Services >
Databases > Java DB > Start Server as shown in the following screenshots.
Beginning with the Java EE 6 Platform Hands-On Lab
Note that both this project and the solutions are marked with the “Completed” tag :