Your First Cup: An Introduction to the Java EE Platform

Coding the Example Application

This section describes how to code the example application.

Getting Started

Before you start coding the example, you need to perform some configuration tasks:

  1. Register the server with your NetBeans IDE as described in Configuring Your Environment.

  2. Create a directory for the example you will build.

ProcedureCreate a Directory for the Example

  1. Create another directory at the same level as the tut-install/example directory, where tut-install is the location of the firstcup tutorial installation, and call it myexample. You'll create the applications described in this tutorial in this directory.

Creating the Web Service

The DukesAgeResource endpoint is a simple RESTful web service. REST stands for representational state transfer, and software architectures that conform to the principles of REST are referred to as RESTful. RESTful web services are web-based applications that use the HTTP protocol to access, modify, or delete information contained within a resource. A RESTful web service resource is a source of specific information identifiable by a uniform resource identifier (URI), for example http://example.com/someResource, and may be manipulated by calling the HTTP protocol's methods, for example GET or POST.

RESTful web services are often contrasted to SOAP web services (for example web services created with the JAX-WS API that is part of Java EE 6). Compared to SOAP web services, RESTful web services are simpler, as they use HTTP directly rather than as a transport mechanism for an underlying XML document format, and typically offer better performance.

Web services are designed to be independent of their clients. Typically RESTful web services are publicly available to a wide variety of clients, and the clients are located throughout the internet. This is called “loose coupling,” as the clients and servers are connected only by the standard HTTP-based requests and responses, and do not need to know each other's implementation details. For this reason, DukesAge will be developed in its own application module, and deployed separately from the DukesBirthdayBean enterprise bean and firstcup web client. DukesAge could be deployed on a completely different machine without affecting the functionality of the firstcup web client.

JAX-RS Resources

DukesAgeResource is a JAX-RS resource class that responds to HTTP GET requests and returns a String representing the age of Duke at the time of the request.

To create DukesAgeResource, use the wizard provided by the JAX-RS plug-in for NetBeans IDE to generate the resource class. This class is annotated with the javax.ws.rs.Path annotation, which specifies the URL suffix to which the resource will respond. DukesAgeResource has a single method, getText, annotated with the javax.ws.rs.GET and javax.ws.rs.Produces annotations. @GET marks the method as a responder to HTTP GET requests, and @Produces specifies the MIME-type of the response sent back from getText to clients. In this case, the MIME-type is text/plain.

Creating the Endpoint

In NetBeans IDE, create a web project with a source file called DukesAgeResource.java in the firstcup.webservice package using the RESTful Web Service wizard.

ProcedureCreate the Project in NetBeans

  1. Select File -> New Project.

  2. Select Java Web in the Categories pane.

  3. Select Web Application in the Projects pane.

  4. Click Next.

  5. Set Project Name to dukes-age.

  6. Set the Project Location to tut-install/myexample.

  7. Click Next.

  8. Select your GlassFish Server instance from the Server menu.

  9. Select Java EE 6 Web from the Java EE Version menu.

  10. Set the Context Path to /DukesAgeService

  11. Click Finish.

    You should now see the module you created in the Projects pane.

  12. From the Projects pane, right-click on the index.jsp file and select Delete. Click Yes in the dialog.

ProcedureCreate the DukesAgeResource Class

  1. Make sure dukes-age is selected in the Project menu.

  2. Select File -> New File.

  3. Select Web Services in the Categories pane.

  4. Select RESTful Web Services From Patterns in the File Types pane.

  5. Click Next.

  6. Under Select Pattern select Singleton and click Next.

  7. Set Resource Package to firstcup.webservice.

  8. Under Path enter dukesAge.

  9. Under Class Name enter DukesAgeResource.

  10. Under MIME Type select text/plain.

  11. Click Finish.

    You should now see the DukesAgeResource.java file inside the firstcup.webservice package in the Projects pane. The DukesAgeResource.java file should also be open in the editor pane.

ProcedureConfigure the dukes-age Web Application

By default, NetBeans IDE bundles the JAX-RS 1.0 JARs with web applications that use JAX-RS 1.0. GlassFish Server already has the JAX-RS 1.0 JARs in the server classpath, so there is no need to separately include the JARs.

The default URL that is brought up in a web browser when you run dukes-age can also be configured in NetBeans IDE.

  1. Right-click on dukes-age in the Projects tab and select Properties.

  2. Click Libraries.

  3. Uncheck the boxes under Compile-time Libraries for restlib-gfv3ee6.

  4. Click Run.

  5. Set Relative URL to /resources/dukesAge.

  6. Click OK.

ProcedureRemove the putText Method

The DukesAgeResource JAX-RS resource doesn't respond to HTTP PUT requests. Delete the generated putText method in DukesAgeResource.

  1. Highlight the following generated Javadoc and method definition and delete it.

    /**
     * PUT method for updating or creating an instance of DukesAgeResource
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("text/plain")
    public void putText(String content) {
    }

ProcedureImplement the getText Method

Add code to DukesAgeResource.getText that calculates Duke's age at the time of the request. To do this, use the java.util.Calendar and java.util.GregorianCalendar classes to create an object representing the date May 23, 1995, Duke's birthday. Then create another Calendar object representing today's date, and subtract today's year from Duke's birth year. If today's date falls before May 23, subtract a year from this result. Then return the result as a String representation.

  1. Highlight the current code in getText and replace it with the following code:

    // Create a new Calendar for Duke's birthday
    Calendar dukesBirthday = new GregorianCalendar(1995, Calendar.MAY, 23);
    // Create a new Calendar for today
    Calendar now = GregorialCalendar.getInstance();
    
    // Subtract today's year from Duke's birth year, 1995
    int dukesAge = now.get(Calendar.YEAR) - dukesBirthday.get(Calendar.YEAR);
    dukesBirthday.add(Calendar.YEAR, dukesAge);
    
    // If today's date is before May 23, subtract a year from Duke's age
    if (now.before(dukesBirthday)) {
    	dukesAge--;
    }
    // Return a String representation of Duke's age
    return new String("" + dukesAge);
  2. Right-click in the editor window and select Format.

  3. Right-click in the Editor and select Fix Imports.

  4. Select File -> Save from the menu to save the file.

Building and Deploying the Web Service

Build the JAX-RS web application and deploy it to your GlassFish Server instance.

ProcedureBuilding and Deploying the Web Service Endpoint

Compile, package, and deploy dukes-age.war to GlassFish Server. This task gives instructions on deploying dukes-age.war in NetBeans IDE.

  1. Select dukes-age in the Projects tab.

  2. Right-click dukes-age and select Run.

    After dukes-age.war deploys successfully to GlassFish Server a web browser will load the URL of the DukesAgeResource path, and you'll see the returned String representing Duke's age.


Example 3–1 Output of DukesAgeResource

Here's an example of the output of DukesAgeResource displayed in a web browser.


14

Creating the firstcup Project

The firstcup web application project consists of the Java Persistence API entity, the enterprise bean, and the JavaServer Faces web front-end.

ProcedureCreate the Web Application Project

Follow these steps to create a new web application project in NetBeans IDE.

  1. Select File -> New Project.

  2. Under Categories select Java Web, then under Projects select Web Application, and click Next.

  3. Set the Project Name to firstcup.

  4. Set the Project Location to tut-install/myexample, where tut-install is the location of the firstcup tutorial installation.

  5. Click Next.

  6. Select your GlassFish Server instance from the Server menu.

  7. Select Java EE 6 from the Java EE Version menu.

  8. Set Context Path to /firstcup and click Next.

  9. Under Frameworks select JavaServer Faces.

  10. Click the Configuration Tab, then under Servlet URL Pattern enter /firstcupWeb/* and click Finish.

Creating the Java Persistence API Entity

The Java Persistence API allows you to create and use Java programming language classes that represent data in a database table. A Java Persistence API entity is a lightweight, persistent Java programming language object that represents data in a data store. Entities can be created, modified, and removed from the data store by calling the operations of the Java Persistence API entity manager. Entities, or the data encapsulated by the persistent fields or properties of a entity, can be queried using the Java Persistence Query Language (JPQL), a language similar to SQL that operates on entities.

In firstcup, there is a single entity that defines one query.

ProcedureCreating the FirstcupUser Entity Class

The FirstcupUser Java Persistence API entity represents a particular firstcup user, and stores the user's birthday and the difference in age between the user and Duke. FirstcupUser also defines a Java Persistence API query used to calculate the average age difference of all users.

  1. With the firstcup project selected in the Projects pane, select File -> New File.

  2. Under Categories select Persistence, then under File Types select Entity Class, and click Next.

  3. Enter FirstcupUser under Class Name and firstcup.entity under Package.

  4. Click Create Persistence Unit, select jdbc/__default under Data Source, and click Create.

  5. Click Finish.

ProcedureAdd Properties to the FirstcupUser Entity

Create the FirstcupUser entity's two properties: birthday, of type java.util.Calendar; and ageDifference, of type int.

The birthday property must be annotated with the javax.persistence.Temporal annotation to mark the property as date field in the underlying database table. All persistent fields or properties of type java.util.Calendar or java.util.Date must be annotated with @Temporal.

  1. Right-click the editor window, select Insert Code, then Add Property.

  2. In the Add Property dialog, enter birthday under Name, java.util.Calendar under Type, and click OK.

  3. Click the error glyph next to the new birthday field and select Add @Temporal Annotation.

  4. Right-click the editor window, select Insert Code, then Add Property.

  5. In the Add Property dialog, enter ageDifference under Name, int under Type, and click OK.

ProcedureAdd a Named Query to the FirstcupUser Entity

Add a JPQL named query to the FirstcupUser entity that returns the mean average age difference of all firstcup users.

This query uses the AVG aggregate function to return the mean average of all the values of the ageDifference property of the FirstcupUser entities.

  1. Directly before the class definition, paste in the following code:

    @NamedQuery(name="findAverageAgeDifferenceOfAllFirstcupUsers",
    query="SELECT AVG(u.ageDifference) FROM FirstcupUser u)

    The @NamedQuery annotation appears just before the class definition of the entity, and has two required attributes: name, with the unique name for this query; and query, the JPQL query definition.

ProcedureAdd a Business Method to DukesBirthdayBean that Gets the Average Age Difference of firstcup Users

Once the FirstcupUser entity is complete, add a business method to the DukesBirthdayBean session bean to call the named query that returns the average age difference of all users.

  1. Double-click DukesBirthdayBean in the Projects Pane under Enterprise Beans.

  2. Below the class definition, add a @PersistenceContext annotation and field of type EntityManager:

    @PersistenceContext
    private EntityManager em;
  3. Right-click in the Editor window, select Insert Code, then Add Business Method.

  4. In the Add Business Method dialog, enter getAverageAgeDifference under Name, set the Return Type to Double, and click OK.

  5. Replace the body of the newly created getAverageAgeDifference method with the following code:

    public Double getAverageAgeDifference() {
        Double avgAgeDiff = (Double) 
            em.createNamedQuery("findAverageAgeDifferenceOfAllFirstcupUsers")
            .getSingleResult();
        logger.info("Average age difference is: " + avgAgeDiff);
        return avgAgeDiff; 
    }

    The named query in FirstcupUser is called by using the EntityManager's createNamedQuery method. Because this query returns a single number, the getSingleResult method is called on the returned Query object. The query returns a Double.

  6. Select File -> Save.

Creating the Enterprise Bean

DukesBirthdayBean is a stateless session bean. Stateless session beans are enterprise beans that do not maintain a conversational state with a client. With stateless session beans the client makes isolated requests that do not depend on any previous state or requests. If an application requires conversational state, use stateful session beans.

To create DukesBirthdayBean create one Java class: DukesBirthdayBean, the enterprise bean class. DukesBirthdayBean is a local enterprise bean that uses a no-interface view, meaning two things. First, a local enterprise bean is only visible within the application in which it is deployed. Second, enterprise beans with a no-interface view do not need a separate business interface that the enterprise bean class implements. The enterprise bean class is the only coding artifact needed to create a local, no-interface enterprise bean.

DukesBirthdayBean will be packaged within the same WAR file as the Facelets web front-end.

Creating DukesBirthdayBean in NetBeans IDE

This section has instructions for creating the web application project and the DukesBirthdayBean enterprise bean.

ProcedureCreating the DukesBirthdayBean Enterprise Bean Class

Follow these steps to create the enterprise bean class in NetBeans IDE.

  1. Select firstcup project in the Projects tab.

  2. Select File -> New File.

  3. Select Java EE in the Categories pane.

  4. Select Session Bean in the File Types pane and click Next.

  5. Set EJB Name to DukesBirthdayBean.

  6. Set the Package name to firstcup.ejb.

  7. Select Stateless under Session Type.

  8. Click Finish.

ProcedureModify DukesBirthdayBean.java

Add a java.util.Logger instance and a business method that calculates the difference in age in years between Duke and the user, and creates a new FirstcupUser entity.

  1. Directly after the class declaration, paste in the following code:

    private static Logger logger = 
    		Logger.getLogger("firstcup.ejb.DukesBirthdayBean");

    This code creates a logger for the session bean.

  2. Right-click in the editor window and select Insert Code, then Add Business Method.

  3. Set the name to getAgeDifference and the return type to int.

  4. Under Parameters click Add, set the Name to date and the Type to java.util.Date, then click OK.

  5. Replace the body of the getAgeDifference method with the following code:

    	int ageDifference;
    
    	Calendar theirBirthday = new GregorianCalendar();
    	Calendar dukesBirthday = new GregorianCalendar(1995, Calendar.MAY, 23);
    
    	// Set the Calendar object to the passed in Date
    	theirBirthday.setTime(date);
    
    	// Subtract the user's age from Duke's age
    	ageDifference = dukesBirthday.get(Calendar.YEAR) - 
    	theirBirthday.get(Calendar.YEAR);
    	logger.info("Raw ageDifference is: " + ageDifference);
    	// Check to see if Duke's birthday occurs before the user's. If so, 
    	// subtract one from the age difference
    	if (dukesBirthday.before(theirBirthday) && (ageDifference > 0)) {
    		ageDifference--;
    	}
    
    	// create and store the user's birthday in the database
    	FirstcupUser user = new FirstcupUser(date, ageDifference);
    	em.persist(user);
    
    	logger.info("Final ageDifference is: " + ageDifference);
    
    	return ageDifference;

    This method creates the Calendar objects used to calculate the difference in age between the user and Duke and performs the actual calculation of the difference in age.

    Similar to the DukesAgeResource.getText code, getAgeDifference subtracts Duke's birthday year from the user's birthday year to get a raw age difference. If Duke's birthday falls before the users, and the raw difference is more than 0, subtract one year from the age difference.

    A new FirstcupUser entity is created with the user's birthday and age difference, then stored in the JavaDBTM database by calling the EntityManager's persist method.

    The final age difference is returned as an int.

  6. Right-click in the editor window and select Format.

  7. Right-click in the editor window and select Fix Imports.

  8. Choose the java.util.logging.Logger fully-qualified name for the Logger class.

  9. Click OK.

  10. Select File -> Save.

Creating the Web Client

To create the web client, you need to perform the following tasks:

Creating a Resource Bundle

In this section, we'll create the resource bundle that contains the static text and error messages used by the Facelets pages. The firstcup client supports both English and Spanish locales. Therefore we need to create two properties files, each of which will contain the messages for one of the locales.

ProcedureCreating a Resource Bundle

  1. Right-click firstcup in the Projects pane.

  2. Select New -> Other from the popup menu.

  3. Select the Other category, then Properties File from the New File dialog and click Next.

  4. In the New Properties File dialog, enter WebMessages in the File Name field.

  5. In the Folder field, enter src/java/firstcup/web as the location of the file.

  6. Click Finish.

  7. After NetBeans IDE creates the properties file, enter the following messages or copy them from here to the file:


    Welcome=Hi. My name is Duke. Let us find out who is older -- You or me. 
    DukeIs=Duke is
    YearsOldToday=years old today.
    Instructions=Enter your birthday and click submit.
    YourBD=Your birthday
    Pattern=MM/dd/yyyy
    DateError=Please enter the date in the form MM/dd/yyyy.
    YouAre=You are 
    Year=year
    Years=years
    Older=older than Duke!
    Younger=younger than Duke!
    SameAge= the same age as Duke!
    Submit=Submit
    Back=Back
    AverageAge=The average age difference of all First Cup users is

    These messages will be referenced from the XHTML pages.

  8. Save the file by selecting File -> Save from the menu.

  9. To add the Spanish translations of the messages, copy the properties file WebMessages_es.properties from tut-install/firstcup/example/firstcup/src/java/com/sun/firstcup/web to tut-install/firstcup/myexample/firstcup/src/java/firstcup/web.

    You can create multiple properties files, each with a set of messages for a different locale. By storing localized static text and messages in resource bundles, you don't need to create a separate set of XHTML pages for each locale.

Configuring the Resource Bundle in the Configuration File

To make the resource bundle available to the application, you need to configure it in the configuration file, by performing the following task.

ProcedureCreating a Configuration File

The faces-config.xml deployment descriptor contains configuration settings for the JavaServer Faces application. JSF applications don't require a deployment descriptor unless they use features that can only be configured in faces-config.xml. In firstcup, the deployment descriptor has settings defining the resource bundle that provides localized strings in English and Spanish.

  1. Select firstcup in the Projects Pane and select File -> New File.

  2. In the New File dialog, select JavaServer Faces under Categories, new JavaServer Face Configuration under File Types, click Next, then Finish.

ProcedureConfiguring the Resource Bundle

The firstcup application is localized for English and Spanish languages. JavaServer Faces applications can automatically select the proper language based on the locale of the user's web browser. Specify the default and supported locales in the faces-config.xml file.

  1. With the newly created faces-config.xml file open, click XML.

  2. Add the following <application> tag to configure the resource bundle:


    <application>
    	<resource-bundle>
    		<base-name>firstcup.web.WebMessages</base-name>
    		<var>bundle</var>
    	</resource-bundle>
    	<locale-config>
    		<default-locale>en</default-locale>
    		<supported-locale>es</supported-locale>
    	</locale-config>
    </application>

    The base-name element of the resource-bundle element identifies the fully-qualified class name of the resource bundle. The var element identifies the name by which the XHTML pages will reference the resource bundle. The locale-config element identifies the locales supported by the resource bundle.

  3. Right-click in the editor window and select Format.

  4. Select File -> Save.

Creating the DukesBDay Managed Bean Class

The DukesBDay JavaBeans component is a backing bean. A backing bean is a JavaServer Faces managed bean that acts as a temporary data storage for the values of the components included on a particular JavaServer Faces page. A managed bean is a JavaBeans component that a JavaServer Faces application instantiates and stores in scope. The section following this one describes more about managed beans and how to configure them.

This section describes how to create the DukesBDay class. To create the class you need to do the following:

ProcedureCreating the Managed Bean Class.

Create a JavaServer Faces managed bean class that will subsequently be modified.

  1. Right-click the firstcup.web package in the Projects pane.

  2. Select New -> Other.

  3. Select JavaServer Faces under Categories, then JSF Managed Bean under File Types.

  4. Enter DukesBDay in the Class Name field.

  5. Select firstcup.web in the Package field.

  6. Select session under Scope.

  7. Click Finish.

ProcedureAdding an Enterprise Bean Reference

Add a javax.ejb.EJB annotation to inject a reference to the DukesBirthdayBean enterprise bean. This session bean will be called from the methods in DukesBDay.

  1. Right-click in the editor window and select Call Enterprise Bean.

  2. In the Call Enterprise Bean dialog expand the firstcup application, select DukesBirthdayBean, and click OK. The following field will be added:


    @EJB
    private DukesBirthdayBean dukesBirthdayBean;

ProcedureAdding Properties to the Bean

During this task, you will add the following properties to the DukesBDay bean:

  1. Right-click in the Editor window, select Insert Code, then Add Property.

  2. Enter age under Name, and set the Type to int, click OK.

  3. Repeat the above steps to create the following properties: yourBD of type java.util.Date, ageDiff of type int, absAgeDiff of type int, and averageAgeDifference of type Double.

  4. After the newly created property fields, add the following Logger instance:


    private static Logger logger = Logger.getLogger("firstcup.web.DukesBDay");
  5. Initialize the variables in the default constructor:


    public DukesBDay() {
    	age = -1;
    	yourBD = null;
    	ageDiff = -1;
    	absAgeDiff = -1;
    }
  6. Right-click in the editor and select Format.

  7. Right-click in the editor and select Fix Imports.

  8. Select java.util.logging.Logger for the Logger class, and click OK.

ProcedureGetting Duke's Current Age

While performing this task, you will add some code to the getAge method to access Duke's current age from the JAX-RS web service.

Use the java.net and java.io classes to create an HTTP connection to the Duke's Age web service and read in the result.

  1. Add the following code to the getAge method.

    public int getAge() {
        // Use the java.net.* APIs to access the Duke's Age RESTful web service
        HttpURLConnection connection = null;
        BufferedReader rd = null;
        StringBuilder sb = null;
        String line = null;
        URL serverAddress = null;
    
        try {
            serverAddress = new URL(
    				"http://localhost:8080/DukesAgeService/resources/dukesAge");
            connection = (HttpURLConnection) serverAddress.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setReadTimeout(10000);
    
            // Make the connection to Duke's Age
            connection.connect();
    
            // Read in the response
            rd = new BufferedReader(
    				new InputStreamReader(connection.getInputStream()));
            sb = new StringBuilder();
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
    
            // Convert the response to an int
            age = Integer.parseInt(sb.toString());
        } catch (MalformedURLException e) {
            logger.warning("A MalformedURLException occurred.");
            e.printStackTrace();
        } catch (ProtocolException e) {
            logger.warning("A ProtocolException occurred.");
            e.printStackTrace();
        } catch (IOException e) {
            logger.warning("An IOException occurred");
            e.printStackTrace();
        }
    
    	return age;
    }
  2. Right-click in the editor window and select Format.

  3. Right-click in the editor window and select Fix Imports.

  4. Click OK.

ProcedureGetting the Age Difference From the DukesBirthdayBean Enterprise Bean

During this task, you will create a processBirthday method to get the difference in age between the user's age and Duke's age from the EJB, set the absAgeDiff variable to the absolute value of the age difference, and set a result string that is will forward the user to the display page..

  1. Add a processBirthday method with the following code:

        public String processBirthday() {
            this.setAgeDiff(dukesBirthday.getAgeDifference(yourBD));
            logger.info("age diff from dukesbday " + ageDiff);
            this.setAbsAgeDiff(Math.abs(this.getAgeDiff()));
            logger.info("absAgeDiff " + absAgeDiff);
            return new String("success");
        }

    This method calls the getAgeDifference method of DukesBirthdayBean to get the age difference and store it in the ageDiff property, sets the absolute age difference stored in the absAgeDiff property, and returns a status code of success. This status code will be used by the JavaServer Faces runtime to forward the user to the appropriate page.

  2. Right-click in the editor window and select Format.

  3. Select File -> Save.

Creating the Facelets Client

The Facelets client consists of a resource library, a composite component, and two XHTML files.

Resource Libraries in firstcup

A JavaServer Faces resource library is a collection of user-created components collected in a standard location in a web application. Resource libraries are identified according to a resource identifier, a string that represents a particular resource within a web application. Resources can be packaged either at the root of the web application or on the web application's classpath.

A resource packaged in the web application root must be in a subdirectory of a resources directory at the web application root.

resources/resource identifier

A resource packaged in the web application classpath must be in a subdirectory of the META-INF/resources directory within a web application.

META-INF/resources/resource identifier

Resource identifiers are unique strings that conform to the following format:

[localePrefix/][libraryName/][libraryVersion/]resource name[/resourceVersion]

Elements of the resource identifier in brackets ([]) are optional. A resource name, identifying a particular resource (a file or a graphic, for example), is required. In firstcup, a resource library with the name components is packaged in the web application root, and this library contains one resource, a file called inputDate.xhtml. The resource identifier for this resource is therefore components/inputDate.xhtml, and it is located in the web application root at resources/components/inputDate.xhtml.

The inputDate Composite Component

A composite component is a set of user-defined JavaServerFaces and Facelets components located in a resource. In firstcup, the inputDate.xhtml resource, located in the components resource library is a composite component that contains tags for reading in a date the user enters in a form. Composite components consist of an interface definition and an implementation.

The interface definition is specified with the <composite:interface> tag to define which attributes are exposed to pages that use the composite component. Attributes are identified with the <composite:attribute> tag.


Example 3–2 inputDate Composite Component Interface Definition

The inputDate.xhtml interface definition is as follows. It defines a single attribute, date, that must be specified in pages that use the inputDate composite component.

<composite:interface>
    <composite:attribute name="date" required="true" />
</composite:interface>

The implementation of the composite component is specified with the <composite:implementation> tag. The tags within the <composite:implementation> are the actual component tags that will be added to pages that use the composite component. They can be any HTML Render Kit, JavaServer Faces, or Facelets tags. The #{cc.attrs.attribute name} expression is used to get the value of the specified attribute from the page or component that is using the composite component.


Example 3–3 The inputDate Composite Component Implementation

The implementation of the inputDate composite component is as follows. An HTML input text component will store the entered text into the date attribute, accessed by the #{cc.attrs.date} expression. A JavaServer Faces convertDateTime component will convert the entered text to a date with the form of MM/dd/yyyy (04/13/2009, for example).

<composite:implementation>
    <h:inputText value="#{cc.attrs.date}">
        <f:convertDateTime pattern="MM/dd/yyyy" />
    </h:inputText>
</composite:implementation>

ProcedureCreating the inputDate Composite Component

Create the inputDate composite component as a resource in the components resource library.

  1. In the firstcup project, select File -> New File.

  2. Select JavaServer Faces under Categories, JSF Composite Component under File Types, and click Next.

  3. In the New JSF Composite Component dialog, enter inputDate under File Name, components under Folder, and click Finish.

  4. Add the composite component interface definition between the <body> and </body> tags in inputDate.xhtml:

    	<composite:interface>
    		<composite:attribute name="date" required="true" />
    	</composite:interface>
  5. Add the composite component implementation below the interface definition:

    	<composite:implementation>
    		<h:inputText value="#{cc.attrs.date}">
    			<f:convertDateTime pattern="MM/dd/yyyy" />
    		</h:inputText>
    	</composite:implementation>
  6. Right-click in the editor window and select Format.

  7. Select File -> Save.

The Facelets Web Interface

The firstcup web application interface has two XHTML files. The greeting.xhtml file displays Duke's current age and the form to the user for her to enter her birthday. The response.xhtml file displays the age difference between the user and Duke.

The greeting.xhtml contains several pieces of the firstcup application detailed previously. It uses the localized strings contained in WebMessages.properties and WebMessages_es.properties. It uses the DukesBDay managed bean to call both the DukesAgeResource JAX-RS web service and the DukesBirthdayBean enterprise bean. It uses the inputDate composite component to create the input for the user to enter her birthday.


Example 3–4 The greeting.xhtml File

Here's the content of the greeting.xhtml file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
      PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:fc="http://java.sun.com/jsf/composite/components">
<head>
    <title>Firstcup Greeting Page</title>
</head>
<body>
<h:form>
    <h2>
        <h:outputText value="#{bundle.Welcome}"/>
    </h2>
    <h:outputText value="#{bundle.DukeIs} "/>
    <h:outputText value="#{DukesBDay.age} #{bundle.YearsOldToday}"/>
    <p/>
    <h:outputText value="#{bundle.Instructions}"/>
    <p/>
    <h:outputText value="#{bundle.YourBD} "/>
    <fc:inputDate id="userBirthday" date="#{DukesBDay.yourBD}" />
    <h:outputText value=" #{bundle.Pattern}"/>
    <p/>
    <h:commandButton value="#{bundle.Submit}" action="response"/>
    <p/>
    <h:message for="userBirthday" style="color:red"/>
</h:form>
</body>
</html>

The greeting.xhtml file uses the JSF Core, HTML Render Kit, and the components resource library tag libraries. The components tag library has a prefix of fc, and is used to specify the inputDate composite component in the form below. The <fc:inputDate id="userBirthday" date="#{DukesBDay.yourBD}" /> tag has the required date attribute, and stores the value in the yourBD property in the DukesBDay managed bean by using the EL expression #{DukesBDay.yourBD}.

The localized strings are referred to by using the EL expressions #{bundle.property name}. For example, the <h:outputText value="#{bundle.Welcome}"/> tag will display the following string in English locales:


Hi. I'm Duke. Let's find out who's older -- You or I.

The <h:commandButton value="#{bundle.Submit}" action="response"/> tag creates a submit button and specifies that a successful submission should render the response.xhtml file by setting the action attribute to response. The action attribute is used to define navigation rules for forms in Facelets pages.

If the form submission is unsuccessful, a warning message is displayed. This is done with the <h:message for="userBirthday" style="color:red"/> tag, which is connected to the inputDate composite component with the id userBirthday. That is, if there's an error with the input of the inputDate component, a warning message is displayed.


The response.xhtml displays the age difference between the user and Duke. Different strings are displayed based on whether the user is the same age, younger, or older than duke. The text can be displayed or not based on the conditions specified by the rendered attribute of the <h:outputText> tag. The conditions used in the rendered attribute are EL language alternatives to the Java programming language conditional operators to allow XML parsing of the XHTML file.

Table 3–1 Conditional Operator EL Language Alternatives

Logical Condition 

Java Programming Language Conditional Operator 

EL Language Alternative 

AND 

&&

&&

EQUALS 

==

==

LESS THAN 

<

lt

GREATER THAN 

>

gt


Example 3–5 The response.xhtml File

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
      PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
<head>
    <title>Response Page</title>
</head>
<body>
<h:form>
    <h:outputText value="#{bundle.YouAre} "/>
    <h:outputText value="#{bundle.SameAge}"
                  rendered="#{DukesBDay.ageDiff == 0}"/>
    <h:outputText value="#{DukesBDay.absAgeDiff}"
                  rendered="#{DukesBDay.ageDiff lt 0}"/>
    <h:outputText value=" #{bundle.Year} "
                  rendered="#{DukesBDay.ageDiff == -1}"/>
    <h:outputText value=" #{bundle.Years} "
                  rendered="#{DukesBDay.ageDiff lt -1}"/>
    <h:outputText value="#{bundle.Younger}"
                  rendered="#{DukesBDay.ageDiff lt 0}"/>
    <h:outputText value="#{DukesBDay.absAgeDiff}"
                  rendered="#{DukesBDay.ageDiff gt 0}"/>
    <h:outputText value=" #{bundle.Year} "
                  rendered="#{DukesBDay.ageDiff == 1}"/>
    <h:outputText value=" #{bundle.Years} "
                  rendered="#{DukesBDay.ageDiff gt 1}"/>
    <h:outputText value="#{bundle.Older}" rendered="#{DukesBDay.ageDiff gt 0}"/>    <p/>
    <h:commandButton id="back" value="#{bundle.Back}" action="greeting"/>
</h:form>
</body>
</html>

For example, the #{bundle.SameAge} string is displayed if the user and Duke have the same birthday as specified by the condition #{DukesBDay.ageDiff == 0} in the rendered attribute. That is, display the following string if the ageDiff property of DukesBDay equals 0:


You are the same age as Duke!

The form also contains a <h:commandButton> tag that creates a back button that will direct the user back to the greeting.xhtml page, as specified in the action attribute.

ProcedureCreating the XHTML Files

Create the Facelets XHTML files in NetBeans IDE.

  1. In the firstcup project select Web Pages in the left pane in NetBeans IDE.

  2. Select File -> New File.

  3. Select Java Server Faces under Categories, New JSF Page under File Types, and click Next.

  4. Enter greeting under File Name and click Finish.

  5. Repeat the previous steps to create a new Facelets Simple File named response.

ProcedureSet the Welcome File in the web.xml Deployment Descriptor

Configure the application to use greeting.xhtml as the welcome file by modifying web.xml

  1. In the firstcup project under Configuration Files double-click web.xml.

  2. Click Pages.

  3. Click Browse under Welcome Files, expand Web Pages, select greeting.xhtml, and click Select File.

  4. Select File -> Save.

ProcedureAdding Tag Libraries to the XHTML Files

Modify greeting.xhtml to include the components tag library.

  1. In the firstcup project open greeting.xhtml by double-clicking the file name under Web Pages in the left pane.

  2. Add the components tag library to the <html> tag.

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
          xmlns:f="http://java.sun.com/jsf/core"
          xmlns:h="http://java.sun.com/jsf/html"
          xmlns:fc="http://java.sun.com/jsf/composite/components">

    The components resource library is referred to by the fc prefix. The JSF Core and HTML Render Kit tag libraries are also used in greeting.xhtml.

  3. Add a title directly after the <html> tag.

    <head>
        <title>Firstcup Greeting Page</title>
    </head>
  4. Select File -> Save.

  5. Open response.xhtml and add the following title:

    <head>
        <title>Response Page</title>
    </head>
  6. Select File -> Save.

ProcedureAdding the Form to greeting.xhtml

Add the form that provides the user interface for displaying Duke's age and entering the user's birthday.

  1. In the firstcup project in greeting.xhtml add the following tags between the <body> and </body> tags.

    <h:form>
        <h2>
            <h:outputText value="#{bundle.Welcome}"/>
        </h2>
        <h:outputText value="#{bundle.DukeIs} "/>
        <h:outputText value="#{DukesBDay.age} #{bundle.YearsOldToday}"/>
        <p/>
        <h:outputText value="#{bundle.Instructions}"/>
        <p/>
        <h:outputText value="#{bundle.YourBD} "/>
        <fc:inputDate id="userBirthday" date="#{DukesBDay.yourBD}" />
        <h:outputText value=" #{bundle.Pattern}"/>
        <p/>
        <h:commandButton value="#{bundle.Submit}" action="#{DukesBDay.processBirthday}"/>
        <p/>
        <h:message for="userBirthday" style="color:red"/>
    </h:form>
  2. Right-click in the editor window and select Format.

  3. Select File -> Save.

ProcedureAdding the Form to response.html

Add a form that displays the age difference between Duke and the user, displays the average age difference of all users, and allows the user to navigate back to greeting.xhtml.

  1. In the firstcup project in response.xhtml add the following tags between the <body> and </body> tags.

    <h:form>
        <h:outputText value="#{bundle.YouAre} "/>
        <h:outputText value="#{bundle.SameAge}"
                      rendered="#{DukesBDay.ageDiff == 0}"/>
        <h:outputText value="#{DukesBDay.absAgeDiff}"
                      rendered="#{DukesBDay.ageDiff lt 0}"/>
        <h:outputText value=" #{bundle.Year} "
                      rendered="#{DukesBDay.ageDiff == -1}"/>
        <h:outputText value=" #{bundle.Years} "
                      rendered="#{DukesBDay.ageDiff lt -1}"/>
        <h:outputText value="#{bundle.Younger}"
                      rendered="#{DukesBDay.ageDiff lt 0}"/>
        <h:outputText value="#{DukesBDay.absAgeDiff}"
                      rendered="#{DukesBDay.ageDiff gt 0}"/>
        <h:outputText value=" #{bundle.Year} "
                      rendered="#{DukesBDay.ageDiff == 1}"/>
        <h:outputText value=" #{bundle.Years} "
                      rendered="#{DukesBDay.ageDiff gt 1}"/>
        <h:outputText value="#{bundle.Older}" rendered="#{DukesBDay.ageDiff gt 0}"/>
        <p/>
        <h:outputText value="#{bundle.AverageAge}": #{DukesBday.averageAgeDifference}" />
        <p/>
        <h:commandButton id="back" value="#{bundle.Back}" action="greeting"/>
    </h:form>
  2. Right-click in the editor window and select Format.

  3. Select File -> Save.

ProcedureSetting the Navigation for firstcup

Add a navigation rule to faces-config.xml that forwards the user to response.xhtml when the returned status of the DukeBDay.processBirthday method is success.

  1. With the firstcup project selected in the Projects pane, expand Configuration File and double-click faces-config.xml.

  2. Click PageFlow in the top left corner of the editor pane to display the visual navigation editor.

  3. Select greeting.xhtml click and hold the navigation arrow box on the far right, and drag a navigation arrow to the response.xhtml file.

  4. Double-click the default case1 outcome associated with the navigation arrow and change it to success.

  5. Select File -> Save.

Building, Packaging, Deploying, and Running the firstcup Web Application

In this section, you will build the firstcup web application, deploy it to the server, and run the application.

ProcedureBuilding and Packaging the firstcup Web Application

While performing this task, you'll build and package the DukesBirthdayBean enterprise bean and the firstcup web client into an WAR file, firstcup.war, in the dist directory.

  1. Select firstcup in the Projects tab.

  2. Right-click firstcup and select Run.

ProcedureRunning the firstcup Application

This section describes how to run the firstcup application.

  1. Launch an internet browser.

  2. Enter the following URL in the address field of the browser:


    http://localhost:8080/firstcup
  3. Enter your birth date in the Your birthday text field. Make sure you use the date pattern specified on the page: MM/dd/yyyy.

  4. Click Submit.

  5. After the response.xhtml page is displayed, click Back to return to the greeting.xhtml page.


Example 3–6 A Successful Response Page for firstcup


You are 20 years older than Duke!
The average age difference of all First Cup users is: 20