Copyright ©May 2008
Russell Bateman and
Etretat Logiciels, LLC

Permission is granted for any derivational use. You are forbidden only to repost the files of the tutorial and project without express permission of the author.

   

Tutorial: Using NetBeans or Eclipse with JDK 6, Apache Tomcat and JavaServer Faces



Introduction

Three weeks ago, failing to complete several JSF tutorials for Eclipse launched me off on a tangent to learn about the deeper internals of JSF and then to Maven, whose promise was that it could set me up a blank but working JSF project that I could then just modify.

Here are my emerging notes for a JSF tutorial. What I learned here is relevant to Eclipse use also. In the end, it's more about learning JSF than Eclipse or NetBeans although tools often get in the way. And, at the present time, I'm spending pretty much all my time in Eclipse as I work through a new book, Essential JSF, Facelets & JBoss Seam.

Bibliography, Tutorials, Source Code and Other, Related Resources

Click here for an exhaustive bibliography and other helps.


I bought the book, Core JavaServer Faces by David Geary and Cay Horstmann. It took me a long time to get it going. I tried and failed over and over again in Eclipse. This is what led me, first to Maven, and then to NetBeans.

The authors waffled on the source code details throwing a great deal of confusion into the process. It wasn't until I carefully waded through the different possibilities and chose one that I got it working. Click here for the details.

I also have the book, JavaServer Faces in Action, by Kito Mann which also has a sample in its first chapter. I haven't finished getting that one going; there's one last problem. I do have most of it working and I learned some crucial, if now trivial, things along the way. Click here for the details.

Now I have to try my own application. Click here for the details.

 

An excellent tutorial I'm going through at present is in the first two chapters of Essential JSF, Facelets & JBoss Seam, by Kent Tong. Those chapters are available to read free of charge here. I, however, purchased the whole book. At this writing, I'm going through it (it's only $19.95 on-line). It seems well-worth the price (if you're as desperate as I). You don't get bogged down in deep explanations, but the instructions seem to work and I've learned more than a couple of things.


Here are some things I've learned that I didn't know and whose absence from my wisdom caused me no end of trouble (probably why I went to NetBeans originally).

  1. The modern url-pattern to use in your web.xml is
    	<url-pattern> /faces/* </url-pattern>
    
    instead of
    	<url-pattern> *.faces </url-pattern>
    
    which you will find in many books. Getting confused between what these older books say and what modern practice is can lead to HTTP errors and frustration. This has a particular effect upon the path typed into the browser address line.
     
  2. When creating a Dynamic Web Project (speaking of the dialog boxes you walk through), change Configurations to say JavaServer Faces v1.2 Project (if you can't or it isn't there, you probably didn't install correctly—see early pages of Chapter 1 in Essential JSF, Facelets & JBoss Seam)
     
  3. In JSF Capabilities, choose JSF RI 1.2 and check Deploy plus make certain to populate the rest of the dialog box thus:
    	/WEB-INF/faces-config.xml
    	Faces Servlet
    	javax.faces.webapp.FaceServlet
    	/faces/*
    
  4. From https://maven-repository.dev.java.net/repository/jstl/jars/, copy file jstl-1.2.jar to your project's WebContent/WEB-INF/lib path. To make Eclipse find it, right-click on the project and choose Refresh.

Notes

Here are some random notes I'll incorporate into something worth reading one day.

How the JSP generates HTML code in two steps

  1. The JSP is translated into as much HTML as is apparent just as when not using JavaServer Faces.
     
  2. The JSP engine reads in the tag libraries specifed between <@ ... >.
     
  3. After this, the HTML code noted in step 1 is put out.
     
  4. When a JSF tag like <f:view> is encountered, a JSF component is created (rather than HTML generated). Text or something else is put into this component which becomes an output component, <h:outputText>. Once the JSF component “tree” is built (the structure is hierarchical just as is XML/HTML), at which time the JSP engine begins seeing normal HTML and puts it out. Beans are invoked as they appear in JSF components and their result is incorporated into the output.

Others...

- In a JSF application, a page is defined by a JSP file and identified by a view id or the relative path to the page from the root (kept as WebContent in Eclipse).

- Each JSP tag belongs to a certain tag library (including the main ones). These libraries are identified by URL. Before you use a tag, you must introduce a prefix or short-hand for the URL and then use it to qualify the tag name.

- When a warning appears in the text portion under the Web Page Editor looking at a JSP, and you've done everything right, save all files, drop Eclipse and relaunch it. If you've done everything right, the warning will sometimes disappear. If not, look harder. One sign is to try to run it anyway; if it works, it probably isn't your fault and bouncing Eclipse may fix the problem.

When you fix a warning or error (or suspect one is already fixed, or just want to see), choose Project -> Clean and clean the current project. If invalid (unless an Eclipse bug), the warning or error should disappear.

- If you're using an external browser to test with, you may need—at very least—to drop the page you're running before running again after some modifications. This is because Eclipse can't clean up and redeploy. I create a new tab, run and then discard the tab every time to make certain I don't have any of the deployed files (principally under WebContent/WEB-INF/lib) still open.

- Over and over again, I learn that web.xml is king and if there's the smallest typo in this file, “FacesServlet” instead of “Faces Servlet”, etc., the worst possible thing will happen, i.e.: an HTTP 404 error or some such thing.

- If web.xml is king, then faces-config.xml is minister of foreign affaires. Anything amiss in this file and the JSF wiring doesn't work and neither does your application.

- The JSF engine goes through the following phases during a form submission:

  1. Restore View
  2. Apply Request Values
  3. Process Validations
  4. Update Domain Values
  5. Invoke Application
  6. Render Response

If there is any error in the Process Validations phase or the Update Domain Values phase, the JSF engine will jump to the Render Response phase directly. Tong addresses this with pretty good detail in chapter 2, especially his StockQuote example.

I intend to go over the preceeding list and define in some detail each phase.

- Managed beans gain access to each other via the <managed-property>. It is important to ensure that the referring bean has a shorter or same lifetime (scope) than the referred so that resources don't disappear from underneath it.

- Definition of “domain” by Kent Tong

A domain class is a Java class that models the logic and/or concepts in the domain. The Request class is one such class.

“Domain” means the logic and concepts surrounding the business operations concerned: e.g.: the postage is $10 per kg, some patrons may have discounts, etc.

In contrast, there are other classes that deal with getting input from the user to displaying output to the user. Such classes are called “UI classes”.

In such an application if later we decide to use a new UI technology (e.g.: one from JSF to some new technology), the domain classes can be reused but the UI ones can't. This is still much better than if a class is involved with both domain logic and UI because then as the UI technology needs to change, the code won't be reusable.

- Never let a session-scoped bean refer to any other managed bean because when the session bean is written out to disk, the other bean won't be (since it's not session-scoped) and when read back in, the reference inside the session bean will be nil. See Essential JSF, Facelets & JBoss Seam, page 135 (chapter 4).

- Information can be hidden on forms in a special hidden JSF HTML tag (<h:inputHidden>).

- A facet is a child component that is subjected to special processing by its parent. In the shop site example (Essential JSF, chapter 4), the data rows of the catalog are facets and contain <h:outputText> tags. The summary on page 160 makes some important points about creating tables whose row data can only be determined at run time.


Notes on run errors I find...

Notes on intermediate errors I find...

...and how I eliminate them. If I don't show these, then I'll always sit mystified in front of them. This way, I check back to remind myself how I solved them. After a while, I'll start remembering. Mostly, however, errors are always due to a misalignment between Java classes, JSF elements in the JSP file and the definitions in faces-config.xml.

Notes on Facelets...

Facelets is a developer friendly enhancement of JavaServer Faces (JSF) eliminating a lot of mucking around in the complicated faces-config.xml file and making the whole process more designer friendly. The latter question is simply that life is very hard for the Dreamweaver-based page and graphics designer when he has to work on JSF pages whose elements (tags) make Dreamweaver choke.

Facelets corrects this problem with templating, re-use and ease of development. JSF is, after all, the platform developers want to use instead of developing to JSP, creating their own tags (that Dreamweaver will choke on anyway) and having to do all the hard work over and over again.

Facelets can use any container; you do not tie yourself to Tomcat, JBoss, or GlassFish, etc. when you code to Facelets.

The components of Facelets include a JAR, jsf-facelets.jar, makes use of the UIComponents in the JavaServer Faces API and a single modification to faces-config.xml:

	<view-handler> com.sun.facelets.FaceletViewHandler </view-handler>

as well as statements in web.xml like:

	<context-param>
	  <param-name>  javax.faces.DEBUG_SUFFIX </param-name>
	  <param-value> .xhtml                   </param-value>
	</context-param>

Facelets use the “EL-API” specification with JSF, meaning that #{ ... } or ${ ... } to reference beans.

You do still create beans for reference in the web page code just as for JSP and JSF, but you don't have to maintain the laborious faces-config.xml for this with the risk of name mismatches between this file, code, JSP files, etc.

Custom components

Facelets lets you set up your own component libraries. This is a little like writing C preprocessor macros to subsume a bunch of lines of code that you don't want to type over and over again.

	<facelet-taglib>
	  <namespace>          http://www.mycompany.com/jsf  </namespace>
	  <tag>
	    <tag-name>         bar                           </tag-name>
	    <component>
	      <component-type> javax.faces.Data              </component-type>
	      <renderer-type>  com.mycompany.Bar             </renderer-type>
	    </component>
	  </tag>
	</facelet-taglib>

You put this kind of definition into a file named like bar.taglib.xml under project-name/JavaSource/META-INF.

The jsfc attribute that can be included with any standard HTML element tag like span, form, etc. makes it so that these tags get handled as server-side components by the Facelets view handler.

An Eclipse DTD Trick

I'm reproducing this here because I fear (with no particular foundation) that the URL might disappear one day. This is by Dan Allen and it very much affects chapter 6 of Essential JSF, Facelets and JBoss Seam. Starting at the top of page 189 is the text to foo.taglib.xml and it needs the document type definition (DTD) referred to in this trick. The solution was dated January 31, 2006. I'm using it in June, 2008 and it appears to stop the little yellow triangle from appearing.

 

Love it or hate it, Eclipse is very insistent on going out to the web to fetch DTDs to validate the active XML file. When it can't find one, it whines, complains and puts an ugly yellow mark on your file, tagging it as a warning condition. Perhaps this is a small itch, but I felt like scratching it, so I have included an equally small solution to the problem.

The problem with DTDs is (and has always been?) that they don't necessarily point to actual internet resources. Authors use DTD URIs as namespaces to keep the elements in one definition totally seperate from ones (perhaps with the same name) in another. In the early days, it was even encouraged that authors just make up any old URL, as long as it was, and would remain to be, unique. Well, maybe Eclipse missed that day in class, so we hack on.

The question remains, where can you find the DTD in a consistent location, from whereever you are? Sure, you can load it into your local catalog, but as soon as you are on another computer, the problem is back. We want a permanent solution. The source code repository, of course! These servers are always available, serve up the files without interference from a website rebranding, and better yet, they are already versioned! Brilliant! Simply use the "download" link from the web-based CVS/SVN tool that points to the DTD file in the source code repository in your DOCTYPE definition at the top of the file (we have to at least assume the author checked it in!). I will leave you with an example:


	<?xml version="1.0"?>
	<!DOCTYPE facelet-taglib PUBLIC
	    "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
	    "https://facelets.dev.java.net/source/browse/*checkout*/facelets/src/etc/facelet-taglib_1_0.dtd">
		

Aaaargh! (the cry of desperate anguish...)

Okay, this is pretty much disasterous confusion; what I've found by doing Chapter 6 all over again a fourth time in a new workspace all alone is...

  1. I was able to make it work up to page 188.
  2. Starting with the section, “Create your own tag,” it would only work in the internal browser; the external browser gave me nothing at all when running as instructed by page 191 and again on page 193 for the exercise, “Hiding JSF tags in[...] HTML tags.”
  3. Viewing the source for the exercise in #2, I note that everything is there, but it just doesn't display in the browser. I didn't actually recognize this until the implied exercise instruction at the bottom of page 194.
  4. For the exercise, “Forbidding direct access to xhtml files,” which failed utterly the first, second and third times in the old workspace, I succeed this time in the external debugger, but, strangely, not in the internal one. I got exactly the illustration at the bottom of page 193. Go figure.
  5. The internal browser wanted to open or save listfaq.xhtml instead of display it (or display nothing as the exercise claims should happen). This is doubtless because the Eclipse browser is similar to Internet Exploder and not to Firefox. (Again, go figure.)
  6. Then, after modifying web.xml and running again as instructed in the middle of page 194, I got exactly what was advertised.
  7. For the implied exercise at the bottom of page 194 (rerunning with listfaq.jsf again), I feared the worst because the external browser had not been working, but I tried anyway. The result was that it did work and when I did View Source... I saw the same “garbage” I had seen in #3 above and recognized it as such.