Getting Started with Java EE 6

By on Wednesday, January 27th, 2010 in Technical | Related Software Packages: , , , , , , , , | Keywords: ,

In this tutorial we’ll update you on the world of Java EE 6 with the help of a Twitter-like demo application we’ve code-named wallfriend. The demo application contains JSF 2.0, PrimeFaces, CDI and Weld as well as Hibernate Validator frameworks.

Before You Start

Our tutorial assumes that you’re familiar with the following technologies:

  • JavaServer Faces (JSF) and Facelets
  • Dependency Injection Mechanism
  • Bean Validation

You’ll also need to install the following applications in order to build the demo application from scratch, or to run it on your local machine:

  • Java 6 (Java SDK 1.6) or greater
  • NetBeans 6.8 bundled with GlassFish 3
  • Maven, preferably the latest version 2.2.1 (Netbeans ships with Maven 3.0-SNAPSHOT, so that can also be used)

Meat & Potatoes

What’s New with Java EE 6?

Java EE 6 specification was finalized in December of 2009, bringing new and updated features to the world of enterprise application development. It introduces the profile approach, meant to focus both developers and applications on particular parts of the Java EE 6 platform. The first profile defined by the expert group is the Java EE 6 web profile, which attempts to specify the minimal configuration targeted for the development of typical web applications. Here are the elements of the web profile, with a few that we’ve chosen to explain in detail.

  1. Servlet 3.0
    In web frameworks, servlets are used as an entry point to handle all incoming requests, so it could be said that they are the core elements of web-based applications. The new 3.0 version (specification JSR-315) offers innovative features like ease of development with annotations (@Servlet, @ServletFilter, @ServletContextListener) and annotations for restful services like @GET, @POST and more. It also offers pluggability and extensibility. The main aim here is to attain zero-configuration when working with other frameworks and libraries. Toward this end, a  new xml tag definition called <web-fragment> can be used to apply this feature. The web fragments, which are to be stored inside the jars of their respective libraries, will be merged by the container — so there’s no need for the developer to set up any configurations on the web descriptor file. Speaking of pluggability and extensibility, Servlet 3.0 also has a new application programming interface (API) which can be used to add servlets and filters with coding.
  2. JavaServer Pages (JSP) 2.2
  3. ExpressionLanguage (EL) 2.2
  4. Debugging Support for Other Languages (JSR-45) 1.0
  5. Standard Tag Library for JavaServer Pages (JSTL) 1.2
  6. JavaServer Faces (JSF) 2.0
    Ever since  the release of JSF’s 1.X version, its aim was to be the go-to framework for building user interfaces and web applications. As it gained popularity with many application developers around the world, there was a growing awareness of terrific features like componenting, validation, navigation, i18n and others. However, as with so many wonderful things, flaws and disadvantages became more evident over time — like how complicated it could be to accomplish even a simple task such as creating your own custom JSF component. JSF version 2.0 aims to remedy these flaws by simplifying and easing development and introducing new features, like built-in Ajax support, which will make standard some of what have until now been third party solutions. Here’s a quick summary of the improvements that are part of JSF 2.0.

    • Composite components
      Implementing custom JSF components in 1.x is a real burden. You have to implement a UI component and Tag class, with the option of a Renderer for the markup, and then configure all these within faces-config and tld files. JSF 2.0 simplifies the procedure with the composite component approach introduced in Facelets.
    • Native Ajax Support
      JSF 2.0 provides built-in support for Ajax with its API and infrastructure.  A good example of the useful new components is f:ajax.
    • State Saving
      Since JSF 2.0 aims to handle requests partially with classes like PartialViewContext and PartialStateHolder (among others), it also attempts to make use of a partial mechanism to handle state saving. This has been implemented before, by Apache Trinidad, but PartialStateHolder and StateHelper classes provide a more elegant solution. The goal is to have a lightweight version of the saved state going back and forth in response to requests.
    • Scopes
      In addition to the request, session and application scopes, 2.0 also introduces view and flash scopes. View-scoped beans have a life span that is longer than a request, but shorter than session-scoped beans. Flash scopes are like the view scopes that will live on a specified view, including the redirects, and will be removed if you’re moving another view.
    • Navigation
      In JSF 1.x every navigation rule should be added to faces-config.xml. With version 2.0 implicit navigation can also be used, as in whether or not an outcome corresponds to a view I.D. It’s also possible to perform conditional navigations on a navigation-case. The new tag <if> can be used in faces-config, with an el snippet for conditional navigation. Version 2.0 also makes it easy to retrieve view parameters and assign them to a given property, which in turn makes handling the parameters for GET requests easy. Two new components (h:link and h:button) also support the integration of view parameters. The key benefit of using these components will be bookmarkable URLs.
    • Configuration with Annotations
      With JSF 2.0 you can annotate your managed beans with the new @ManagedBean annotation, and you can specify the scope for your beans with @RequestScoped, @SessionScoped, @ViewScoped, @NoneScoped and more. Instead of those, we’ve chosen to use CDI and Weld annotations.
  7. Common Annotations for Java Platform (JSR-250) 1.1
  8. Enterprise JavaBeans (EJB) 3.1 Lite
  9. Java Transaction API (JTA) 1.1
  10. Java Persistence API (JPA) 2.0
    In our opinion, the main highlights of this release are the API for criteria queries and the support for validation. There are also some fancy new features like extended map support and ordered list mappings.
Download the Open Source Policy Builder

Java EE 6 Containers

There are currently two application servers that are compatible with the implementation of Java EE 6: GlassFish Enterprise Server v3 and TMAX JEUS 7. We’ve chosen to stick with GlassFish v3.

So – What’s Up with PrimeFaces?

PrimeFaces is an open source JSF component suite that bundles over 70 components with built-in Ajax support. It’s based on the YUI and jQuery javascripting libraries. It has a simple, lightweight design that is fully compatible with other JSF component libraries. PrimeFaces also supports Ajax Push with a Comet framework, and it has a mobile UI kit known as TouchFaces. Currently, PrimeFaces supports JSF 2.0 with its 2.0.0.RC and 2.0.0-SNAPSHOT releases.

The ability of Java EE 6 to merge web.xml fragments that originate from third-party frameworks makes it unnecessary (in the context of Java EE 6) to do servlet and mapping configurations for PrimeFaces. Primefaces ships with its own web-fragment.xml.

For more information, visit www.primefaces.org.

Contexts and Dependency Injection (CDI)

As stated in Java Specification Request JSR-299, the purpose of this specification is to unify the JSF-managed bean component model with the EJB component model, resulting in a significantly simplified programming model for web-based applications. CDI also makes it possible for JEE elements to interact with each other using the observer pattern, making it a lot easier to work with enterprise beans and transactional support, among other things.

Dependency Injection For Java

JSR 330 is also a part of Java EE 6, offering a set of standard annotations that can be used for dependency injection. In our demo application we’ll use some of these annotations, such as @Named, @Inject, @Qualifier and others.

WELD

Weld is the reference implementation of JSR-299, which is abbreviated as CDI.  Weld provides a complete SPI, allowing Java EE containers to use Weld as their built-in CDI implementation. GlassFish 3 (which we’ll use in our demo) ships with Weld.

Bean Validation and Hibernate Validator

The Bean Validation, JSR 303, defines a metadata model and an API for JavaBean validation. The Hibernate Validator is the reference implementation for this specification request. Hibernate Validator’s latest version adds some nice features — things like validation grouping, native integration with JPA v.2 and JSF v.2, an extended annotation set and more.

WallFriend, The Demo APP

Let’s start by creating the project. We’ll do it using the Maven archetype command. It has an interactive mode, so see below for the user input data (in bold).

mvn archetype:generate -DarchetypeCatalog=http://anonsvn.jboss.org
   /repos/weld/archetypes/tags/1.0.0-BETA1
DEV$ mvn archetype:generate -DarchetypeCatalog=http://anonsvn.jboss.org
   /repos/weld/archetypes/tags/1.0.0-BETA1
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] ------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO]    task-segment: [archetype:generate] (aggregator-style)
[INFO] ------------------------------------------------------------------
[INFO] Preparing archetype:generate
[INFO] No goals needed for project - skipping
[INFO] Setting property: classpath.resource.loader.class =>
'org.codehaus.plexus.velocity.ContextClassLoaderResourceLoader'.
[INFO] Setting property: velocimacro.messages.on => 'false'.
[INFO] Setting property: resource.loader => 'classpath'.
[INFO] Setting property: resource.manager.logwhenfound => 'false'.
[INFO] [archetype:generate]
[INFO] Generating project in Interactive mode
[INFO] No archetype defined. Using maven-archetype-quickstart
(org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Choose archetype:
1: remote -> weld-jsf-servlet-minimal (Weld archetype for creating an
application using JSF 2.0 and CDI 1.0 for Servlet Containers
(Tomcat 6 / Jetty 6))
2: remote -> weld-jsf-jee-minimal (Weld archetype for creating a minimal
Java EE 6 application using JSF 2.0, CDI 1.0 and EJB 3.1 (persistence unit
not included))
3: remote -> weld-jsf-jee (Weld archetype for creating a Java EE 6
application using JSF 2.0, CDI 1.0, EJB 3.1 and JPA 2.0 (persistence
unit included))
Choose a number:  (1/2/3): 2

Here enter 2, for weld-jsf-jee-minimal. And then specify the
groupId-artifactId-packaging for the project.

Define value for groupId: : com.openlogic.wazi
Define value for artifactId: : wallfriend
Define value for package: : war
Confirm properties configuration:
version: 1.0.0-SNAPSHOT
groupId: com.openlogic.wazi
artifactId: wallfriend
package: war
 Y: : Y
[INFO] -------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -------------------------------------------------------------------
[INFO] Total time: 19 seconds
[INFO] Finished at: Tue Jan 12 21:58:35 EET 2010 [INFO]
Final Memory: 12M/79M [INFO]
-------------------------------------------------------------------

Since this is an archetype project, we can immediately run it from the command line with Maven on an embedded GlassFish:

DEV$ mvn package embedded-glassfish:run
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'embedded-glassfish'.
[INFO] org.apache.maven.plugins: checking for updates from glassfish
[INFO] org.codehaus.mojo: checking for updates from glassfish
[INFO] -------------------------------------------------------------------
[INFO] Building wallfriend
[INFO]    task-segment: [package, embedded-glassfish:run]
[INFO] -------------------------------------------------------------------
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Compiling 1 source file to /DEV/wallfriend/target/classes
[INFO] [resources:testResources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:testCompile]
[INFO] Compiling 1 source file to /DEV/wallfriend/target/test-classes
[INFO] [surefire:test]
[INFO] Surefire report directory: /DEV/wallfriend/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running TestSuite
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.369 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] [war:war]
[INFO] Packaging webapp
[INFO] Assembling webapp[wallfriend] in [/DEV/wallfriend/target/wallfriend]
[INFO] Processing war project
[INFO] Webapp assembled in[162 msecs]
[INFO] Building war: /DEV/wallfriend/target/wallfriend.war
[INFO] [embedded-glassfish:run]
[WARNING] Attempting to build MavenProject instance for Artifact
(org.codehaus.mojo:jboss-maven-plugin:3.0) of type: maven-plugin;
constructing POM artifact instead.
Downloading: http://repository.jboss.org/maven2/org/codehaus/mojo
/jboss-maven-plugin/3.0/jboss-maven-plugin-3.0.pom
Downloading: http://repo1.maven.org/maven2/org/codehaus/mojo
/jboss-maven-plugin/3.0/jboss-maven-plugin-3.0.pom
[WARNING] Attempting to build MavenProject instance for Artifact
(org.apache.maven.plugins:maven-eclipse-plugin:3.0)  of type:
maven-plugin; constructing POM artifact instead.
Downloading: http://repository.jboss.org/maven2/org/apache/maven
/plugins/maven-eclipse-plugin/3.0/maven-eclipse-plugin-3.0.pom
Downloading: http://repo1.maven.org/maven2/org/apache/maven
/plugins/maven-eclipse-plugin/3.0/maven-eclipse-plugin-3.0.pom
Jan 13, 2010 10:36:39 PM com.sun.enterprise.v3.server.AppServerStartup run
INFO: GlassFish v3 (74.2) startup time : Embedded(1228ms)
startup services(1317ms) total(2545ms)
Jan 13, 2010 10:36:39 PM com.sun.enterprise.transaction
.JavaEETransactionManagerSimplified initDelegates
INFO: Using com.sun.enterprise.transaction.jts
.JavaEETransactionManagerJTSDelegate as the delegate
Jan 13, 2010 10:36:40 PM org.glassfish.admin.mbeanserver
.JMXStartupService$JMXConnectorsStarterThread run
INFO: JMXStartupService: JMXConnector system is disabled, skipping.
Jan 13, 2010 10:36:40 PM AppServerStartup run
INFO: [Thread[GlassFish Kernel Main Thread,5,main]] started
Jan 13, 2010 10:36:40 PM org.hibernate.validator.util.Version
INFO: Hibernate Validator null
Jan 13, 2010 10:36:40 PM org.hibernate.validator.engine.resolver
.DefaultTraversableResolver detectJPA
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver
.JPATraversableResolver.
Jan 13, 2010 10:36:41 PM com.sun.enterprise.v3.services.impl
.GrizzlyProxy$2$1 onReady
INFO: Grizzly Framework 1.9.18-k started in: 434ms listening on port 7070
Jan 13, 2010 10:36:58 PM com.sun.common.util.logging
.LoggingConfigImpl openPropFile
INFO: Cannot read logging.properties file.
Jan 13, 2010 10:36:58 PM com.sun.enterprise.web.WebContainer
createHttpListener
INFO: Created HTTP listener embedded-listener on port 7070
Jan 13, 2010 10:36:58 PM com.sun.enterprise.web.WebContainer
configureHttpServiceProperties
WARNING: pewebcontainer.invalid_http_service_property
Jan 13, 2010 10:36:59 PM com.sun.enterprise.web.WebContainer createHosts
INFO: Created virtual server server
Jan 13, 2010 10:36:59 PM com.sun.enterprise.web.WebContainer
loadSystemDefaultWebModules
INFO: Virtual server server loaded system default web module
^[[BJan 13, 2010 10:37:08 PM com.sun.enterprise.security.SecurityLifecycle
INFO: security.secmgroff
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.ssl.SSLUtils
checkCertificateDates
SEVERE: java_security.expired_certificate
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.SecurityLifecycle
onInitialization
INFO: Security startup service called
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.PolicyLoader
loadPolicy
INFO: policy.loading
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.auth.realm.Realm
doInstantiate
INFO: Realm admin-realm of classtype com.sun.enterprise.security.auth
.realm.file.FileRealm successfully created.
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.auth.realm.Realm
doInstantiate
INFO: Realm file of classtype com.sun.enterprise.security.auth.realm.file
.FileRealm successfully created.
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.auth.realm.Realm
doInstantiate
INFO: Realm certificate of classtype com.sun.enterprise.security.auth
.realm.certificate.CertificateRealm successfully created.
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.SecurityLifecycle
onInitialization
INFO: Security service(s) started successfully....
classLoader = WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)
SharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7@2d205042
Jan 13, 2010 10:37:09 PM org.jboss.weld.bootstrap.WeldBootstrap
INFO: WELD-000900 SNAPSHOT
Jan 13, 2010 10:37:09 PM org.hibernate.validator.engine.resolver
.DefaultTraversableResolver detectJPA
INFO: Instantiated an instance of org.hibernate.validator.engine
.resolver.JPATraversableResolver.
nullID: /DEV/wallfriend/gfembed6764346819525137279tmp/applications
/wallfriend/ CLASSES: [class war.HelloWorld]

Jan 13, 2010 10:37:10 PM com.sun.faces.config.ConfigureListener
contextInitialized
INFO: Initializing Mojarra 2.0.2 (FCS b10) for context '/wallfriend'
Jan 13, 2010 10:37:14 PM com.sun.enterprise.web.WebApplication start
INFO: Loading application wallfriend at /wallfriend
Hit ENTER to redeploy, X to exit

Once you see the line Hit ENTER to redeploy, X to exit, make a request for http://localhost:7070/wallfriend on your browser. You should get a first look at the archetype application like the one below:

WallFriend - FirstLook

Now, let’s open the project inside NetBeans 6.8. Open NetBeans and click File > New Project and then select Maven / Maven Project with Existing POM from the resulting wizard. This should put the Open Project menu on your screen. Select wallfriend from here and you should see the project in the projects tab:

WallFriend - NetBeans

To run wallfriend inside NetBeans 6.8, you need to make sure that you have Java 1.6 defined as a Java platform, and be sure that wallfriend is also using it. Also, from the Tools > Servers menu, you need to define the Java 1.6 executable for your GlassFish. Netbeans also comes with a Maven 3.0-SNAPSHOT version. So, if you want to use your own external Maven, you must declare it to the IDE from Preferences > Miscellaneous > Maven. After configuring it all, just make a request for http://localhost:8080/wallfriend on your browser. You should see the very same page as you did when you ran the project with the embedded GlassFish.

Adding PrimeFaces to the Project

In order to use the JSF components of PrimeFaces, we first have to add the repo and dependency definitions to the pom.xml of the project. Go ahead and open Project Files > pom.xml in NetBeans and add the following snippets, respectively:

<repository>
    <id>prime-repo</id>
    <name>Prime Technology Maven Repository</name>
    <url>http://repository.prime.com.tr</url>
    <layout>default</layout>
</repository>

<dependency>
    <groupId>org.primefaces</groupId>
    <artifactId>primefaces</artifactId>
    <version>2.0.0-SNAPSHOT</version>
</dependency>

Now namespace can be added inside the xhtml’s files for PrimeFaces, xmlns:p=”http://primefaces.prime.com.tr/ui”. As mentioned above, there is no configuration needed in web.xml since PrimeFaces ships with its own web fragment.

Wallfriend – The Implementation

As we said before, wallfriend is a simple write-to-wall application with a basic domain, managed beans, and some xhtml pages. You can check out the source from the Google Code project at http://wallfriend.googlecode.com/svn/trunk/wallfriend. A follow the wall mechanism as well as a restful expose of the wall will be added to the project in the near future.

Since the application was not created from scratch, we have some clean-up to do on the archetype-created application. Go ahead and delete the following folders, because they won’t be used:

  • Web Pages/WEB-INF/templates
  • Web Pages/resources
  • Source Packages / war
  • Test packages / war

Now let’s go through the parts of the project: The Model, The Managed Beans, and The Views.

The Model

For the domain, we have 3 classes: Wall, Brick and WallFriendContext. Wall and Brick are for defining a master-detail relationship between the posts and the wall. WallFriendContext is the application-scoped bean for storing created walls. It’s marked with the javax.enterprise.context.ApplicationScoped bean.

Wall.java

package com.openlogic.wazi.beans;

import java.util.LinkedList;
import java.util.List;

public class Wall {

    String wallName;

    List bricks = new LinkedList();

    public Wall(String wallName) {
        this.wallName = wallName;
    }

    public void addBrick(String graffiti) {
        bricks.add(0, new Brick(graffiti));
    }

    public String getWallName() {
        return wallName;
    }

    public List getBricks() {
        return bricks;
    }
}

Brick.java

package com.openlogic.wazi.beans;

import java.util.Date;

public class Brick {

    private String graffiti;
    private Date publishDate;

    public Brick(String graffiti) {
        this.graffiti = graffiti;
        this.publishDate = new Date();
    }

    public void init() {
    }

    public String getGraffiti() {
        return graffiti;
    }

    public void setGraffiti(String graffiti) {
        this.graffiti = graffiti;
    }

    public Date getPublishDate() {
        return publishDate;
    }

    public void setPublishDate(Date publishDate) {
        this.publishDate = publishDate;
    }
}

WallFriendContext.java

package com.openlogic.wazi.beans;

import java.util.HashMap;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class WallFriendContext {

    private Map walls = new HashMap();

    public void addWall(Wall wall) {
        walls.put(wall.getWallName(), wall);
    }

    public Map getWalls() {
        return walls;
    }
}

The Managed Beans (a.k.a. Contextual Beans)

The managed bean classes are defined by the CDI and implemented by Weld, which ships with the GlassFish server. CDI also needs an empty beans.xml file under the WEB-INF folder, since we’re going to use annotations to define our beans. That’s right — that means they can also be configured with good old fashioned XML.

LoginView is the managed bean of choice for handling wall management and creation/accessing. The annotation javax.enterprise.inject.Model identifies the LoginView as a bean of the model layer, as stated in the MVC pattern. We use javax.inject.Inject to identify injectable constructors, while methods and fields. org.hibernate.validator.constraints.NotEmpty is a validator annotation that specifies that the field wallName cannot be empty.

package com.openlogic.wazi.view;

import com.openlogic.wazi.beans.Wall;
import com.openlogic.wazi.beans.WallFriendContext;
import javax.enterprise.inject.Model;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import org.hibernate.validator.constraints.NotEmpty;

@Model
public class LoginView {

    @Inject
    private WallFriendContext wallFriendContext;

    @NotEmpty(message="Wall Name cannot be empty")
    private String wallName;

    public String doLogin() {
        Wall wall;
        if (wallFriendContext.getWalls().containsKey(wallName)) {
            wall = wallFriendContext.getWalls().get(wallName);
        }
        else {
            wall = new Wall(wallName);
            wallFriendContext.addWall(wall);
        }
        FacesContext.getCurrentInstance().getExternalContext()
.getRequestMap().put("wall", wall);

        return "myWall";
    }

    public String getWallName() {
        return wallName;
    }

    public void setWallName(String wallName) {
        this.wallName = wallName;
    }
}

MyWallView is the managed bean for handling the paint-a-graffiti on the wall action. The annotation javax.inject.Named, used here, allows you to access the bean using the bean name, with the first letter in lowercase. We use javax.annotation.PostConstruct to mark a method to be invoked after the Dependency Injection is done.

package com.openlogic.wazi.view;

import com.openlogic.wazi.beans.Wall;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.hibernate.validator.constraints.NotEmpty;

@Named
@SessionScoped
public class MyWallView implements Serializable {

    private Wall wall;

    @PostConstruct
    public void init() {
        wall = (Wall) FacesContext.getCurrentInstance()
                  .getExternalContext().getRequestMap().get("wall");
    }

    @NotEmpty(message="Graffiti cannot be empty")
    private String graffiti;

    public String paint() {
        wall.addBrick(graffiti);
        graffiti = "";

        return null;
    }

    public Wall getWall() {
        return wall;
    }

    public void setWall(Wall wall) {
        this.wall = wall;
    }

    public String getGraffiti() {
        return graffiti;
    }

    public void setGraffiti(String graffiti) {
        this.graffiti = graffiti;
    }
}

The Pages

Facelets, JSF 2.0, and PrimeFaces projects are used for the development of views. JSF tags are also commonly used. One different component could be p:growl, which is for viewing the FacesMessages in a Mac-like growl. Also, there is no defined navigation-rule in the faces-config.xml file for navigating from login.xhtml to myWall.xhtml. This is with the implicit navigation mechanism that comes with JSF 2.0. The return string of LoginView#doLogin() method matches the name of the myWall.xhtml view.

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
     xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.prime.com.tr/ui">
      <h:head>
          <title>WallFriend - Java EE 6 Starter Application</title>
      </h:head>
      <h:body>
          <h:form>
              <p:growl showDetail="true" />
              <p:panel header="Access to your wall" style="width:400px">
                  <h:outputLabel value="Wall Name : " for="wallname" />
                  <h:inputText id="wallname" value="#{loginView.wallName}" />
                  <h:commandButton value="Paint it Now, Paint it Black"
                      action="#{loginView.doLogin}" />
              </p:panel>
          </h:form>
      </h:body>
</html>

myWall.xhtml page renders the wall posts for a wall, and the user can also write up to the wall.

 <html xmlns="http://www.w3.org/1999/xhtml"
       xmlns:h="http://java.sun.com/jsf/html"
       xmlns:f="http://java.sun.com/jsf/core"
       xmlns:ui="http://java.sun.com/jsf/facelets"
       xmlns:p="http://primefaces.prime.com.tr/ui">
       <h:head>
          <title>WallFriend - Java EE 6 Starter Application</title>
       </h:head>
       <h:body>
          <h:form>
             <p:growl showDetail="true" />
                <p:panel header="#{myWallView.wall.wallName}'s WALL"
                    style="width:600px">
                   <h:panelGrid columns="1">
                   <h:panelGroup>
                      <h:inputTextarea value="#{myWallView.graffiti}"
                             cols="50" rows="3" />
                      <h:commandButton value="Paint"
                             action="#{myWallView.paint}" />
                   </h:panelGroup>
                   <p:dataTable value="#{myWallView.wall.bricks}"
                            var="brick">
                      <p:column>
                        #{brick.graffiti}
                        <br/>
                        <h:outputText value="#{brick.publishDate}">
                           <f:convertDateTime dateStyle="default"
                              type="both" pattern="dd.MM.yyyy HH:mm:ss" />
                        </h:outputText>
                     </p:column>
                  </p:dataTable>
               </h:panelGrid>
            </p:panel>
         </h:form>
      </h:body>
</html>

Finishing Up

Java EE 6 is hot, new, and pretty darn cool. In our opinion, as users begin to employ it for upcoming projects, the number of blogposts, samples, and other resources will eventually increase. And with its adoption by the Java Community, we’ll for sure see more Java EE 6-compliant application servers around. Java EE 6 really eases development with its “standardized” features, and the zero-configuration approach apparent in every part of the implementation is really nice, lending an out-of-the-box feeling that’s similar to the .NET environment.  It’s not just another java framework!

Related posts:

  1. Creating a Continuous Integration Server for Java Projects Using Hudson
  2. Choosing the Right Java Web Development Framework
  3. Getting Started with Mercurial
  4. iText: Generate PDFs in Java
  5. Creating a Maven-Based Development Environment on Linux

Related Open-Source Packages

Glassfish: See all Glassfish Articles » Get Glassfish Support at OLEX »
Java: See all Java Articles » Get Java Support at OLEX »
Java EE: See all Java EE Articles » Get Java EE Support at OLEX »
JavaServer Faces: See all JavaServer Faces Articles » Get JavaServer Faces Support at OLEX »
JQuery: See all JQuery Articles » Get JQuery Support at OLEX »
JSF: See all JSF Articles » Get JSF Support at OLEX »
Maven: See all Maven Articles » Get Maven Support at OLEX »
NetBeans: See all NetBeans Articles » Get NetBeans Support at OLEX »
YUI: See all YUI Articles » Get YUI Support at OLEX »

Mert

Mert Caliskan is a software architect working for STM A.S., a defense contractor located in Turkey. He worked several years on various Enterprise Java Projects mostly built upon open source frameworks. He is a founder & committer of open-source projects like PrimeFaces, mesir, YUI4JSF, JSFExcelCreator, HibernateTrace and a contributor of Apache MyFaces. He is a sun certified java professional and javablackbelt contest winner. He gives speeches at local and international conferences about OSS frameworks and tries to leverage the use of them.

23 Responses to “Getting Started with Java EE 6”

  1. Dan Allen says:

    Glad to see the Weld archetypes getting some use! Thanks for writing this up Mert.

    Two minor corrections.

    1) In the summary of JSF 2.0 scopes, I believe you have view scope and flash scope mixed up. The view scope is state associated with a view (whose state is maintained across multiple postbacks to the same view). The flash scope temporarily holds state in a “mini” session across a redirect to a view (same view or a different view).

    2) Per the spec, CDI beans cannot be configured via XML. The beans.xml is only for enabling alternatives, interceptors and decorators at the moment. In the future, there maybe a schema for defining and configuring beans via XML. Until then, you can use a Weld portable extension: http://anonsvn.jboss.org/repos/seam/modules/xml/trunk/

    Also, if I may offer a design suggestion. You are really encouraged to expose state through named CDI beans or producer methods rather than using the JSF API to explicitly assign values to request-scoped variables. For instance, you could have a session-scoped WallContext bean that you inject into LoginView and MyWallView that holds the wall for the current user. Prefer injection of state holders over any explicit assignments.

    Keep up the good work!

  2. Very cool !!! JEE6 will come with every power !!!
    Regards.

  3. [...] Mão na massa com JEE 6 01/29/2010 Fernando Franzini Deixe um comentário Ir para os comentários Nesse tutorial vc pode encontrar detalhes de implementação do mais novo mundo do JEE6, vendo um exemplo completo chamado de “wallfriend”. A aplicação é baseada no JSF 2.0, usando PrimeFaces, CDI e Hibernate validator framework. Acesse o artigo completo atraves do site wazi. [...]

  4. Helen Neely says:

    This is nice – just to see how easy it is to integrate PrimeFaces with the latest Java EE 6.
    Nice article BTW :)

  5. Bill Shannon says:

    Mert, please note that there is nothing called “JEE6″. The correct name is “Java EE 6″.
    I would greatly appreciate it if you would update your article to use the correct name.

    Thanks.

    Bill Shannon
    Java EE Spec Lead

    http://www.java.com/en/about/brand/naming.jsp

  6. Mert says:

    Thanks Dan,

    Your comments clarify the scopes better. View do live more than a request scope but yeah across the same view…

    I should have stated the name of that WELD extension. Thanks for pointing that out.

    Yeah that’ll be a more CDI-wise design, I’ll do some work for that on wallfriend project. You can join in if you want also :)

    Cheers…

  7. Mert says:

    Thanks Bill,

    name corrected.. we’re now saying “java” :) …viva la Java…

    Cheers…

  8. Rob Kraft says:

    Prime faces looks nice. Any comparisons to ICEFaces?

  9. Praveen says:

    I am seeing below error when I run the first mvn command. Please help.

    =========================
    C:\demos\EE6>mvn archetype:generate -DarchetypeCatalog=http://anonsvn.jboss.org
    [INFO] Scanning for projects…
    [INFO] Searching repository for plugin with prefix: ‘archetype’.
    [INFO] ————————————————————————
    [INFO] Building Maven Default Project
    [INFO] task-segment: [archetype:generate] (aggregator-style)
    [INFO] ————————————————————————
    [INFO] Preparing archetype:generate
    [INFO] No goals needed for project – skipping
    [INFO] Setting property: classpath.resource.loader.class => ‘org.codehaus.plexus.velocity.ContextClassLoaderResourceLo
    er’.
    [INFO] Setting property: velocimacro.messages.on => ‘false’.
    [INFO] Setting property: resource.loader => ‘classpath’.
    [INFO] Setting property: resource.manager.logwhenfound => ‘false’.
    [INFO] [archetype:generate {execution: default-cli}]
    [INFO] Generating project in Interactive mode
    [WARNING] Error reading archetype catalog http://anonsvn.jboss.org
    java.lang.RuntimeException: java.lang.NullPointerException
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1014)
    at sun.net.www.protocol.http.HttpURLConnection.getHeaderField(HttpURLConnection.java:2211)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:382)
    at org.apache.maven.wagon.providers.http.LightweightHttpWagon.fillInputData(LightweightHttpWagon.java:115)
    at org.apache.maven.wagon.StreamWagon.getInputStream(StreamWagon.java:116)
    …………………………………
    Caused by: java.lang.NullPointerException
    at sun.net.www.ParseUtil.toURI(ParseUtil.java:261)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:795)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
    … 28 more
    [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.
    0)
    Choose archetype:
    Choose a number: : /repos/weld/archetypes/tags/1.0.0-BETA1

  10. dario says:

    the “la” in the phrase “viva la java” is wrong. just say: “Viva Java!”

  11. Mert says:

    Praveen,

    Because of the styling that we have in wazi, that mvn command was split into two lines. You’re missing the second part. It should be like this,

    mvn archetype:generate -DarchetypeCatalog=http://anonsvn.jboss.org/repos/weld/archetypes/tags/1.0.0-BETA1

  12. @Rob, to learn more about how PrimeFaces compares with other libraries, whyprimefaces page can help;

    http://www.primefaces.org/whyprimefaces.html

  13. Victor says:

    Hi when execute mvn package give the error:

    C:\test>mvn -e package embedded-glassfish:run
    + Error stacktraces are turned on.
    [INFO] Scanning for projects…
    [INFO] Searching repository for plugin with prefix: ‘embedded-glassfish’.
    [INFO] ————————————————————————
    [ERROR] BUILD ERROR
    [INFO] ————————————————————————
    [INFO] The plugin ‘org.apache.maven.plugins:maven-embedded-glassfish-plugin’ does not exist or no valid version could be found
    [INFO] ————————————————————————
    [INFO] Trace
    org.apache.maven.lifecycle.LifecycleExecutionException: The plugin ‘org.apache.m
    aven.plugins:maven-embedded-glassfish-plugin’ does not exist or no valid version
    could be found
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.verifyPlugin(DefaultLifecycleExecutor.java:1569)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.getMojoDescriptor(DefaultLifecycleExecutor.java:1851)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.segmentTaskListByAggregationNeeds(DefaultLifecycleExecutor.java:462)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:175)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
    at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:6
    0)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)

    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.version.PluginVersionNotFoundException: The plugin ‘org.apache.maven.plugins:maven-embedded-glassfish-plugin’ does not exist or no valid version could be found
    at org.apache.maven.plugin.version.DefaultPluginVersionManager.resolvePluginVersion(DefaultPluginVersionManager.java:229)
    at org.apache.maven.plugin.version.DefaultPluginVersionManager.resolvePluginVersion(DefaultPluginVersionManager.java:91)
    at org.apache.maven.plugin.DefaultPluginManager.verifyPlugin(DefaultPluginManager.java:179)
    at org.apache.maven.plugin.DefaultPluginManager.loadPluginDescriptor(DefaultPluginManager.java:1642)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.verifyPlugin(DefaultLifecycleExecutor.java:1540)
    … 15 more
    [INFO] ————————————————————————
    [INFO] Total time: < 1 second
    [INFO] Finished at: Tue Feb 09 18:49:51 GMT-03:00 2010
    [INFO] Final Memory: 1M/15M
    [INFO] ————————————————————————

  14. Mert says:

    Hi Victor,

    the embedded-glasfish plugin is somehow removed from central maven repository (see http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-embedded-glassfish-plugin). So in order to make it work you have to add plugin repository that contains the plugin, could be this: http://download.java.net/maven/glassfish. Also define the org.glassfish:maven-embedded-glassfish-plugin:3.0 in the build section of the pom.xml.

  15. Praveen says:

    Mert,

    Thanks for the help, now I am able to successfully bring the Hello World page.

    -Praveen.

  16. Praveen says:

    Victor,

    Try running
    mvn package embedded-glassfish:run

    command from the wallfriend folder, it fails try second time.

    -Praveen.

  17. codebrain says:

    Hi thanks for a great tutorial. I was trying to deploy and debug from Eclipse Galileo. I have installed the Glassfish server, and the server plugin for eclipse, and m2eclipse plugin. I can import the project; but don’t see any run on server. Any help, pointer will be greatly appreciated.

  18. James Barrow says:

    Hi,

    Today [2010/03/30] I had the error below, where [m2repo] is my local Maven repository location:

    org.apache.maven.BuildFailureException: Compilation failure
    error: error reading [m2repo]\org\primefaces\primefaces\2.0.0\primefaces-2.0.0.jar; error in opening zip file

    Had to install the JAR manually by downloading it from the repository then manually installing it into my local repository.

    Cheers,

    James

  19. James Barrow says:

    My web app takes an extremely long time to start up, related to [https://glassfish.dev.java.net/issues/show_bug.cgi?id=11516] where the offline files aren’t being used

  20. [...] Getting Started with Java EE 6 A nice essay that demonstrates how easy it is to make a Java EE 6 application integrating PrimeFaces. [...]

  21. Johnny says:

    Victor, Praveen’s solution is the easy way to fix it. I somehow forgot to change to the project folder, and running mvn outside the project folder gives you that error.

  22. Sebastian says:

    Is there any way to start the GlassFish administrator console using this archetype ? There is nothing in the 4848… thanks

Leave a Reply

© 2012 OpenLogic, Inc. | Licensing | Privacy Policy | Terms of Use

Bad Behavior has blocked 2290 access attempts in the last 7 days.