David R. Heffelfinger

  Ensode Technology, LLC


JavaServer Faces (JSF) in a Hurry

Need to learn JSF in a hurry? I'm here to help!

Assuming you already have some Java experience, as well as some HTML experience, there is nothing to JSF, you can learn the basics in a few minutes. I also assume that you are familiar with packaging and deploying Java code to an application server such as GlassFish, WildFly, JBoss, Weblogic or Websphere, or to a servlet container such as Tomcat or Jetty.

JSF has evolved over the years, this blog post covers the best practices in JSF 2.0 or newer, specifically, Facelets is used to develop the front end (as opposed to JSP) and CDI Named beans are used to develop the server side code (as opposed to managed beans).

Step 1: Develop Java class(es) that will hold information (the Model in the MVC pattern)

Your Java class will be a Plain Old Java Object (POJO), it will consist of private properties public setters and getters.

package com.ensode.jsfinahurry.model;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

public class Person {

    private String firstName;
    private String lastName;
    private Short age;

    public String getFirstName() {
        return firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;

    public String getLastName() {
        return lastName;

    public void setLastName(String lastName) {
        this.lastName = lastName;

    public Short getAge() {
        return age;

    public void setAge(Short age) {
        this.age = age;


The @Named annotation designates the class as a CDI managed bean, gives it a name, which by default is the class name with its first character switched to lowercase (“person”, in our case). This annotation allows JSF pages to access our Java class.

The @RequestScoped annotation gives our CDI bean a scope of request. If you have developed web applications in Java before you should be familiar with bean scopes by now.

The following table shows the most commonly used scopes for CDI named beans:

 Annotation Scope
 @RequestScoped Request
 @SessionScoped Session
 @ApplicationScoped Application
 @ConversationScoped Conversation
 @FlowScoped Flow
 @Dependent Dependent pseudo scope

The first three should be self-explanatory, the last two (@ConversationScoped and @FlowScoped) are both meant for the bean to live throughout two or more requests, but not last through the whole session. Since we're in a hurry, I can't explain these in detail, but suffice to say that @FlowScoped was introduced in JSF 2.2 as part of Java EE 7 and is the preferred way to achieve this functionality if you are using JSF 2.2 or newer. @Dependent just means that the bean will be created as needed.

Step 2: Develop a controller class

This is the controller in the Model-View-Controller (MVC) design pattern. As far as plumbing, there is not much to do for controllers, just use the @Named annotation and an appropriate annotation.
package com.ensode.jsfinahurry.controller;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

public class PersonController {
    public String processData(){
        //in a real application, we would process user-input here
        //more than likely saving data to a database
        return "confirmation";

Our JSF pages will invoke the processData() method when the user clicks on a button, via a method binding expression (next section). By convention, the next page to render in the browser will match the return value of the invoked method (processData(), in our case). For our example, we will develop a page named confirmation.xhtml (matching the return value of “confirmation”) that will be rendered after our processData() method is invoked.
Step 3: Develop the pages
Now that we have our Java code in place, we need to develop the user interface. JSF pages are developed using Facelets, a JSF specific view technology. Facelets pages are nothing but standard XHTML pages using some JSF specific name pages.
A page used to allow the user to enter person data (to be stored in our Person class) may look like this:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml"
        <title>Enter Person Data</title>
        <h3>Enter Person Data</h3>
        <h:form id=”personForm”>
            <h:panelGrid columns="2">
                <h:outputLabel for="firstName" value="First Name"/>
                <h:inputText id="firstName" label="First Name" value="#{person.firstName}"/>
                <h:outputLabel for="lastName" value="Last Name"/>
                <h:inputText id="lastName" label="Last Name" value="#{person.lastName}"/>
                <h:outputLabel for="age" value="Age"/>
                <h:inputText id="age" label="Age" value="#{person.age}"/>
                <h:commandButton value="Submit" action="#{personController.processData()}"/>

If you know even basic HTML, you should have a pretty good idea of how the above Facelets markup works. Before explaining the markup, notice that most JSF specific tags on the page have an id attribute. This attribute is optional, but it is a good idea to set it, for starters, it allows us to link labels to input fields (explained below), but also, when things don't work as expected it is much easier to identify which tag is causing trouble, as most JSF error messages will display the id of the component (if we don't set it, JSF will assign one, that will be meaningless to us).

The <h:head> and <h:body> tags are drop-in replacements for HTML <head> and <body> tags.
<h:form> is equivalent to the HTML <form> tag, notice that for JSF we don't need to specify the method and action attributes (method will always be “post” and the action will always point to the JSF servlet, which is automatically used when developing with JSF).

The <h:panelGrid> component lays out JSF tags on the page, similar to using a table to lay out HTML tags. Its column attribute specifies how many tags will be placed in each column.
<h:outputLabel> renders an HTML <label> tag, its “for” attribute must match the id attribute of the input component the label is meant for.

<h:inputText> is equivalent to an HTML <input> tag with a type of “text”. A nice thing about JSF is that it automatically converts user-entered values to the appropriate type in the corresponding CDI named bean. The value of the value attribute is what is known as a value binding expression, we can recognize these since they are encapsulated in curly braces and preceded by a hash (i.e. #{..}). Value binding expressions are used to automatically populate the corresponding attribute in a CDI named bean with the user-entered value for the corresponding input text. Remember the @Named annotation? “person” inside each value attribute corresponds to the name of our Person bean. The value after the dot corresponds to the corresponding property in the Person bean. For example,  #{person.firstName} corresponds to the firstName property of the Person bean.

<h:panelGroup> is used to group JSF tags together in a single cell. In our case, all we wanted to do was have an empty cell so that our button would vertically align with the rest of the input fields, so we placed an empty <h:panelGroup> tag at the appropriate location in our <h:panelGrid>.

Finally, <h:commandButton> submits our form, its value attribute sets the label for the button, its action attribute indicates which CDI named bean method to execute when the button is clicked (processData(), in our case). This is what is called a method binding expression. The method must be public, return a String and take no arguments. What we implemented here is what is referred to as dynamic navigation, although our simple example always returns the same String, there is nothing stopping us from returning different values depending on some conditions, we can then take the user to different pages depending on these conditions (picture a switch statement or if/then/else, with different return values for different conditions).
If we don't need to do any processing after the user clicks the button and we always will display the same page, we can use static navigation, in which case the value of the action attribute can be hardcoded, like this:

<h:commandButton value=”Submit” action=”somepage”/>

We know that the value is hardcoded and not an expression since it is not surrounded by curly braces preceded by a pound sign (“#{...}”). In this case a page named somepage.xhtml would be rendered on the browser every time the user clicks on the button.
The markup for our confirmation page simply displays the values the user entered on the previous page.

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml"
        <title>Confirmation Page</title>
        <h3>You entered the following data</h3>
        <b>First Name:</b> ${person.firstName}<br/>
        <b>Last Name:</b>${person.lastName}<br/>

The only thing new on this page is the use of curly braces preceded by a dollar sign (“${...}”) to retrieve a named bean's properties. When the page is displayed the value of the corresponding property is displayed on the page.

Our application in action

Once we package our application in a WAR file and deploy it to our application server of choice (I'm using GlassFish), our input page will be rendered. Here is what it would look like after a user entered some data:

Notice that we didn't have to specify any mappings in web.xml (as a matter of fact, web.xml is optional in modern JSF applications). By default, JSF pages are mapped to the /faces prefix.
When the user clicks on the Submit button, the processData() method on our PersonController class is executed, which takes us to the confirmation screen.

What I left out

This post is meant as a quick introduction to JSF, so I obviously did not cover every JSF nook and cranny. There are lots of additional JSF tags that I didn't cover, there are JSF specific equivalents to every HTML input tag.

JSF also has input validation built-in, we can make fields required and also accept only specific formats, for example. For application specific cases, we can develop our own custom validators.

JSF has built-in data conversion, we saw this in action by adding a property of type short and having the user-entered value automatically converted to the appropriate type. JSF also allows us to develop custom data converters.

JSF also has Ajax integration built in, a topic that I obviously didn't cover.
Finally, almost nobody develops “raw” JSF applications, the beauty of JSF is that allows the creation of component libraries. Most JSF applications employ one of these component libraries. Some of the most popular include PrimeFaces, RichFaces and IceFaces.

Where to go from here

After reading this short blog post, you should have a pretty good idea of the basic mechanics of JSF. To learn more about it, I'd be very grateful if you purchased one my books, Java EE 7 Development With GlassFish 4 or Java EE 6 Development With NetBeans, or, if you need personalized training, I can help you with that as well, just head over to my company web site: http://www.ensode.com for my contact information.
Of course, there is a ton of free information on the web as well, now that you know the basics other tutorials out there that assume basic knowledge should make more sense, just use your favorite search engine to find out more.

 The source code for the example shown in this post can be downloaded here.


Java Lingo for Non-Java People

This post is meant for managers, business analysts, recruiters, and anyone else who needs to interact with Java developers but is not a Java developer him/herself.
Just like any other discipline, Java development is full with lingo that may be intimidating to those not in the field.

Java itself is a programming language that is platform independent, which means that Java code can run unmodified on a variety of operating systems such as Windows, Linux/Unix, and Mac OS. Traditionally source code needs to be compiled for each specific platform, this is not the case for Java.

The Java Virtual Machine
But Java is not only a programming language, it is also a platform. Java code runs on the Java Virtual Machine (JVM), which translates Java bytecode (compiled Java code) into native code for each platform. There are several other languages that run in the JVM, such as JRuby, Clojure, Groovy, Ceylon and many others.

Eclipse, NetBeans, IDEA
Java applications are typically developed using an Integrated Development Environment (IDE), the three most popular IDEs are Eclipse, NetBeans and IntelliJ IDEA.

ANT, Maven, Gradle
Java applications also typically use a build tool to help compile, build and deploy applications, the three most popular build tools are ANT, Maven and Gradle.

Java EE, JEE, J2EE
Java is extremely popular for developing enterprise server side applications, these types of applications typically use a web based user interface, with the business logic running on a server. Java Enterprise Edition (Java EE) is a set of Application Programming Interfaces (APIs) used to develop server side applications. Sometimes Java EE is referred to as JEE, however the officially sanctioned name is Java EE and the use of the term JEE is discouraged by Oracle, the company behind the Java platform (Oracle bought Sun Microsystems, the original company behind Java, back in 2010). Java EE was formerly known as J2EE, the J2EE term was so popular that it is still commonly used to refer to Java EE.

The Spring framework is an alternate set of APIs used to develop server side applications. In general, server side Java developers belong to either the Java EE or Spring camps, rare is the developer that is a fan of both.

GlassFish, Weblogic, Websphere, JBoss, Tomcat, etc
Server side Java applications are deployed to an application server. Application servers provide functionality that is common to all enterprise applications so that application developers don't have to concern themselves with implementing this functionality. For example, application servers take care of transaction management, security and scalability. Some examples of application servers include GlassFish, JBoss, WildFly, Weblogic and Websphere. Tomcat can be thought of as an application server as well, however strictly speaking, it is a servlet container, that is, it provides less functionality out of the box than full fledged application servers. Java applications written using Spring typically don't require a full fledged application server and can be deployed to Tomcat. Another popular servlet container is Jetty.

JSF, Struts, GWT, Etc
There are several Java web frameworks that are used to ease and accelerate the development of web based applications. JavaServer Faces (JSF) is the standard Java EE framework for web development. There are several JSF component libraries that run on top of JSF, these libraries make it easy to develop nice looking JSF based web applications. Some examples of these libraries include PrimeFaces, RichFaces and IceFaces. In addition to JSF, there are several other Java web frameworks such as Struts (considered by many to be a legacy framework), the Google Web Toolkit (GWT), Struts Web MVC and Wicket.

On the server side, Enterprise JavaBeans (EJBs) provide transactions, security and scalability out of the box. This frees Java developer from having to implement this functionality and allows them to focus on implementing the business logic.

JPA, Hibernate, MyBatis
There are Java APIs (Application Programming Interfaces) that help developers write code to interact with a database, the Java Persistence API (JPA) is the standard Java EE API used for this purpose. Hibernate and MyBatis (formerly known as iBatis) are two other popular libraries used for this purpose.

So there you have it, my friend, after reading this post you'll have some idea of what the heck those Java guys are talking about or what it is that is needed for that Java developer position your company is hiring for.

Anything I missed? Leave a comment.


Why is it so hard to find Java talent?

One common complaint that I hear from my clients and recruiter friends is that it is very hard to find good Java talent.

I am fortunate enough to be on the other side of the coin, I have been working with Java for several years now, I have authored several books on Java and have been a speaker at Oracle's JavaOne conference on more than one occasion, so I'd like to think I'm one of those hard to find good Java developers.

Being on the other side of the coin, I am bombarded every day with emails from recruiters interested in my services, I am fortunate enough to be able to be selective about the projects I work with. In my experience there are three things that drive me away from accepting a project. Here are my suggestions on things you can do to attract top Java talent.

Make it easy to apply

It is mind boggling to me the number of companies that require me to go fill out some long, convoluted form just so that I can apply for a job with them. I have several other companies that are dying to hire me, don't make it a hassle for me to apply for a job for you. On a similar note, many companies require me to fill out some form made in Word that duplicates all the information that already exists in my resume.

If you want me to work for you, don't make it a hassle for me to apply.

Be flexible with your tax terms

For quite a few years now, I've been an independent consultant, in order to do this, I had to incorporate, hire a payroll service, and get insurance for my business. I already have an infrastructure in place to run my business, therefore I only take Corp-to-Corp (C2C) contracts. A lot of companies do W2 only, or want a permanent employee only. Again, I have several potential clients that want to hire me and agree to my terms, your chances of hiring me are slim to none if you are unwilling or unable to do a C2C contract.

Your project has to be interesting

I'm not going to pull any punches here, a lot of the Java projects out there just suck, plain and simple. If what you want me to do is maintain an old J2EE application using Struts 1 and Spring 1 or 2, I'm not going to be very interested in your project. You need to modernize your infrastructure if you want to attract top Java talent. I have actually researched the topic on modernizing legacy server side Java web applications, and wrote a series of articles for the Oracle Technology Network (OTN) a while back on the topic. The articles focus on Spring to Java EE migration, but the same concepts apply to J2EE to Java EE migration. If you need help modernizing a legacy project, drop me a note, this will certainly be an interesting project and I'll be happy to help.


Trying to keep an open mind in the Spring Vs Java EE Debacle

One common criticism of my Spring to Java EE Migration article series (see part 1, part 2, part 3 and part 4) is that the article uses an old version of Spring against a modern version of Java EE. There's a reason for that, since project using older versions of Spring are the most likely ones to be looking to migrate to a newer technology stack, be it a newer version of the Spring Framework, Java EE or something else.

Nevertheless, truth be told, I've been focusing on Java EE projects for the last few years, and the times I've used Spring have been when maintaining legacy applications that don't use modern versions of the Spring framework.

Trying to keep an open mind, I bought Just Spring by Madhusudhan Konda for my Kindle Fire. The book uses Spring 3.0, versus Spring 2.5 in my article series. I decided to go for this book since it is a quick read (just over 60 pages), I didn't want to have to go through a 300+ behemoth of a book just to see if my opinion of Spring was outdated.

Quite frankly, the book did little to change my opinion in the Java EE vs Spring debacle. Although annotations get a brief mention in Konda's book, most of the examples still use XML configuration, and the seemingly endless XML needed to do anything nontrivial in Spring is one of the main reasons I'm not a fan of the framework.


To learn more about Java EE development, please check out my own books, Java EE 6 with GlassFish 3 Application Server and  Java EE 6 Development with NetBeans 7.



Spring to Java EE Migration Article, Part 4

The fourth and final part of my Spring to Java EE migration article series has been published.

Spring to Java EE Migration, Part 4 

Part 4 compares equivalent functionality in Java EE and Spring, covering topics such as MVC design pattern implementation, data access, transaction management, and dependency injection. 


Spring to Java EE Migration, Part 2

Part 2 of my Spring to Java EE migration series has been published. 

This part of the article shows off NetBeans Java EE capabilities, such as automatically generating JSF pages, JSF managed beans and Data Access Objects (DAO's) implemented as EJB session Beans. 


James Gosling, Father of Java, Leaves Google

A while back, there were news all over the blogosphere about James
Gosling, father of Java, leaving Oracle shortly after the database giant
bought Sun Microsystems.

Gosling was unemployed for a while, but in March 2011, he went to work for Google. Today he published a new blog entry, announcing that he left Google to join a company called Liquid Robotics, a company that makes an unmanned ocean vehicle called the Wave Glider.

surprised that Mr. Gosling decided to leave Google after less than six
months of employment; nevertheless I wish him the best of luck in his
new endeavors. I'm sure Liquid Robotics will benefit greatly from the
positive public relations of having the father of Java join their
company, and I'm sure they are hoping his tenure will be longer than the
one he had at Google.


Reports of Java's Demise Have Been Greatly Exaggerated

It seems like every other day a new article or blog post comes out declaring Java as a dead language. Every time I read one of these articles, I scratch my head in confusion. Are these people serious? If Java is so dead then why is there so much demand for it?

What does it mean for a language to be dead anyway? Is it that there is no demand for programmers with expertise in the language? If this is the case, then Java is definitely not dead since I routinely get emails out of the blue from companies looking for Java developers. I have been doing contract work since the late 1990's, and I move from one project to the next with ease, in most cases I have several offers before my current project is over. Therefore in this sense, Java is not dead.

Is a programming language dead if it's not evolving? If that's the case Java is certainly not dead.  JDK 7 is just around the corner, and there are so many Java libraries out there, which release new versions periodically. Java is still very much evolving and improving, therefore in this sense Java is definitely not dead.

I can't think of any other reason why a programming language may be considered "dead", other than lack of demand for expertise or lack of evolution, therefore I'm pretty certain that Java is very much alive and well.

Perhaps the bloggers and reporters declaring Java's demise are actually doing us Java developers a favor, the less Java developers out there, the less competition for Java projects, which would in turn increase the demand (and billing rate) of us Java programmers. Keep stating that Java is dead folks, me, my colleagues (and our bank accounts) will thank you.


Maven pom.xml configuration for Servlet 3.0

Good old servlets are getting a facelift in the next major version of Java EE after been somewhat neglected for so long.

One of the major changes of the new Servlet 3.0 API is that a web.xml is no longer required. Instead, servlets can be configured directly in the source code via annotations.

I wanted to try out this new feature, deploying in GlassFish 3 preview, which is the only Java EE 6 compliant application server at the moment.

As usual, I created a Maven project to test out this functionality, unfortunately, nobody has told Maven that a web.xml is no longer required. My build was failing with Maven complaining about the lack of a web.xml.

After some research, I found out how to configure Maven to avoid it complaining about this non issue.

Here is my pom.xml in it's entirety.

<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

Notice that I'm using the Maven war plugin version 2.1 (in beta at the moment), since previous versions of the plugin (like the default 2.0) do not support the <failOnMissingWebXml> tag yet.


JasperReports 3.5 For Java Developers Published

I'm proud to announce that the second edition of my JasperReports book, JasperReports 3.5 for Java Developers has been published.

The book has been updated to cover the latest features added to JasperReports since the first edition was published. Here is the table of contents:

Chapter 1: An Overview of JasperReports
Chapter 2: Adding Reporting Capabilities to our Java Applications
Chapter 3: Creating your First Report
Chapter 4: Creating Dynamic Reports from Databases
Chapter 5: Working with Other Datasources
Chapter 6: Report Layout and Design
Chapter 7: Adding Charts and Graphics to Reports
Chapter 8: Other JasperReports Features
Chapter 9: Exporting to Other Formats
Chapter 10: Graphical Report Design with iReport
Chapter 11: Integrating JasperReports with Other Frameworks

The full table of contents can be found here.

I also added JPA integration as part of the chapter on JasperReports integration with other frameworks.

An article based on the book can be found at the Packt Publishing web site, it covers the most common use for JasperReports, which is generating reports from database data.

Also, chapter 10, Graphical Report Design with iReport, is available for free, no registration required.


Java DB / Apache Derby: Insecure By Default

Both JDK 1.6 and GlassFish come bundled with Java DB, which is nothing but a rebranded Apache Derby RDBMS. If you have ever done anything with Derby, you know that a database can be created by simply by passing the create attribute with a value of true. For example, to create a database on a server called myserver.com, all that is needed is to use the following JDBC URL:


The above JDBC URL will create a database called "mydb", and, in Derby/Java DB, the default schema matches the user name, so the above URL will create a schema called "foo" and set it as the default schema.

This is great in the sense that creating a database is very easy, but it is not so great in the sense that it allows anybody to create a database on the server and do whatever they want with it.

If this wasn't bad enough, by default passwords are ignored, therefore, with the default configuration in place, anybody can connect to the database as user "foo", for example, the following JDBC URL would connect you just fine:


Notice that in this second JDBC URL, the password is different than the one we used when we created the database, it doesn't matter, in the default Derby configuration, the password is ignored, it is as if it didn't exist, therefore this URL would allow us to log in just fine.

Standalone Derby / Java DB only listens for connections from localhost, so in this case the default behavior is not too bad (there is still some security risk in a server with multiple users, however random people cannot connect through the network and create databases/log in to a database willy nilly).

However, GlassFish comes bundled with Java DB/Derby. When starting the database through GlassFish's asadmin utility:

asadmin start-database

The database by default listens accepts network connections. Unfortunately all other (lack of) security defaults stay in place, therefore with GlassFish's JavaDB's default configuration, random Joe's out there can connect to our databases without using a password, and can also create their own databases. This is a major security hole.

Luckily, Java DB/Derby can be easily configured to require valid user credentials, it is unfortunate that it is not configured this way by default. There are various ways to configure authentication in Derby/Java DB, it can be "hooked up" to an LDAP server, additionally, custom code can be written to handle authentication, and finally, a property file can be written set up authentication. The Derby Developer's Guide has all the details, in this entry, I'll just explain the simplest way, in case you are panicking because I just made you realized your database is exposed to the world.

The property file to create to enable authentication has to be called derby.properties it should look something like this:


# Users definition

derby.connection.requireAuthentication=true tells Derby/Java DB that authentication is required.

derby.authentication.provider=BUILTIN sets up Derby to use its internal, built-in authentication mechanism.

After setting the above two properties, we need to add some users, they are added as shown in the above sample derby.properties file, properties preceeded by "derby.user." are understood to be users, the user name is the string immediately following "derby.user.", and the password is the value to the right of the equal sign. For example, if we wanted to add another user with a username of "joe", and a password of "secret", we would add the following line to derby.properties:


Once we have created this file, we need to put it in $DERBY_HOME/bin if we are using the standalone Java DB/Derby or the Java DB version that is bundled with JDK 1.6. Java DB is placed under $JAVA_HOME/db in in Linux and under C:\Program Files\Sun\JavaDB in Windows.

If we are using the Java DB version that is included with GlassFish, then the derby.properties file needs to be placed under $GLASSFISH_HOME/databases, where $GLASSFISH_HOME is the directory where GlassFish is installed.

After copying the file to the appropriate location, the Java DB/Derby needs to be restarted for the changes to take effect.


A Slightly Biased Comparison Between Wicket and JSF

Recently I will start working on a project using Wicket. I used Wicket briefly in the past, I wrote an article about it and even worked as a technical reviewer for a book on Wicket, but I have never used it in production systems.

On the other hand, I have written two books that cover JSF, I also teach a class that covers JSF development, and I have worked on some projects that use JSF in production. As the author of two books that cover JSF, I have a vested interest in having JSF remain popular, therefore I am obviously somewhat biased, however I'll try to be as objective as possible when making this comparison.

All of my Wicket experience happened a few years ago, I haven't used it much in about three years, so for the past few days I've been refamiliarizing myself with this framework.

When comparing Wicket with plain vanilla JSF wicket is the clear winner. The fact that the markup in Wicket is plain HTML (with special wicket specific attributes) makes Wicket much more accessible, since no special knowledge of Wicket components is needed to come up with the markup. This allows web designers to do what they do best, design their user interfaces with their preferred tools such as Dreamweaver or other web design tools. The changes to the markup to make it work with Wicket are minimal, the wicket specific attributes need to be added to HTML tags that will be replaced at runtime with Wicket components. However, very few people use "vanilla" JSF. Most JSF developers use a component library such as ICEFaces or RichFaces. Furthermore, Facelets is a very popular view technology that can also use standard XHTML to develop JSF views. When component libraries and Facelets enter the picture, picking a winner is not so easy.

The fact that Wicket uses standard HTML for its markup may be an advantage or a disadvantage depending on your situation. If you are working with a professional web designer, then having straight HTML as markup is a real advantage. However, if your team consists primary of Java developers with little or no web design skills, then using a JSF component library that renders its pages using predefined CSS and Javascript, then in this case JSF may have the advantage.

Wicket reminds me a lot of working with Facelets, when using Facelets, we can develop pages that are plain XHTML, however we are not prohibited from using JSF specific tags. When previewing a Facelets page in the browser, the JSF specific tags are simply ignored.

Wicket also has some Wicket specific tags, however they are used to ignore parts of the HTML when it is rendered in the browser and other functionality, they are not really meant to be rendered. On the other hand, HTML tags in Wicket can have an wicket id corresponding to a component that renders HTML on the page, for example, a <span> tag could map to a custom Wicket component, therefore, a Wicket page may not preview exactly like it will be rendered when the application is deployed, which is the case with Facelets as well.

My impression on which one is better is, like in most cases, it depends. If a professional web designer is available, then Wicket may be the better choice, however if most of the development team are backend Java developers, then using JSF with Facelets plus a component library such as IceFaces or RichFaces may be a better choice.


Confessions of a Java Snob

For the past couple of months I've been working on porting a PHP application to Java EE using JSF, JPA and EJB 3 (in case you are wondering, yes, I've been using NetBeans and GlassFish).

I've never had any real exposure to PHP, so this is a new experience for me. I'm not sure if what I'm seeing is typical PHP code, but comparing this legacy system to the typical enterprise Java system shows some striking differences in architecture. When analyzing the PHP code, it became obvious to me that the mindset of PHP developers is very different from your typical Java developer.

In the Java world, we love our design patterns, we can't live without our DAO's and MVC. In PHP, it seems to be no big deal to mix presentation, business logic and data access in a single file.

Having worked with Java for over 13 years and Java EE/J2EE for about 10 years, I have to confess that the architecture (if you can call it that, more like "lack of architecture") seemed appalling to me. In the enterprise Java world, we've been conditioned to think that separation of concerns is a good thing.

Our presentation logic should contain presentation only, that way if in the future we want to switch say, from straight JSPs and servlets to JSF, the rest of the code shouldn't be affected. Additionally, if we want to convert our web application to a desktop application using Swing, it should be fairly straightforward to do so.

Data access logic should be done via Data Access Objects (DAO's), that way if today we are using straight JDBC and tomorrow we want to use an object relational mapping tool such as JPA or Hibernate, all we need to do is change the data access layer, the rest of the code should not be affected.

Communication between layers in our applications should be done via Value Objects, which shouldn't really change if we change our data access layer or presentation layer.

Controllers should manage flow from one page to another, again these should only be rewritten if we change our presentation layer. Most Java web application frameworks provide their own controllers, however they are not self sufficient, for example, in Struts we need to use Actions and in JSF we need to write managed beans, therefore changing the presentation layer would usually involve changing the controller as well.

After analyzing the code for the legacy system I got the impression that PHP is a language for amateurs and Java/J2EE/Java EE is for professional software engineers and architects. Am I right? Or I am just a Java snob? Feel free to set me straight.


Solving JasperReports Dependencies with Ivy

Lately, I've been doing some work with JasperReports. On my previous JasperReports projects, I've either used Maven, which automatically takes care of resolving dependencies, or I have simply downloaded the project's dependencies by hand.

Using Maven is nice, since it resolves dependencies, however, JasperReports comes with a series of useful ANT tasks to compile reports, preview them etc. I wanted access to these tasks and I also wanted dependency management.

There were a couple of ways I could achieve both. I know ANT targets can be called from Maven, this could be one approach. Also, there is a dependency manager for ANT called Ivy. I had briefly used Ivy before, I thought I would try this approach.

Ivy works by adding a series of custom ANT tasks, installing Ivy is very simple, all that needs to be done is to copy the Ivy jar file to ${ANT_HOME}/lib. Once Ivy is installed, custom Ivy tasks are available in our ANT build files.

Some additional configuration needs to be done in an Ivy specific XML file, named ivy.xml. In this file is where we actually specify our dependencies.

I set up my project to depend on JasperReports and tried to have Ivy automatically download all of JasperReports dependencies, unfortunately the build failed, complaining about some missing dependencies, specifically mondrian and commons-javaflow.

[ivy:retrieve] 		::::::::::::::::::::::::::::::::::::::::::::::
[ivy:retrieve] :: UNRESOLVED DEPENDENCIES ::
[ivy:retrieve] ::::::::::::::::::::::::::::::::::::::::::::::
[ivy:retrieve] :: commons-javaflow#commons-javaflow;20060411: not found
[ivy:retrieve] :: mondrian#mondrian; not found
[ivy:retrieve] ::::::::::::::::::::::::::::::::::::::::::::::

After some googling, some head scratching (and some hair pulling and banging on the table for good measure), I found out what was going on.

JasperReports has some optional dependencies declared in its pom.xml, these dependencies are not downloaded by default when using Maven, however Ivy attempts to download them. For some reason these dependencies do not exist in the repository, because of this the ANT build fails.

After some research, I found out the necessary modifications to ivy.xml to make the build succeed:

<ivy-module version="2.0">
    <info organisation="ensode" module="mymodule"/>  
        <dependency org="jasperreports" name="jasperreports" rev="3.1.2" conf="*->default"/>

What I had to do was to  use the conf attribute of the <dependency> tag to specify that I wanted that configuration for this particular dependency. The *-> default means that all your module configurations depend on the 'default' configuration of JasperReports, as explained by Xavier Hanin in this message of the Ivy users mailing list.

After making this change, Ivy was able to successfully download all JasperReports dependencies.

[ivy:retrieve]     commons-beanutils#commons-beanutils;1.8.0 by [commons-beanutils#commons-beanutils;1.7.0] in [runtime]
    |                  |            modules            ||   artifacts   |
    |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
    |      runtime     |   14  |   12  |   12  |   2   ||   11  |   11  |

I figured I would document this procedure in case others are having similar issues.


Common JPA Questions

  1. How can I have a composite primary key in JPA?

    There are several ways to do it, this page explains them.

  2. How can I prevent users from overwriting each other's changes to the database?

    Use the @Version annotation.

  3. Is there a way to do bulk updates and/or deletes with the Java Persistence Query Language (JPQL)?



« April 2014

© David R. Heffelfinger