Digital Java EE 7 Web Application Development

By Peter Pilgrim
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    Digital Java EE 7
About this book

Digital Java EE 7 presents you with an opportunity to master writing great enterprise web software using the Java EE 7 platform with the modern approach to digital service standards.

You will first learn about the lifecycle and phases of JavaServer Faces, become completely proficient with different validation models and schemes, and then find out exactly how to apply AJAX validations and requests. Next, you will touch base with JSF in order to understand how relevant CDI scopes work. Later, you’ll discover how to add finesse and pizzazz to your digital work in order to improve the design of your e-commerce application. Finally, you will deep dive into AngularJS development in order to keep pace with other popular choices, such as Backbone and Ember JS.

By the end of this thorough guide, you’ll have polished your skills on the Digital Java EE 7 platform and be able to creat exiting web application.

Publication date:
September 2015
Publisher
Packt
Pages
486
ISBN
9781782176640

 

Chapter 1. Digital Java EE 7

 

"Nobody is madder than me about the fact that the website isn't working"

 
 --President Barack Obama, 21st October 2013 in a Rose Garden speech

Digital adaptation is a sign of the times for the software developers who are involved with contemporary web design. The phrase Digital Transformation is yet another buzzword pandered around by business executives. Enterprise Java developers do not have to be afraid of this new digital world, because we are involved in building the most exciting software on this planet. We are building software for users, customers, and people. Replace the word Digital with User Experience and you will instantly get what all the fuss is about.

So let's remove the marketing terms once and for all. Digital transformation takes a non-online business process and produces the equivalent online version. Of course, a ponderous ugly caterpillar does not suddenly morph into a beautiful Red Admiral butterfly overnight, without life experience and genetics. It takes the considerable skills of developers, designers, and architects to adapt, transform, and apply the business requirements to technology. In recent times, the software profession has recognized the validity of users and their experiences. Essentially, we have matured.

This book is about developers who can mature and want to mature. These are the developers who can embrace Java technologies and are sympathetic to the relevant web technologies.

In this chapter, we will start our developer's journey with the requirements of the web developer, engineers at the so-called front-end, and the digital and creative industry. We will survey the enterprise Java platform and ask the question, where does Java fit in? We will look at the growth of JavaScript. We will learn about the Java EE 7 modern web architecture. To conclude, we will finish with a simple JavaServer Faces example.

 

Working in the digital domain


Working in a digital domain requires the business to move beyond legacy and institutionalized thinking. It is no longer acceptable to slap together some HTML, a few links to press releases, and some white papers, bundle together some poorly written JavaScript code, and call it your web site. That strategy was suitable, once upon a time. Nowadays, private and public corporations, and even the government, plan web technology for the long-tail in business by focusing on high usability and content (https://en.wikipedia.org/wiki/Long_tail). If your web technology is hard to use, then you will not make any money and no citizen will use your online service.

 

Digital Java developer requirements


As a digital developer, you definitely need powerful development machines, capable of running several of the applications simultaneously. You need to be strong and assertive, and insist on your experience being the best that can be. You are responsible for your own learning. A digital developer should not be hamstrung with a laptop that is fit for the sales and marketing division.

Your workhorse must be able to physically handle the demands for every single tool in the following list:

Items

Explanation

Java SE 8 (or, at least, Java SE 7)

Java SE 8 was released on March 18th, 2014 and it provides Lambdas, where functions are first class citizens. Java 7 is an acceptable alternative for the short term and for a cautious business IT director.

Java EE 7

GlassFish 4.1 application server is the reference implementation for Java EE 7, but there is a lack of professional support. Alternatively, the IT directors may consider Red Hat JBoss WildFly 9 that does have Service Level Agreements.

Integrated Development Environment

IDE like IntelliJ IDEA 14, Eclipse Kepler 4.3, or NetBeans 8

Adobe Creative Suite

Adobe Photoshop CC (and sometimes Adobe Illustrator) are the de facto graphics work inside the creative digital media industry.

Cucumber or Selenium

Cucumber is a behavior-driven development for testing the features of a web application. It is written against Ruby programming and thus, requires that environment and the tool chain.

A suite of modern web browsers

Mozilla Firefox, Google Chrome, and Internet Explorer 10 and the de facto web browsers that support HTML5 and the latest W3C standard. Required Windows 10 recently launched with Edge.

Developer plug-in for web browsers

It really helps to have a JavaScript debugger, HTML, and a CSS element inspector in your tool set. Plug-ins such as Chrome developer tool ease digital engineering.

Text editor

A lightweight text editor to handle small-scale work is often very useful for editing the JavaScript, Puppet (or Chef) scripts, as well as HTML and CSS files.

By just examining this table of software, it is no wonder that the average business-supplied company laptop is so ill-equipped to handle this development.

Tip

Digital engineers are smart, professional engineers

I personally have a 2012 MacBook Pro Retina edition with 16 GB of RAM, 512 GB static hard disk drive as my main machine. Some of my clients have supplied me with badly configured machines. One particular client in finance gave me a Dell Latitude with only 4 GB RAM, running Windows 7 Professional. This developer machine was so poor in performance that I had to complain many times. Inform the decision makers in your business that digital workers need adequate development machines, fit for the purpose of engineering and designing great user experiences.

Let's switch from creativity and design to the Java platform.

 

Java in the picture


The Java platform is in widespread use today. It was the first commercial language featuring JVM and byte-code with garbage collection, sandbox security, and networking capability to be adopted by business. Java's greatest strength is that businesses trust this platform to power enterprise applications in server-side computing. Since 1995, this strength in depth has grown to such a level that the platform is seen as very mature and mainstream. The disadvantage of being part of the main herd is that innovation takes a while to happen; as the steward of the platform, earlier Sun Microsystems and now Oracle Corporation, always guarantee backward compatibility and the maintenance of standards through the Java Community Process.

The JVM is the crown jewel of the platform. Java is the mother programming language that runs on the JVM. Other languages such as Scala, Groovy, and Clojure also run the JVM. These alternative JVM languages are popular, because they introduced many functional programming ideas to the mainstream developers. Functional programming primitives such as closures and comprehensions and languages such as Scala demonstrated a pure object-oriented model and mix-ins. These languages benefited from an easy interaction tool called REPL.

Tip

In fact, Java SE 9 will most likely have Read-Evaluate-Print-Loop (REPL). Keep an eye on the progression of the official OpenJDK project Kulla at http://openjdk.java.net/projects/kulla/.

Released in 2014, Java SE 8 features functional interfaces, otherwise known as Lambdas, which bring the benefits of closures and functional blocks to the main JVM language on the platform.

Whatever programming language you choose to develop your next enterprise application, Java or Scala or otherwise, I think you can bet on the JVM being around for a long time, at least for the next decade or so. The PermGen issue finally ended in Java SE 8, because there is no permanent generation in there. Before Java SE 8, PermGen was the source of many memory leaks (slow and steady memory hogs). This was also the dedicated space where the JVM would load classes into a piece of memory such as the Java Runtime (such as java.lang.String, java.lang.System, or java.util.collection.ConcurrentHashMap). However, classes were rarely unloaded or compacted in size, especially during a very long execution of a JVM. If you are running websites 24/7 over a number of days or even weeks at a time with some degree of user interaction, then there is a good chance that your applications (and their application server) could run out of memory (java.lang.OutOfMemoryError: PermGen space). The permanent generation was the storage area reserved for internal representation of Java classes in releases before JDK 8. For long running application servers and JVM processes, it was possible for references to metadata and classes to remain in permanent generation memory even after if WAR/EAR applications were undeployed and uninstalled. In Java SE 8, the reserved allocation of memory for the Java classes is adaptive. The JVM can now gracefully manage its own memory allocations and represents at least 10 percent efficiency improvement as compared to the previous versions.

In Java SE 8, we have a Garbage First Garbage collector known as G1, which is a parallel collector. Java SE 8 also includes new byte codes to improve the efficiency of dynamic languages such as JRuby and Clojure. The InvokeDynamic byte code from JDK 7 and the Method Handle API were particularly instrumented for the Nashorn, an implementation of JavaScript (ECMAScript Edition 6).

Tip

As of April 2015, Oracle stopped releasing updates to Java SE 7 to its public download sites. Please pass on this information to your CTO!

There is no doubt that the Java platform will continually serve digital engineers as a back-end technology. It may even occur to businesses to take advantage of the client-side technology in Java SE 8 that is now delivered with the platform. JavaFX is an interesting solution, but outside the scope of this book.

We should introduce some code now. The following is a Lambda function for Java SE 8:

public interface PaymentIssuer {
  public void allocate( int id );
}

@ApplicationScoped
public class CreditCardTicketTracker() {
  // Rely on CDI product factory to inject the correct type
  @Inject PaymentIssuer issuer;
 
  public void processTickets( List<Ticket> ticketBatch ) {
  final LocalDate dt = LocalDate.now().plusDays(2)
    ticketBatch.stream()
      .filter(
        t -> t.isAvailable()  &&
        t -> t.paymentType == PaymentType.CreditCard &&
        dt.isBefore(DateUtils.asLocalDate(
      t.getConcertDate())))
      .map(t -> t.getAllocation().allocateToTicket(t))
      .forEach(allocation -> issuer.allocate(allocation));
  }
}

If this code looks very strange to you, then you are probably not yet familiar with Lambda expressions. We have a Context and Dependency Injection (CDI) bean, which is application scoped, called CreditCardTicketTracker. It has a method called processTickets() that accepts a list collection of Ticket objects. The exact type of Ticket is unimportant. What is important, however, is the PaymentIssuer type that the CDI injects into a Plain Old Java Object (POJO). The method processTickets() invokes the stream API of the Java SE 8 collection. Essentially, invoking the method parallelStream() causes processing on each element in the Java collection with multiple threads working in a concurrent operation. The Lambda expressions are on the filter(), map(), and the forEach() methods of the updated Collection API.

Moreover, the code reads close enough to written English. Let me now explain the method processTickets(). An outside component is sending batches of concert tickets for processing to our component CreditCardTicketTracker. For each ticket in the batch, we filter only those tickets that are marked as available, which have already been paid for using a credit card, and where the concert date is two or more days after the current date. By the way, we take advantage of java.time.LocalDate, which is new in Java SE 8.

So, very briefly, a Lambda expression is an anonymous method and the syntax follows this format:

( [[Type1] param1 [,  [Type2] param2 ....]] ) -> { 
  /*
   * Do something here and return a result type
   * including void
   */
}

A lambda expression can be parameterless; therefore, the Java compiler can infer that an expression can be substituted for the java.lang.Runnable type. If there are parameters, the compiler can infer the types of the arguments given enough information. Therefore, the Type1 and Type2 declarations are optional. A Lambda must return a single instance of a type or it may be void, which means the curly braces may be left off.

Lambda expressions are concise, timesaving, and allow functions to be passed to the libraries. For more information, consult the excellent Java Tutorial for Java SE 8 on Oracle's website (http://docs.oracle.com/javase/tutorial/java/index.html). As we have seen in the previous example, your application could use the parallel stream facility in the collection to achieve concurrency.

One immediate use of the Lambda expressions is to replace the inner classes that call the managed thread services, javax.enterprise.concurrent.ManagedExecutorService in Java EE 7. We know that Java has multiple-thread support, networking, and security. Let us turn our attention to the client side.

 

The impressive growth of JavaScript


Over the past decade, digital engineers have adopted a healthy respect for JavaScript as a programming language. Despite its many shortcomings, developers have learned to write modular applications that truly exploit the functionality of this programming language, which executes inside web browsers and servers universally. The framework that eventually changed the game was something called jQuery. It was then written by John Resig in order to simplify the client-side scripting of HTML in JavaScript. Released in 2006, it is the most popular framework in the JavaScript library today.

The greatest innovation in jQuery was the selector engine called Sizzle that allowed JavaScript programming to filter out the DOM elements by declarations, allow traversal, and perform algorithm through a type of collection comprehension. It introduced a new direction for JavaScript development.

It is not just jQuery that has been driving JavaScript. In truth, the progress can be tracked back to the re-discovery of AJAX techniques and the emergence of several competing frameworks such Script.aculo.us and Prototype.

The following is an example of a JavaScript code that uses jQuery:

var xenonique = xenonique || {}

xenonique.Main = function($) {
    // Specifies the page marker ID
    var siteNavigationMarker = '#navigationMarker';

    var init = function() {
      $(document).ready( function() {
        $('#scrollToTheTopArrow').click( function() {
        $('html, body').animate({
                scrollTop: 0
            }, 750);          
        })      
      })
    }

    var oPublic = {
       init: init,
        siteNavigationMarker: siteNavigationMarker,
    };

    return oPublic;
}(jQuery);

Please do not worry if you are struggling to understand the preceding code and certainly do not run away from this piece of JavaScript. The code shows the modern idiom of developing JavaScript in a good, reliable, and maintainable way without using global variables. It perfectly illustrates the module technique of keeping the JavaScript variables and function methods inside an enclosing scope. Scope is the most important item to understand in JavaScript programming.

The preceding JavaScript code creates a namespace called xenonique, which exists in its own scope. We make use of the Module Pattern to create a module called Main, which depends on jQuery. There is a method defined called init(), which executes a jQuery selector with an anonymous function. Whenever the user clicks on the HTML element with the ID #scrollToTheArrow, the web page scrolls the top automatically in 750 milliseconds.

The JavaScript module pattern

The critical technique in this code, as elaborated by Douglas Crockford in his seminal book, JavaScript: The Good Parts, is to create a module that acts like a singleton object. The module is invoked by the interpreter immediately because of the parameter argument statement at the end of the declaration, which relies on a jQuery instance.

Let's simplify the module for effect:

var xenonique = xenonique || {}

xenonique.Main = function($) {
    /* ...a */
    return oPublic;
}(jQuery);

The module xenonique.Main in the preceding code is actually a JavaScript closure, which has its own scope. Thus, the module pattern simulates the private and public members and functions. The return value of the closure is an object that defines the publicly accessible properties and methods. In the module, the init() method and the siteNavigationMarker property are publicly accessible to other JavaScript variables. Closure is preserved in the return object with the JavaScript execution context and, therefore, all private and public methods will exist throughout the lifetime of the application.

JavaScript advanced libraries

For some engineers, writing custom JavaScript, even around a jQuery selector, is too detailed and low-level. AngularJS is an example of a JavaScript framework that takes the evolution of client-side programming further along its trajectory. AngularJS notably features two-way data binding of the DOM elements declaratively to each other or to the JavaScript module code. The creators of AngularJS intended to bring the Model-View-Controller (MVC) design pattern and the separation of concerns to web application development, as well as inspire behavior driven-design through a built-in testing framework.

AngularJS (http://angularjs.org/) is one of the highlights of the new modern movement in JavaScript. Whilst there is a JavaScript library being invented every week, it seems, the standouts in the professional development life also include GruntJS, Node.js, RequireJS, and UnderscoreJS.

GruntJS (http://gruntjs.com/) is particularly interesting, as it works like Make in C or C++ and Maven or Gradle in the Java space. Grunt is a JavaScript task management system and it can build applications, execute unit tests, compile Sass and LESS files to CSS, and perform other duties with the resources. It can also invoke utilities that will compress JavaScript using a process called minification, and optimize them into ugly (hard-to-reverse-engineer) files for both speed and some degree of security.

Note

Sass (http://sass-lang.com/) and LESS (http://lesscss.org/) are CSS preprocessors used by designers and developers. These tools transform reusable common-style configurations into specific device and site style sheets.

For a new digital engineer, I think you will, perhaps, find this discussion overwhelming. So I will summarize it in the following table:

JavaScript Item

Description

jQuery

The most important open source JavaScript library for manipulating the DOM and for selecting elements by ID and name. It has a very popular plugin architecture with many products on offer.

http://jquery.org/

jQuery UI

This is a popular plugin that extends the standard jQuery, and adds additional animations, customizable themes, and UI components including a date calendar picker.

http://jqueryui.org/

RequireJS

A dependency management framework of a JavaScript file and modules loader. This framework has the ability to optimize bundles of modules for larger applications, especially through Asynchronous Module Definition API.

http://requirejs.org/

Nashorn

A JavaScript runtime engine built by Oracle and shipped as standard with Java SE 8. Nashorn runs on the JVM, it is open source, and a part of the OpenJDK project.

http://openjdk.java.net/projects/nashorn/

Dojo Toolkit and microkernel architecture

A refactored JavaScript modular framework and toolkit full of widget components. It makes use of AMD for fast download speed and the efficiency of modules to only load what is necessary for the client-side application. Dojo Toolkit has useful graphs and visualization components.

http://dojotoolkit.org/

Ember JS

Ember is a framework for building client-side web applications. It uses JavaScript for invoking the templates to generate page content. Ember is aimed at the mobile developers who want to compete with native applications. The framework makes use of the Handlebars templating library.

http://emberjs.com/

Handlebars JS

Handlebar is a JavaScript templating library for client-side web applications. The templates, on first examination, resemble HTML with the addition of the expressions tokens. Those familiar with AngularJS will see that the expressions are very similar in syntax.

http://www.handlebarsjs.com/

Underscore JS

This is a JavaScript developer library that brings functional programming ideas and constructs into the language through an API. It has over 80 library helpers that include methods like select, map, flatMap, filter, reduce, forEach, and invoke.

http://underscorejs.org/

Backbone JS

A JavaScript Framework that adds a modeling aspect to the client-side applications. It provides models with key-value binding to DOM and custom application events. Models and collections can be saved to the server. Backbone also provides views with declarative data binding. In many ways, this framework is seen as a viable competitor to AngularJS.

http://backbonejs.org/

Angular JS

AngularJS is a JavaScript framework that provides two-way data binding between the DOM elements and custom JavaScript module code. It has a Model-View-Controller architecture and also provides support for custom HTML components through a feature called directives. Angular JS is also strongly supported by the developers who currently work at Google, and therefore, it is a famous JavaScript framework. Its strength lies in single-page web applications and declarative programming.

http://angularjs.org/

As you can see, there are a lot of challenges to face if you happen to work with front-end (interface developer) engineers versed in many of the above technologies. An enterprise Java or server-side engineer has to be aware of other peoples' skill sets. (See the worker roles in Appendix C, Agile Performance – Working inside Digital Teams).

 

Information architecture and user experience


The digital worker is confronted today by multiple inputs and customer design requirements. One of those is the so-called Information Architecture (IA).This is essentially about the static structure of a website, and describes the flow in order to obtain the best customer-user experience. Information architecture models the shared visual and contextual data that a customer can see in a web page, application, and environment.

Most Java engineers might have seen IA diagrams being passed around among the designers and business analysts during business team discussions. It would be an error to simply gloss over or ignore these discussions, which is why a digital developer ought to have some awareness about how, why, and where is the IA applied. It looks a bit like the visualization of a site map. The following is an example of an information architecture diagram for an e-commerce application:

Basic information architecture for fashion store web site

The preceding diagram describes the IA for a potential fashion store web application. It might be considered too simplistic for this book. This diagram, however, is a work in progress for a pitch, a sales meeting in order to win the contract to develop and build the web application. Architecture is based on three components that are vital for the customer: the initial welcome page, the access to the catalogue and product, and content about the corporation. For this particular customer, the diagram reflects their concerns for the featured fashion items, brands, and promotions. The IA will evolve over time through further interactions with the customer. If we win the pitch to develop the fashion store application, potentially, it might be the searchability of the site that requires deeper investigation.

Information architecture helps the designers and developers along with the business stakeholder to understand the structure of the website through a shared language that consolidates the knowledge and purpose of the domain. A website owner and the business can view the IA as a breakdown of the content. They can comprehend how the site is built.

Information architecture can also be about kinesthetic reactions to the content (how someone feels inside). In the future, this would be important for wearable computers, because the user may not be looking at a screen for sensations and notifications. Interactions may be through sound or even through a smell or taste. These modeling techniques and an ability to write in a manner that has an emotional impact are embraced in a new and recent job title: the content strategist.

Writing and building a professional website or enterprise application has grown from its infancy. The developers now must be approachable, adaptable, and sophisticated. Approachable means the ability to work in harmony with others and as a team. Adaptable means being fearless in the face of constant challenges and changes; sophisticated means being able to cope with the stress and handling it gracefully.

Let's move on to understanding the technical aspect of the enterprise Java platform.

 

Java EE 7 architecture


Java EE is an open standard, an enterprise platform, and a specification for applications that execute on a server. For the digital worker, Java EE provides many services for building web applications including Servlets, JavaServer Faces, Facelets, Context and Dependency Injection, Java Message Services, WebSocket, and crucial Java for RESTful services.

Java EE 7 was announced and released in June 2013, and the overreaching theme was better HTML5 support and increased productivity. Currently, it looks like the future Java EE 8 specification might add support for the administrative configuration of services and application aspects through declarative annotations (extension of JSR 220).

Standard platform components and API

Java EE architecture is a container and layer-based architecture. At the crux of the design is an application server and an increasingly cloud-based solution, although this is yet to be standardized in the specification.

In the non-cloud-based Java EE, we can think of Java EE as four separate containers: the first one is the EJB container for life cycle management of Enterprise Java Beans and the second container is the Web container for life cycle management of the Java Servlets and Managed Beans. The third container is called the Application Client container, which manages the lifecycle of the client-side components. Finally, the fourth container is reserved for Java Applets and their life cycles.

Most of the time, digital engineers are concerned about the EJB, web, and the managed CDI bean containers.

Note

If you are interested in a full description of the architecture, please refer to my first book, The Java EE 7 Developer Handbook by Packt Publishing. You can consider it as a sister book to this one.

According to the Java EE 7 specification, there are two official implementation profiles: the full and the web profile. A fully conformant Java EE product such as Glassfish or JBoss WildFly application server implements the full profile, which means it has all containers: EJB, CDI, and web. A server like Apache Tomcat, which builds against the Java EE 7 web profile, implements only the web container. A server like Tom EE that extends the Apache Tomcat implements the web container, and may add extra facilities like CDI, EJB, and even JMS and JAX-RS.

The following diagram illustrates the full profile Java EE 7 architecture as an enterprise solution. The Java EE platform is an abstraction of the hardware, disk storage, networking, and the machine code. Java EE relies on the presence of a Java Virtual Machine for operation. There are versions of JVM that have been ported to hardware chips like Intel, ARM, AMD, Sparc, FreeScale, and others as well as to operating systems including Windows, Mac OS, Linux, Solaris, and even Raspberry Pi.

Therefore, Java and the other alternative languages can execute seamlessly on this chip architecture, and this applies to the enterprise applications. The Java EE provides additional standard API to the standard core Java SE. Let's take a brief look at some of the Java EE features.

Java EE 7 takes advantage of the New Input Output (NIO) feature in the Java SE edition to allow Java Servlets 3.1 to handle asynchronous communication.

JavaServer Faces 2.2 is now enhanced with tighter CDI integration, improved life cycle events, and a new queue control for AJAX requests. For the digital engineer, there is sensible HTML5 support, resource library contracts, faces flows, and stateless views.

An illustration of the Java EE 7 full platform and JSR specifications

Expression Language 3.0 is not truly a new specification, but it is a broken-out specification from Servlets, JavaServer Pages, and JavaServer Faces. Developers can access the expression evaluator and invoke processing on custom expressions like, say, their own custom tag libraries or server-side business logic.

Perhaps, the most important change in Java EE 7 is the strengthening of the CDI in order to improve type-safety and the easier development of CDI extensions. CDI, Interceptors, and Common Annotations improve the type-safe dependency injection and the observation of life cycle events inside the CDI container. These three specifications together ensure that extensions, which address crosscutting concerns and can be applied to any component, can be written. Developers can now write portable CDI extensions to extend the platform in a standard way.

RESTful Services (JAX-RS) has three crucial enhancements: the addition of client-side API to invoke a REST endpoint, asynchronous I/O support for the client and server endpoints, and hypermedia linking.

Bean validation is a constraint validation solution for domain and value object. It now supports method-level validation and also has better integration with the rest of the Java EE platform.

WebSocket API 1.0 is a new specification added to Java EE 7. It allows the Java application to communicate with the HTML5 WebSocket clients.

Java EE 7 continues the theme that was started in the earlier editions of the platform: improvements for ease-of-development and allowing the developers to write POJOs.

 

Xentracker JavaServer Faces


Let's move into the development mode now. We will look at a JSF example that I created for my earlier book. The project is called XenTracker. The code is available at https://github.com/peterpilgrim/javaee7-developer-handbook. The following is the JSF view (xentracker-basic/src/main/webapp/views/index.xhtml):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">

  <ui:composition template="/views/template.xhtml">
    <f:metadata>
      <f:viewParam name="id" value="#{taskListViewController.id}" />
      <f:event type="preRenderView" listener="#{taskListViewController.findProjectById}"/>
    </f:metadata>

    <ui:define name="content">

      <div class="entry-form-area">

        <h1>Task List for Project</h1>

        <p>
          <h:outputText value="Task list for this project:"/>
        </p>

        <h:link styleClass="btn btn-primary" outcome= "createTask.xhtml?id=#{taskListViewController.id}">
        <f:param name="id" value="#{taskListViewController.id}" />
        Create New Task
        </h:link>

        <table class="table table-striped table-bordered" >
          <tr>
            <td>Title:</td>
            <td><strong>
             &#160;#{taskListViewController.project.name}
            </strong></td>
          </tr>
          <tr>
            <td>Headline:</td>
            <td>&#160;
            #{taskListViewController.project.headline}</td>
          </tr>
          <tr>
            <td>Description:</td>
            <td>&#160;
            #{taskListViewController.project.description}</td>
          </tr>
        </table>
        <!-- form table grid see below -->
      </div>
    </ui:define>
  </ui:composition>
</html>

At first glance, this looks like standard HTML5; the specific JSF tags and the Expression Language syntax are not so obvious. The name of the file in the project is called projectTaskList.xhtml, which serves a big clue to the type of view this file represents. This view is actually a JSF Facelet template. The file type refers to an older XHTML standard, as sanctioned by the World Wide Web Consortium (W3C) after the creation of the HTML 4.01 standard. XHTML is the same as HTML4, but restricted by an XML schema and, therefore, is genuinely an XML document.

In order to render any output from JSF, the specification stipulates the provision of a Page Description Language (PDL). It is possible to have more than one type of PDL. The standard PDL is a view called a Facelet view template. The Facelet framework was a separate open source API external to the JCP, but since JSF 2.0 it has been brought into the fold. Facelet templates are designed to be lightweight and work natively with the JSF framework. Facelets have implicit knowledge of the JSF lifecycle and have access to the UI components through expression language, and they provide decorators to standard HTML elements. The Facelets templating solution performs very well in servlet engines. It may eventually feature in its own specification for Java EE 8.

The templating in the preceding example is illustrated by the specific Facelet tags, namely <ui:define> and <ui:composition>. Briefly, the <ui:composition> tag refers to a template view that defines the layout of the page. One can think of this as the master view. The <ui:define> tag defines the actual content, which will be inserted into the template to form the final page output. We will comprehensively tackle JSF and Facelets in later chapters of this book.

By inspecting the opening XML definition at the top of the view definition, we can see a few namespace declarations. The xmlns:ui namespace, as you have already seen, refers to the Facelet extensions. The xmlns:f namespace refers to the core JSF tags and xmlns:h namespace refers to the JSF components that render the HTML elements. You are warned not to expect a complete one-to-one match as you will understand later on. For instance, the <h:outputText> tag simply prints out the content; you can almost think of it as the echo function in PHP.

The really observant among you will see that it is definitely possible to build modern websites with JSF. There is a <div> element in the markup, and yes, as you may have guessed correctly, Bootstrap CSS is definitely being used. It is important to stress that JSF is a server-side templating solution and a view technology.

Look at the following section again:

<h:link styleClass="btn btn-primary" outcome="createTask.xhtml?id=#{taskListViewController.id}">

This is approximately the equivalent to this straight HTML5:

<a style="btn btn-primary" href="JSF_munged_createTask.xhtml?id=jsf_fizz_12345">

In JSF, the syntactic delimiters denote Expressions: #{...}. The expression language is parsed in the JSF runtime during the rendering phase of the lifecycle. We will discuss the life cycle in the following chapters.

The previous view is incomplete, because we are missing the tabular view component. Although HTML tables are frowned upon due to the layout of content of the web pages, tables are still extremely important for their original purpose, that is, to display tabular data.

The following is the missing table view that should be inserted in the correct place:

<h:form>
  <h:dataTable id="projects" value="#{taskListViewController.project.tasks}" styleClass="table table-bordered" var="task">
    <h:column>
      <f:facet name="header">
        <h:outputText value="Task Name" />
        </f:facet>
        <h:outputText value="#{task.name}"/>
    </h:column>
    <h:column>
      <f:facet name="header">
        <h:outputText value="Target Date" />
      </f:facet>
        <h:outputText value="#{task.targetDate}">
          <f:convertDateTime pattern="dd-MMM-yyyy" />
        </h:outputText>
    </h:column>
    <h:column>
      <f:facet name="header">
        <h:outputText value="Completed" />
      </f:facet>
      <h:outputText value="#{task.completed}"/>
    </h:column>
    <h:column>
      <f:facet name="header">
        <h:outputText value="Action" />
      </f:facet>
      <h:link styleClass="btn" outcome="editTask.xhtml?taskId=#{task.id}">
        <f:param name="taskId" value="#{task.id}" />
        <i class="icon-edit"></i>
      </h:link>
      <h:link styleClass="btn" outcome="removeTask.xhtml?taskId=#{task.id}">
        <f:param name="taskId" value="#{task.id}" />
          <i class="icon-trash"></i>
      </h:link>

    </h:column>
  </h:dataTable>
  <hr/>
  <h:commandLink styleClass="btn btn-primary btn-info" immediate="true" action="#{taskListViewController.returnToProjects}">
    Return to Projects</h:commandLink>
</h:form>

The preceding code exemplifies the JSF style of content. The <h:form> tag corresponds to a HTML Form element. The <h:dataTable> tag denotes the table component grid that renders the data from the managed JSF bean. The value attribute denotes the data that is retrieved from a server component named taskListViewController. This controller accesses the list collection of Task objects using the expression language, and translates it to the Java reflection invocation of taskListViewController.getProjects().getTasks(). It is worth noticing once more the Bootstrap CSS in the attribute styleClass="table table-bordered".

The <h:dataTable> JSF component essentially iterates over a Java Collection, array, iterator, or enumerator, sets the current element defined by the attribute var, and processes the content in its body. It builds an HTML table. The <h:column> tag declares the content in each column of the row and <f:facet> tag declares the content specifically to go into the table header rows.

The <h:outputText> tag is also flexible enough to accept another usual tag <f:convertDateTime>, which formats the particular data value into a date time format.

Finally, we have the h:commandLink tag that renders an HTML anchor tag, which behaves like a form submit button. The h:commandLink tag is optionally associated with a backing bean, which in our case is the taskListViewController. Certain components of the JSF HTML tags like h:dataTable and h:commandLink are contained in an h:form tag in order to be processed correctly.

Tip

Bootstrap CSS (http://getbootstrap.com) is a very popular CSS, component, and front-end framework for developing responsive websites. It is particularly suited for mobile by default projects, because it builds against a flexible and fluid grid system. The CSS and JavaScript are easily added to the web application; Bootstrap is genuinely a kick-starter for many projects.

 

Application servers


At the time of writing, there are several popular application servers that are certified as Java EE 7 compliant: GlassFish, WildFly, Payara, Cosminexus, and TMax Jeus 8. The reference implementation for the entire umbrella specification is GlassFish 4.1 (https://glassfish.java.net/). In 2013, I devoted the entire sister book and source code example, Java EE 7 Developer Handbook, to GlassFish, because it was the only server available. GlassFish is built on open source, there is a public issue tracker, many forums on various Java EE topics, and because Oracle supports the host and the repository of the source code, it works out of the box.

In order to be certified as a Java EE 7 application server, the vendor or open source provider must pass the Test Compatibility Kit, which guarantees a certification list of compliance (http://www.oracle.com/technetwork/java/javaee/overview/compatibility-jsp-136984.html). The code written only against Java EE 7 standard APIs must be able to run against a compliant server else the word standard wouldn't hold any meaning. The basic principle of Java: write once run-everywhere, ought be achievable. The fly in the ointment is when the code relies on vendor-specific features that are not part of the standard. It is also worth pointing out that TCK is not free. In fact, I know a very good source of information, who mentioned the cost to be at least $250 K. Therefore, this barrier to entry is beyond the remit of the majority of open source projects or Small & Medium Enterprises (SME), without significant investment from angels or kick-starter funds.

At the beginning of 2014, Oracle announced that it would be removing the commercial support for the GlassFish server. This news had the Java EE community up-in-arms about the future of the application server. Oracle clarified later that there was a roadmap for GlassFish 5, and it was still on the agenda to be the reference implementation for Java EE 8. The database vendor and Java steward instead recommended the avenue of upgrading to Oracle WebLogic for production. In 2014, Oracle released WebLogic 12.1.3 with selected Java EE 7 compliant components.

WildFly 9 (http://wildfly.org/) is the next generation of application servers from Red Hat. The server features a modular architecture based on a new class loader infrastructure in an attempt to avoid the issue of conflicting dependencies between the third party JARs and the infrastructure within the server itself. There are two key benefits to WildFly: the new high performance HTTP server, which is called Undertow (http://undertow.io/) and the reduction of administration ports. The ports are 8080 for web traffic, Servlets, REST, and WebSocket endpoint and 9990 for server administration. With WildFly it is possible to invoke the EJB remote methods through the de facto HTTP port 8080, which adds some interesting possibilities for enterprise applications.

The modular approach in WildFly 9 appears to be suitable for end sites that prefer to have a strict control over the deployment of their enterprise architecture. WildFly has a download option called the core distribution, which allows developers to configure the modules that they require in an application server runtime. The final benefit of WildFly is that it is the first Java EE 7 server that is compatible with Java SE 8 (Lambdas and default interfaces). Only GlassFish 4.1 releases are compatible with Java SE 8.

After the debacle of the professional support for GlassFish, another corporation entered the space. C2B2 Consulting offered an open source adaptation of GlassFish called Payara Server (http://payara.co.uk) with 24/7 production support.

I should quickly mention one other server that is gaining track with the server-side Java community and that is worth keeping an eye on in the near future. The Apache Software Foundation has an open source project called Tom EE (http://tomee.apache.org/). Tom EE (pronounced Tommy) is, essentially, Apache Tomcat 7 with additional extensions, which are already configured, to support JSF, JPA JAX-RS, CDI, and EJB. David Blevins, a popular speaker and an ASF committer, was the founder of the Tom EE project. At the time of writing, Tom EE is only certified against Java EE 6 Web Profile; however, there are plans to add support to Java EE 7. Business stakeholders can obtain commercial and production support for Tom EE through vendors like Tomi Tribe (http://www.tomitribe.com/).

Since GlassFish, WildFly, and Payara are the only application servers certified as Java EE 7-compliant at the time of writing, we will concentrate only on them for the rest of this book. The source code examples work with both these servers. Wherever necessary, we will point out the differences and explain the features appropriately. Let us now continue our journey into the digital web with Java EE 7.

 

Summary


In this chapter, we discussed the role of the digital worker, that is, you, the engineer and how you fit into the new marketing role as a creative person. We looked at the skills and the tool chain set that is certainly expected in the years 2015 and 2016. We covered how the Java platform and JVM fit into this picture.

Being a Digital Java EE 7 worker is more than just developing the server-side Java code; you are expected to understand JavaScript programming at an elementary level. Some of you may already have basic JavaScript knowledge and some others will understand a lot more about programming in the client space. JavaScript, for all its warts and mishaps, is a professional language that deserves respect, and we covered some of the frameworks that you are expected to know. Whilst this book does not teach you JavaScript and is aimed at Java EE development, I recommend that you brush up on your skills apropos module patterns and applying advanced libraries.

In this chapter, we looked at the Java EE 7 architecture and the specifications that are part of the platform. Finally, we pored over the code of a simple JavaServer Faces example. In particular, we inspected a Facelet view code. We noticed that much of the view resembles standard HTML.

In the upcoming chapters, we will delve deeply into the JSF and build a simple Create Retrieve Update Delete (CRUD) example. We will be generating the example in a couple of different ways. As the saying goes, we have to crawl before we can walk, and walk before we can run. Our crawling is over, now let's starting walking.

 

Exercises


In order to aid those in the field of education: students, teachers, and lecturers, questions have been provided at the end of each chapter in the book.

  1. Grab a sheet of paper; outline the core Java EE 7 specifications, which include the Servlets CDI, EJB, JPA, JMS, JAX-RS, and JSF. On a scale of 1-10 (1 being novice and 10 expert) ask yourself how much do you honestly know?

  2. When was the last time you looked at Java EE? If you still think of enterprise development as the term J2EE, then you definitely need to take a look at the book, Java EE Developer Handbook. Make a note of the specifications that you do not know quite so well and plan to learn them.

  3. Test your understanding of the Java EE platform by matching the parts of the specification to a recent web application that you have been involved in. Describe how each specification can provide benefits, including productivity gains.

  4. Now switch to the other side and dissent against Java EE. Some voices in the community are for and some are decidedly against standardization. The detractors say that the standardization process is too slow for a world of need and innovation. What do you think are the potential pitfalls of relying on the Java EE platform? Think of areas beyond software development, such as education, training, hiring, and the wider community. What would be the ideal state of Java where you can do what you like and without responsibility?

  5. You probably already have a favorite website, which you visit regularly, perhaps everyday. Draw or outline the basic (high level) information architecture for it. Chances are that your favorite website has a lot of rich content and has been around for a long time. What changes have you noticed with the information architecture that you know today?

  6. How good is your JavaScript knowledge? On a scale of 1 (beginner) and 10 (expert), how do you rate it as a skill? How does your JavaScript compare against your Java programming?

  7. Did you know that you can examine HTML, CSS, and JavaScript dynamically from a modern web browser with Developer Tools (Chrome Developer Tools https://developer.chrome.com/devtools or Christopher Pederick's Web Developer Tools http://chrispederick.com/work/web-developer/ or similar)? Have you ever learnt to debug JavaScript through these tools? Why not learn to simply add a break point to the code? How about using the inspector to examine the computed CSS?

  8. Using the distributed version control system, Git, to clone the book source code from GitHub (http://github.com/peterpilgrim/digitaljavaee7), and examine the code around the simple JSF example given in this chapter. Download and setup the GlassFish 4.1 (https://glassfish.java.net/) or WildFly 9 (http://wildfly.org/) application servers and get the first examples running.

  9. How good are your image-editing skills in web design (using a commercial application Adobe Photoshop or Firework or Xara Edit)? Do you partake in this activity at work or at home, or do you delegate this effort to another person, like a creative designer? Would it benefit your wider career plans to have better knowledge in this area? Ask yourself, would it make you be a better digital worker?

  10. The digital teams practicing Agile software development tend to work with the stakeholders. It they are lucky, they are in direct contact with the stakeholder. The stakeholder is the customer, a representative of the business end users, to which these teams are delivering software. Have you ever had conversations directly with the stakeholder(s)? What was the outcome of these discussions? How did they go? Did you ever wish to be more involved? Did you ever feel like running away? How could your efforts in these talks have been better, retrospectively? Put yourself in your stakeholder's shoes to understand how he perceives you.

About the Author
  • Peter Pilgrim

    Peter Pilgrim is a professional software developer, designer, and architect. He is an independent contractor living in Milton Keynes, England. Peter is the director and owner of Pilgrim Engineering Architecture Technology Ltd. In the Java community, he is a well-known specialist in the Java Enterprise Edition (Java EE) technology, focused on the server-side and agile digital transformation for blue-chip industry clients and financial services, which include many of London's top-tier investment banks. Peter has had recent real-world experience of working in the GOV.UK project in London by helping his clients to expand their digital by default services to the UK citizens. He, therefore, absorbed experiences from the frontend and backend software development for large consumer bases. Peter is the 91st Oracle Java Champion (February 2007).

    Browse publications by this author
Latest Reviews (7 reviews total)
Le livre aborde les différentes aspects de la plateforme JEE7. Pour moi, le livre est très bien pour quelqu'un qui n'a pas une grande expérience des différentes APIs JEE7.
Digital Java EE 7 Web Application Development
Unlock this book and the full library FREE for 7 days
Start now