Create New Skin in Portal

Creating a Skin that supports Client-Side Aggregation

Skins in client-side aggregation are different from traditional Portal skins in that all the rendering is performed on the client. A CSA skin consists of two parts: a javascript controller and a renderer. Typically, the renderer is an XSL which is applied to the XML returned from the Portal REST services.

Controller


The controller is responsible for responding to all user interactions. It must define the following functions (at the very least):

  • instance
  • destroy
  • renderSkin
  • updateSkin
  • getActiveDiv

Refer to the attached CSASkinCodeExamples.pdf for a controller example.

Renderer


The most common selection for the renderer will be an XSL transformation. Both the provided samples use XSL transformations to create the markup for the skin. These are packaged with the theme and registered in the theme's bootstrap function. The markup produced by the renderer will be inserted into the page's markup and should be designed with that knowledge in mind. Essentially, the markup produced by the renderer needs to be self contained.

Refer to the attached CSASkinCodeExamples.pdf for examples of XSL and XML instances.

Packaging a skin that supports client-side aggregation
The CSA skins are packaged differently from traditional server side skins. The packaging is very flexible; it is up to the theme to set all the correct paths. Usually, the XSL (renderer) is packaged with the theme (in the PortalWeb2 theme, all the xsl files are in the xsl subdirectory), but can be packaged anywhere that is url addressable. The js controller can also be packaged anywhere that is url addressable. All skins must be registered both in Themes & Skins portlet, but also in the boostrap function in the CSA-enabled theme (PortalWeb2 is the sample CSA-enabled theme).

The function signature to register a skin is:

addSkin:
function ( /*Skin*/ skinTemplate, /*Boolean*/isDefault ) {
// summary: Registers a new skin for use in rendering the page.
// description: Adds the skinTemplate to the Page object for use
// in rendering. The Page object stores an associative array
// of skin templates, and a reference to the default skin to
// use if one is not specified for the portlet. There is one
// tempate object for each 'skin', but a factory method:
// skinTemplate.instance(fullPortletId) is used to create an
// actual skin for a specific portlet.
// skinTemplate: com.ibm.portal.aggregation.Skin - the skin template object.
// isDefault: Boolean - whether the skin should be registered as the default for the theme.

}


In head_extras.jspf, the skins are registered by the following lines in the bootstrap function:
portalAggregator.page.addSkin(new com.ibm.portal.aggregation.IbmSkin("IBM",skinResourceRoot2Id["IBM"],""),true);
portalAggregator.page.addSkin(new com.ibm.portal.aggregation.Skin("NoSkin",skinResourceRoot2Id["NoSkin"],""),false);
portalAggregator.page.addSkin(new com.ibm.portal.aggregation.Skin("ThinSkin",skinResourceRoot2Id["ThinSkin"],""),false);

To add a new skin, simply replace the values with the values appropriate to the new skin. For example, to add a new skin called “FunSkin” that is packaged in the xsl subdirectory of the PortalWeb2 theme:

portalAggregator.page.addSkin(new FunSkin("FunSkin",skinResourceRoot2Id["FunSkin"],""),false);

Lifecycle of a skin that supports client-side aggregation
The IBM and NoSkin CSA skins are provided as samples. The basic lifecycle of a skin behaves as follows:

1. The page layout is retrieved and processed. All portlets on the page are extracted from the layout xml.
2. The assigned skin is read and a new instance of the skin controller class is created by calling the instance function.
3. The skin is rendered by calling renderSkin. This happens once per lifecycle and basically just renders the initial skin markup.
4. getActiveDiv is called and the portlet markup is inserted in to the active div returned by the skin controller.
5. When the user navigates away from the page with the current portlet and skin, destroy is called. Click here to View more...

Adding Web 2.0 skins

In conventional portal skins, a Control.jsp implements the code to render the decoration around a portlet. With the portal Web 2.0 theme, the portal renders the pages on the client. Therefore, rather than invoke a JSP to render the skin, it requires to execute an XSLT transformation. To achieve this, the portlet needs to register the following at bootstrap time in head_extras.jspf : The skin name and xslt file path in a mapping for use by the CSA aggregator, along with its object ID, that is its internal identifier which it retrieves from the portal model.

At runtime, the page layout model stores the object ID of the assigned skin. The CSA aggregator retrieves the XSLT path of the skin, then load and apply it to render the skin. If the XSLT path is empty or null, the default skin XSLT would be used.

To add a new skin, proceed as follows:

  1. Implement an XSLT to render the desired markup.
  2. Store the XSLT file in the /xslt directory of the theme, with the same name as the skin. For example, for the IBM skin this is xslt/IBM.xsl .
  3. Register the new skin with the CSA aggregator as follows:
    1. Edit the file head_csa.jspf .
    2. In the definition of the bootstrap() function, find the lines shown below and add a new, similar line for your skin:
      portalAggregator.page.addSkin(new
      com.ibm.portal.aggregation.IbmSkin("IBM",skinResourceRoot2Id["IBM"],""),true);
      portalAggregator.page.addSkin(new
      com.ibm.portal.aggregation.Skin("NoSkin",skinResourceRoot2Id["NoSkin"],""),false);
Click here to View more...

Ajax with HTML

In Eclipse -- Create a Dynamic Web Proj-- Create index.html (Paste the below Code in it)

<html>
<body>

<script type="text/javascript">
var xmlHttp = null;
function ajaxFunction()
{


// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();

// Internet Explorer

xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");



xmlHttp.onreadystatechange=abc;
var myname=document.all.username.value;
xmlHttp.open("GET","time.jsp?name="+myname,true);
xmlHttp.send(null);
}
function abc()
{
if(xmlHttp.readyState==4)
{
if (xmlHttp.responseText=="1")
alert("Enter name is correct");
else
alert("Wrong name");
//alert(xmlHttp.responseText);

//document.myForm.time.value=xmlHttp.responseText;
}
}
</script>

<form name="myForm">
Name: <input type="text"
onblur="ajaxFunction();" name="username" />
Time: <input type="text" name="time" />
</form>

</body>
</html>

Create time.jsp (U can put any server side logic or validation here.. paste the following code there)

<% String myname=request.getParameter("name"); System.out.println("MY CONSOLE : NAME="+myname); if(myname.equals("XXXX")) { response.getWriter().write("1"); } else { response.getWriter().write("2"); } %>


Now u can Run Ur index.jsp on any Web enabled Server Say (JBOSS) Click here to View more...

Add Custom JSF Components to Oracle JDeveloper 10g

Adding Custom JSF components

This HowTo explains how to add custom JavaServer Faces components to Oracle JDeveloper 10g (10.1.3) Preview. This HowTo is divided into two parts - one that is explaining how to get Oracle ADF Faces components up and running and the second part is covering how to get other or your own custom components installed within Oracle JDeveloper 10g (10.1.3). For more information and HowTos, please, refer to the JDeveloper page on Oracle Technology Network (OTN).


Prerequisites

In order to follow this HowTo you need the Oracle JDeveloper 10g (10.1.3) Developer Preview, ADF Faces, and access to Internet.

Adding ADF Faces components

Update Center

Here is a solution to the problem of importing extensions and other upgrades to JDeveloper. The Check for Updates Wizard is used to download and install extensions and patches for Oracle JDeveloper 10g Developer Preview. You can choose whether to install updates from a remote Update Center or from a local update bundle.

Installing ADF Faces components

With the release of Oracle JDeveloper 10g Developer Preview there is built-in support for visually building JavaServer Faces (JSF) applications. The release also contains a basic set of components provided by the JSF reference implementation (JSR 127). For developers looking at building enterprise applications with JSF it will most certainly include the use of custom components provided by third party component vendors.

To provide evaluation software to developers and architects Oracle has released parts of Oracle ADF, the Oracle ADF Faces components, as Early Access software on OTN. Oracle ADF Faces is a rich set of user interface components built on top of the new JavaServer Faces JSR-127 standard. Oracle ADF Faces provides various user-interface components with built-in functionality - such as data tables, hierarchical tables, and color and date pickers - that can be customized and re-used in your application ADF Faces is a subset of the complete Oracle ADF and is an extensive set of JavaServer Faces components.

Major ADF new features and enhancements are currently under development. As a result, the Oracle JDeveloper 10g 10.1.3 Developer Preview does not yet include Oracle Application Developer Framework (ADF). A preview of Oracle ADF (10.1.3) is expected in the first half of CY 2005.

Important Installation Information - Due to an issue in the Preview version of JDeveloper, if you use the update center to update from a previous release of ADF Faces to EA12, you will no longer be able to run projects from the previous release through JDeveloper. Before you do the update you should close any projects you do not plan to upgrade to EA12.

Here is what you have to do in order to setup Oracle JDeveloper 10g (10.1.3) Developer Preview with ADF Faces components:

  1. Download Oracle JDeveloper 10g (10.1.3) Developer Preview.
  2. Select the Help menu and click on the "Check for Updates ..." menu option. The Check for Updates Wizard is launched.
  3. Click Next to get to the first step in this wizard - Source. Here you can select from which Update Center you would like to get your extensions and/or patches.
  4. Make sure the "Official Oracle Extensions" option is selected.


  5. Click Next to go to Step 2: Updates. This will show a list of available updates from that Update Center.


    Note: The version number may be different depending on available ADF Faces version
  6. Make sure that the ADF Faces option is selected (optionally deselect updates that you don't want) and click Next to install the ADF Faces components.


  7. Finish the wizard after checking that your update was installed.

Building a page with ADF Faces Components

You have now installed a very rich set of JSF components that can be used developing J2EE applications. There is no re-start required to use these components nor do you need to create a new project.

Creating a new project

  1. Select File menu and click on the New... option.
  2. In the new gallery select the General category and in the Items list select Application. Click OK.
  3. In the Create Application dialog enter a name and keep everything else as defaulted. Click OK.


  4. In the Create Project dialog enter a name for the project and click OK.
  5. Right click on the Project node and select New...
  6. In the New gallery expand the Web Tier node and select the JSF category. In the Items list select JSF JSP to create a new page and click OK.


  7. In the Create JSF JSP page wizard enter a name for you file and and click Next.
  8. You should now see all available Tag Libraries including the newly added ADF Faces libraries. Use the shuttle control to move the two ADF Faces libraries over to the right side.


  9. You can now finish the wizard by clicking Finish.
  10. You can now start dragging ADF Faces components from Component Palette to your page.

Adding ADF Faces to an already existing project

Using the Update Center feature to add components to JDeveloper do not automatically add these components to your projects. Here is how you add components to an already existing project.

  1. Double click on your project node. This will open the Project Properties dialog.
  2. In left pane select the JSP Tag libraries node.
  3. Click on the Add button available on the right side just below the currently available libraries.
  4. Select the two ADF Faces libraries and click OK.


  5. Click OK to close the Project Properties dialog. You should now be able to see your added components in the Component Palette.

For more information about ADF Faces please visit the Oracle ADF Faces EA page on OTN.

Adding Custom JavaServer Faces components

Installing JSF Components provided by other third party vendor

For most enterprise applications the Oracle ADF Faces components will be more than adequate, but in those rare occasions when a component outside the scope of ADF Faces is needed the Oracle JDeveloper 10g (10.1.3) Developer Preview will allow developers to visually build applications with these custom components.

To illustrate how to install a set of custom components we are going to use the sample components from Sun's reference implementation. Here is how you install custom components.

  1. Download the custom component libraries you would like to use. In this case download the JSF v1.1.01 RI from Sun's website and unzip the file. We are going to refer to the root folder of the unzip source as [COMPONENT_HOME].
  2. Start Oracle JDeveloper 10g (10.1.3) Developer Preview.
  3. Select the Tools menu and click on the Manage Libraries option. This will launch the Manage Libraries dialog.


  4. Select the JSP Tag libraries tab. We are now going to add the component tag library for these custom components.
  5. In the JSP Tag libraries tab select the User node and click the New button.


  6. In the launched dialog expand the [COMPONENT_HOME]/samples/ directory and select the demo-components.jar file. Then click Open.
    Note: Oracle JDeveloper 10g (10.1.3) Developer Preview will automatically detect any tag libraries (TLDs) available in this file.


  7. Change the display name to "JSF Custom Components" and set prefix to "d".
  8. Make sure that you check the "Execute Tags in JSP Visual Editor is selected before closing the dialog by clicking OK.


  9. You are now done adding custom components to Oracle JDeveloper 10g (10.1.3) Developer Preview.

Building a page with the JSF Custom Components provided as samples by the JSF RI

To be able to fully use the newly added JSF custom components provided by JSF RI you will have to perform some additional steps. These steps are only required for these components since they have dependencies on images and styles provided by the sample component set.

  1. After you have created your Application workspace and project you can create JSF JSP page by selecting File -> New Copy the images folder from the [COMPONENT_HOME]\samples\components\web directory and past it in your projects public_html folder.
  2. Copy the following stylesheets to your public_html folder - stylesheet.css, result-set.css, and tree-control-test.css

More Information

For more information about JSF and Oracle JDeveloper 10g (10.1.3) Developer Preview please visit the Oracle JDeveloper home page at Oracle Technology Network.

Click here to View more...

JSF Custom Components

Overview

One of the key strengths of JavaServer Faces (JSF) is that not only does it provide substantial technology for easy, out of the box component based J2EE Web applications assembly, but it also is a very flexible API which allows for a wide breadth of customizations in numerous and innovative ways. This article introduces and explores the component developer's experience of building custom JSF user interface (UI) components.

Intended Audience

First off, this article is intended for component developers who already have an understanding of the overall JSF application development process but want to learn how to start developing their own custom JSF UI components. For those who are still new to JSF development, readers are highly recommended to first consult JSF application tutorials such as Rick Hightower's article on basic JSF development:

http://www-106.ibm.com/developerworks/library/j-jsf1/

Or my earlier JavaPro article, which also introduces JSF:

http://www.fawcette.com/javapro/2004_01/magazine/features/cschalk/

In contrast to those introductory JSF articles, this article introduces the more advanced task of building custom JSF UI components by first explaining all of the "moving parts" associated with custom UI Components starting with a simple custom "HelloWorld" UI Component as an example.

The article then shows how to extend the simple "HelloWorld" component into more useful examples that show live stock quote information using a Web service. At the end of the article readers will have an appreciation of what exactly are the key tasks associated with building custom UI Components along with a full understanding of all the various sub-components that make up a typical "JSF UI Component".

When to Customize JSF

Before jumping into custom JSF component development just for the sake of it, some research should be done on whether custom development is necessary at all and at what level it is needed. As mentioned before, JavaServer Faces' base UI component library actually provides a modest amount of practical UI and non-UI components in its specification. In addition to visible components such as input/output fields, menu components and form buttons the JSF specification also has non-UI components which handle things like basic validation and/or data conversion. In many cases a developer may find that he/she may only need to customize a specific sub-component such as a new validation method as opposed to building an entirely new UI Component.

An easy google search or browsing through sites such as jsfcentral.com many usable and often free component libraries (and implementations) that can be experimented with. Some of the more popular and powerful ones include:

Once the decision has been made to build some custom components as opposed to just using some existing ones, here's how to get started.

The "Moving Parts" of a JSF UI Component

The term "JSF UI Component" is generally used to describe a set of sub-components which each which perform their own specific task such as rendering the component, validating its input, and/or performing any data conversions (such as a String to a Date conversion). This may often give the impression to a novice JSF developer that JSF component development is fairly complicated and possibly tedious, but this is also JSF's strength in that each UI Components' sub-components can be individually customized and re-configured into new and varied combinations. In fact it is JSF's flexible API and it's "pluggable renderering" technology which allows UI Components to written for multiple Web clients thus drastically decreasing the complexity for the Web developer of assembling multi-client Web applications. Let's review the various "moving parts" of what constitutes a JSF UI Component.

The general term "JSF UI Component" refers to a collection of the following:

  • UIComponent Class - A Java class derived from either the UIComponentBase or extended from an existing JSF UIComponent such as outputText. This is the actual Java class representing the core logic of the component. It can optionally contain the logic to "render" itself to a client, or rendering logic can be separated into a separate "renderer" class.
  • Renderer Class - This is a class that only contains code to render a UIComponent. Rendering classes can provide different renderings for a UI Component. For such as either a button or hyperlink for the UICommand component. Renderers can also provide different rendering options for the same UI Component on different client types such as browsers, PDAs etc. This allows JSF the ability to run on any client device providing a corresponding set of renderer classes are built for the specific client type.
  • UI Component Tag Class - This is a JSP tag handler class that allows the UI Component to be used in a JSP. It can also associate a separate renderer class with a UIComponent class. (Note: The UI Component Tag handler class is only required for usage in a JSP deployment environment. Keep in mind that UI Components can also be used in non-JSP environments.)
  • Tag Library Descriptor File - This is a standard J2EE JSP tag library descriptor (tld) file which associates the tag handler class with a usable tag in a JSP page. (Required only For JSP usage only.)
  • Associated helper classes - These include a collection of standard (included in JSF RI) or custom helper classes such as Converters, Validators, ActionListeners etc., that can be programmatically bound to UI Components. For example a JSF UI Input Field component can be associated with a built-in number range Validator which ensures that an entered number is within a certain range. These helper classes can also be customized to perform any type of validation not provided out of the box with the JSF RI. For example a custom credit card Validator could be used with a JSF Input field to validate credit card numbers or a custom Converter could be used to convert currencies.
A Simple "HelloWorld" Custom UI Component Example

Before showing how to build a "Hello World" custom component, let's review quickly how to use it. To invoke the component we have a JSF enabled JSP page with an extra taglib directive specifying a custom tag library (tld) which contains the custom tag, "jsfhello", which is associated with our custom UI Component. To use the jsfhello tag, we simply place it into the body of the JSP and set an optional "hellomsg" attribute.

"http://www.w3.org/TR/html4/loose.dtd">

<%@ page contentType="text/html;charset=windows-1252"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://theserverside.com/customfacescomponents" prefix="cf"%>









A simple HelloWorld Custom Component:



The HelloWorld UI Component:









When the page is run, the JSF UI Component displays the "Hello World" message provided in the "hellomsg" attribute along with the current date and time. We'll review the details of the tag library and how the tag handler class invokes the UI Component shortly, but first let's review how to build the core UI Component class.

Building the"HelloWorld" Custom UI Component Step 1: Creating a UIComponent Class

For our HelloWorld example, our UIComponent will extend the UIComponentBase abstract class, which is provided in the JSF specification, and render a formatted HelloWorld message. Note: We could have also based our new UI Component class on the concrete UIOutput base class which is basically the same as the UIComponentBase with the exception that it has a "value" attribute. Since we aren't using one, we'll simply base it on the UIComponentBase abstract class.

package tss.hello;


import java.util.Date;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import java.io.IOException;
import javax.faces.context.ResponseWriter;


public class HelloUIComp extends UIComponentBase
{

public void encodeBegin(FacesContext context) throws IOException
{
ResponseWriter writer = context.getResponseWriter();
String hellomsg = (String)getAttributes().get("hellomsg");

writer.startElement("h3", this);
if(hellomsg != null)
writer.writeText(hellomsg, "hellomsg");
else
writer.writeText("Hello from a custom JSF UI Component!", null);
writer.endElement("h3");
writer.startElement("p", this);
writer.writeText(" Today is: " + new Date(), null);
writer.endElement("p");
}

public String getFamily()
{
return "HelloFamily";
}
}

As you can see, this custom UI Component renders a formatted Helloworld message using and encodeBegin() method. Also notice that we have defined a method getFamily(). This is actually required for UI Components that extend UIComponentBase since it could come from any component family. Since in our example we won't be creating a new family of components, we can just return any String value such as "HelloFamily". Before examing the code further, a quick note on encoding and decoding.

A Quick Note on Encoding Methods

UI Components and/or associated renderer classes use encode*() methods display themselves to a client. The above HelloWorld example simply renders an HTML header (h3) with the custom hello message (if supplied) along with a paragraph containing the current date and time. For this component a single encodeBegin() (or encodeEnd() ) method is all that is needed to render the complete tag since it does not contain any children. The encodeBegin actually renders the beginning or the complete (bodiless) tag. UI Components with children tags/components will override encodeChildren() along with encodeEnd(). The encodeChildren() method allows children components to be rendered and encodeEnd() renders the closing parent tag.

A Closer Look at the encodeBegin() Method

Upon closer examination of the encodeBegin() method, we see that it receives the FacesContext as an argument. An extension to the servlet and JSP context, the FacesContext provides access to the many useful objects for JSF/JSP/Servlet development. In this example, we simply extract a "writer" object in order to "write" our rendered response back to the client.

 public void encodeBegin(FacesContext context) throws IOException { ResponseWriter

writer = context.getResponseWriter();

Next we get the value of the attribute "hellomsg" which is passed from the tag from our JSP page using getAttributes(). The getAttributes method comes from the UIComponentBase class which is the base class for all UI Components.

String hellomsg = (String)getAttributes().get("hellomsg");

Rendering the HTML message is done using the writer methods in the code:

writer.startElement("h3", this);

if(hellomsg != null)
writer.writeText(hellomsg, "hellomsg");
else
writer.writeText("Hello from a custom JSF UI Component!", null);
writer.endElement("h3");
writer.startElement("p", this);
writer.writeText(" Today is: " + new Date(), null);
writer.endElement("p");

which when executed displays a formatted HTML "HelloWorld" message to the client.

Note: You'll notice that when the attribute (hellomsg) or "property" is written to the client, an additional String value representing the name of the property "hellomsg" is also included as an argument to the writeText() method. The idea behind this is to provide development tools environments the ability to display the name of the property in a visual editor. Leaving the second argument null is also acceptable and will not harm the execution of the component.

Step 2. Registering the custom UI Component in Faces-config.xml

Before moving on to building a JSP tag handler and a TLD file, we'll add a required entry for our custom component in the faces-config.xml file. The syntax for adding our custom UI component is:

...



tss.hello.JsfHello
tss.hello.HelloUIComp

...

The component-type is the "JSF recognized" name of our custom component: "tss.hello.JsfHello". (We'll refer to this later in our tag handler.) The component-class is the actual class path address of our UI Component.

Step 3. Building a Custom JSP Tag Library

In order to be able to use our custom component in a JSP, we need a custom tag library comprised of a tag library descriptor file (TLD) along with references to taghandlers classes. (This example uses just a single tag handler.)

Building the Tag Handler

For JSF component development, the JSP taghandler class is derived from javax.faces.webapp.UIComponentTag. It's main purpose is to:

  1. Associate a JSP callable tag (handler class) with the UI Component.
  2. Associate a separate renderer class (if needed) to the UI Component.
  3. Set the properties from the submitted tag attribute values to the UI Component.

Here is the source code for our tag handler class:

package tss.hello;


import javax.faces.application.Application;
import javax.faces.webapp.UIComponentTag;
import javax.faces.component.UIComponent;
import javax.faces.el.ValueBinding;
import javax.faces.context.FacesContext;

public class FacesHelloTag extends UIComponentTag
{
// Declare a bean property for the hellomsg attribute.
public String hellomsg = null;


// Associate the renderer and component type.
public String getComponentType() { return "tss.hello.JsfHello"; }
public String getRendererType() { return null; }


protected void setProperties(UIComponent component)
{
super.setProperties(component);

// set hellomsg
if (hellomsg != null)
{
if (isValueReference(hellomsg))
{
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
ValueBinding vb = app.createValueBinding(hellomsg);
component.setValueBinding("hellomsg", vb);
}
else
component.getAttributes().put("hellomsg", hellomsg);
}
}

public void release()
{
super.release();
hellomsg = null;
}


public void setHellomsg(String hellomsg)
{
this.hellomsg = hellomsg;
}
}

The first thing to note is the "hellomsg" bean property of type String along with its associated getter and setter methods at the bottom of the class. The hellomsg bean property, "hellomsg", is also an attribute in the JSP tag. (hellomsg="Hello world!"../>)

Next we see two methods which associate this tag handler with our registered UI Component: "tss.hello.JsfHello" as well as associate the renderer. Since we don't have a separate renderer class, this statement returns a null value.

 // Associate the renderer and component type.

public String getComponentType() { return "tss.hello.JsfHello"; }
public String getRendererType() { return null; }

The next method, setProperties(), sets the incoming values from the JSP tag by first calling the parent class' setProperties method along with custom code to set the value from the hellomsg tag attribute. Notice that a check is first done to see if the incoming attribute is a "ValueReference", which takes the form of a JSF EL expression: #{Bean.Property}. If a "ValueReference" is detected, it uses slightly different logic to set the application's value binding.

protected void setProperties(UIComponent component)

{
super.setProperties(component);


// set hellomsg
if (hellomsg != null)
{
if (isValueReference(hellomsg))
{
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
ValueBinding vb = app.createValueBinding(hellomsg);
component.setValueBinding("hellomsg", vb);
}
else
component.getAttributes().put("hellomsg", hellomsg);
}
}

Asides from the hellomsg getter and setter methods the only method required in the taghandler class is the release() method which resets the bean properties back to an unused state.

public void release()

{
super.release();
hellomsg = null;
}

and that's it for our tag handler class. Next we'll quickly review the JSP Tag Library Descriptor (TLD) required for this tag.

Step 4. Building the Tag Library Descriptor File

In order for us to use our custom JSP tag handler class, we need to create an associated TLD file which contains the tag entry associated with the tag handler class. Here is an example of the TLD file needed for this tag. The TLD associates the tag name, "jsfhello" with the tag class "tss.hello.FacesHelloTag" along with it's associated attributes. For our tag, we include our custom attribute, "hellomsg", along with the superclass' core attributes: "id", "binding" and "rendered".



PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

0.01
1.2
simple
http://theserverside.com/simplefacescomponents
This tag library contains simple JSF Component examples.




jsfhello
tss.hello.FacesHelloTag


binding
A value binding that points to a bean property



id
The client id of this component



rendered
Is this component rendered?



hellomsg
a custom message for the Component




Following standard J2EE architecture, the custom TLD file is placed in the /WEB-INF/. sub-directory of the J2EE Web Module containing the application.

Running the simple HelloWorld Example

Just to review, our custom JSF component java classes must be compiled and available on the classpath of a J2EE Web Module. The Web Module must also have in it's class path the required JSF runtime jar files which include: jsf-api.jar, jsf-impl.jar along with the commons jar files (commons-beanutils.jar, commons-collections.jar, commons-digester.jar, commons-logging.jar). The other two required jar files come from JSTL (jstl.jar and standard.jar).
For more info on the Commons and JSTL libraries refer to the Jakarta Apache Project website: http://jakarta.apache.org/ .) For a runtime deployment, all the required jar files must be placed in the /WEB-INF/lib subdirectory of your J2EE Web Module.

Assuming your runtime environment is properly configured, you can test the simple JSF Hello World custom component by first creating a JSF enabled JSP page and then adding the taglib directive and dropping the tag into your page. (As explained before..)

When the JSF page is run, you will see the execution of your HelloWorld JSF Custom Component!


Extending the HelloWorld Custom Component

Now that we've created a simple HelloWorld component, we can now expand upon this very easily. One straightforward extension would be to make the HelloWorld component call a Web service for a specific stock symbol and print out it's value. So instead of providing a hellomsg, our tag/component attribute will contain a stock symbol. The renderer code will then query a stock quote Web service (made available to us via another class) with the symbol provided by the tag and print the current price in the response.

Here's how to modify the HelloWorld Custom Component to display a live stock quote using a Web service.

Create a Web Service Proxy Client

In order to call a Web service from java, you'll need to create a proxy java client which enables any other Java class the ability to call a stock Web service. Many free stock quote Web services are available on the Internet. This example uses the "Delayed Stock Quote Service" available from Xmethods.com. The actual Web Proxy creation step is left to the reader to implement since it is out of the bounds of JSF development however several Java Integrated Development Environments such as Oracle JDeveloper, can automatically generate the necessary client code which enables communication to a Web service.


Oracle JDeveloper 10.1.3 Preview's Web Service Proxy Wizard

Once a Web service Proxy class is created, we'll modify our hellomsg attribute to become a stock symbol attribute and call the Web service with this value and then print it out. This involves the following changes:

Create or Modify the HelloWorld UIComponent Class to Work with "Symbol" Attribute

Change or create a new UIComponent class which refers to a stock symbol attribute, "symbol", instead of the "hellomsg".

public class StockUIComp extends UIComponentBase

{
public void encodeEnd(FacesContext context) throws IOException
{
ResponseWriter writer = context.getResponseWriter();
String symbol = (String)getAttributes().get("symbol");
...

Note: If you create a new UI Component such as StockUIComp, don't forget to register it in your faces-config file ( You could use the name: "tss.hello.JsfStock" mapped to the classpath address "tss.hello.StockUIComp").

Once you've retrieved the attribute value for the stock symbol, you can call your Web service proxy class to get the current price:

 //get stock price using generated Web service Proxy

String stockprice = NetXmethodsServicesStockquoteStockQuotePortClient
.getStockPrice(symbol);

Rendering the the stock price is easily done with the following code:

  writer.startElement("p", this);

if(symbol != null)
writer.writeText("The stock price for " + symbol
+ " is: " + stockprice + ".", null);
else
writer.writeText("You must provide a Stock Symbol by
setting the symbol attribute.", null);
writer.endElement("p");

The changes to the tag handler and TLD is a trivial search and replace of "hellomsg"" with "symbol". Your tag handler class will also have to refer to the different Stock UI Component: "tss.helloJsfStock", but the remaining code in the taghandler is basically the same as before with the "symbol" attribute replacing the "hellomsg" attribute:

public class StockTag extends UIComponentTag

{
public String symbol = null;

public String getRendererType() { return null; }
public String getComponentType() { return "tss.hello.JsfStock"; }

protected void setProperties(UIComponent component)
{
super.setProperties(component);

// set symbol

if (symbol != null)
{
if (isValueReference(symbol))
{
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
ValueBinding vb = app.createValueBinding(symbol);
component.setValueBinding("symbol", vb);
}
else
component.getAttributes().put("symbol", symbol);
}
...

Once you've updated your TLD with a new tag "simplestock" mapped to the taghandler "StockTag", you can then add the new tag to your JSP:

 

The SimpleStock UI Component:


simplestock symbol="orcl" />

Here's the output for the HelloWorld Component along with the new Stock UI Component:

Extending the Stock UI Component Further

Now that we've extended the HelloWorld UI Component into something useful, let's further extend the stock component to make it more user friendly. Our modified stock component will now render an input field along with a submit button. This will allow users to enter a new stock symbol at runtime as opposed to hardcoding the attribute value in the JSP source.

This modification will introduce how to build a decode() method which is used to "decode" the incoming form field values as opposed to simply retrieving tag attribute values. We will also extend our simple encode() method to now render in input field along with a submit button.

Back to the UI Component

This time we'll name the UI Component "HtmlInputStock" following the JSF specification's naming convention. This time we'll extend extend the class from the UIInput component since it will be accepting input.

public class HtmlInputStock extends UIInput

{
...

This component will have a more detailed encode() method. This time our encodeBegin() method will call separate encode methods to render the differerent elements: an input field, a submit button, and an output field which displays the returned price of the stock. Notice that I've add the identifiers ".inputbutton" and ".submitbutton" to the clientIds respectively when calling the encode methods. This will ensure that the names of the rendered HTML: fields will be unique on the client. In general this is good practice should you need to refer to the rendered name of the HTML field.

The encodeBegin() method is as follows:

public void encodeBegin(FacesContext context) throws IOException {

ResponseWriter writer = context.getResponseWriter();
String clientId = getClientId(context);


encodeInputField(writer, clientId+".inputbutton");
encodeSubmit(writer, clientId+".submitbutton");
encodeOutputField(context);
}

The encodeInputField() method is as follows:

 private void encodeInputField(ResponseWriter writer, String clientId)

throws IOException {
// render a standard HTML input field
writer.startElement("input", this);
writer.writeAttribute("type", "text", null);
writer.writeAttribute("name", clientId, "clientId");

Object v = getValue();
if (v != null)
writer.writeAttribute("value", v.toString(), "value");

writer.writeAttribute("size", "6", null);
writer.endElement("input");
}

Notice the name of the input field is assigned the clientId. We'll use this later to identify the field when we decode the input.

The encodeSubmit() is rendered with:

private void encodeSubmit(ResponseWriter writer, String clientId) 

throws IOException {
// render a submit button
writer.startElement("input", this);
writer.writeAttribute("type", "Submit", null);
writer.writeAttribute("name", clientId, "clientId");
writer.writeAttribute("value", "Enter Stock Symbol", null);
writer.endElement("input");
}

And finally the encodeOutputField() which is similar to before:

public void encodeOutputField(FacesContext context) throws IOException

{

ResponseWriter writer = context.getResponseWriter();
String symbol = (String)getAttributes().get("value");
// The "value" attribute is used to pass the stock symbol.

//get stock price
String stockprice = NetXmethodsServicesStockquoteStockQuotePortClient
.getStockPrice(symbol);

writer.startElement("p", this);
if(symbol != null)
writer.writeText("The current price for " + symbol + " is: " +
stockprice + ".", null);
else
writer.writeText("", null);
writer.endElement("p");
}

Now let's move on to the decode() method who's job is to parse the incoming field values and act upon it.

 public void decode(FacesContext context) {

Map requestMap = context.getExternalContext().getRequestParameterMap();
String clientId = getClientId(context);

try {

String string_submit_val = ((String) requestMap.get(clientId+"
.inputfield"));


setSubmittedValue(string_submit_val);
setValid(true);
}
catch(NumberFormatException ex) {
// let the converter take care of bad input, but we still have
// to set the submitted value, or the converter won't have
// any input to deal with
setSubmittedValue((String) requestMap.get(clientId));
}

}

Let's review some of the key statements in our decode() method. First our decode() method obtains a requestMap from the JSF Context.

      Map requestMap = context.getExternalContext().getRequestParameterMap();

The requestMap is a container which allows us to access the values submitted in the http request.

The next statement extracts the clientId which is the unique identifier of the client issuing the request. (i.e. submitting the form)

      String clientId = getClientId(context);

With the unique client identifier we can obtain the value of the submitted value contained in the requestMap for this client. We can then set the submittedValue to the value submitted in the form. Note: For this example, we are simply setting the value that was submitted as is, but in other cases we may wish to perform a conversion or validation on the submitted value before setting the value as "valid".

      try {              

String string_submit_val = ((String) requestMap.get(clientId));
setSubmittedValue(string_submit_val);
setValid(true);
}
catch(NumberFormatException ex) {

setSubmittedValue((String) requestMap.get(clientId));
}

That takes care of our new and improved UIComponent rendering (encoding and decoding). I'll leave out the step of registering this component in the faces-config and highlight the remaining trivial code modifications in the tag handler and the TLD.

For the tag handler we have only minor changes. This tag handler as before extends from the same UIComponentTag but will have a bean property of "value" instead of "symbol". The "value" property is the value submitted in the input field and is handled exactly in the same manner before as the symbol. The only other difference from before is that our tag handler is now registered with the StockInput UI Component Class.

  public String getComponentType() { return "tss.hello.StockInput"; }

The setProperties method is basically the same as before but operating on the "value" instead "symbol":

 protected void setProperties(UIComponent component)

{
super.setProperties(component);
if (value != null)
{
if (isValueReference(value))
{
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
ValueBinding vb = app.createValueBinding(value);
component.setValueBinding("value", vb);
}
else
component.getAttributes().put("value", value);
}

Updating the TLD

Similar to before, the new TLD tag entry can be as follows:

...


stockinput
tss.hello.StockInputTag


binding
A value binding that points to a bean property



id
The client id of this component



rendered
Is this component rendered?



value
A value for submitted stock symbol..


....

Running the Stock Input Component

Invoking this component is done in a similar fashion as before where we simply add the tag to the page:

 

Notice that we can leave the value attribute blank but specify it later when we run it. Once the page is running, enter a test stock symbol such as ORCL or AMZN and check out the result!

Summary

As you can see, building custom JSF UI Component is a fairly straightforward process. Once you understand the mechanism detailed in the encode() and decode() methods in the rendering code, the rest is a fairly trivial process of providing the necessary "plumbing" with tag handlers as such to enable usage in a typical client such as a JSP based client.

Future articles on JSF Component development will also build upon these simple examples and show how to build other non visual JSF components such as Validators and Converters.

Click here to View more...

HTML Layout Tag Library in JSF

Source Code: htmLib.zip (1,777 Kb)


The HTML Layout Tag Library contains components for almost all of the standard HTML tags and attributes based on the HTML 4.01 specification. The excluded tags for the library are the interaction tags, such as form, input, select, and textarea. The library allows you to use old-fashioned HTML layout tags mixed in with JSF components without having to use the f:verbatim tag.

This resolves a problem developers face who begin working with standard JSF libraries and then notice that some features are missing that they had used previously in working with other JSP-centric technologies such as Struts. The stumbling block is that most JSF tags will not allow you to insert a pure HTML tag as a child node. One way around this is to use the f:verbatim tag, but this tag does not allow JSF components inside (as a descendent of the f:verbatim element). This has the unfortunate result of discouraging developers from using JSF tags that provide layout such as h:panelGrid, h:panelGroup, h:column. The HTML Layout Tag Library eliminates this problem, easing the transition to JSF for newbies.

The library contain tags that are rendered into their HTML analogs. You use the tags in the library as you would their HTML analogs (per the W3C documentation) with the following differences:

  • Each library tag contains a rendered attribute. If it is set to false, the tag and its children are not rendered.
  • If the library tag contains an id attribute, the standard JSF convention for id attributes is applied. The id's value will be replaced with the component clientId's value
  • If you want to keep the same value for the id in the rendered result, use an sid attribute instead.
  • Each tag has a binding attribute. So, you can use the component binding. The component class name for each tag is built based on tag name using the com.exadel.htmLib.components.UI pattern. Where the is a name of the tag starts with a capital letter.
    For example,
    htm:table - com.exadel.htmLib.components.UITable
    htm:b - com.exadel.htmLib.components.UIB
  • Each attribute, except the id attribute, supports value binding. You can use something like #{foo.bar} instead of a static literal value.
  • Each attribute, except the id attribute, supports jsp scriplets. You can use something like <%=foo%> instead of a static literal value.
  • The following attribute names are changed due the name convention problem:
    • class with styleClass
    • for with forAttribute
    • char with charAttribute

How to Download

Download htmLib.jar (72.4K) file and put it into the WEB-INF/lib folder of your JSF application.

How to Use

Add the following taglib declaration at the top of the page:

<%@ taglib uri="http://jsftutorials.net/htmLib" prefix="htm" %> 

After that, you can use the tags (htm:table, htm:tr, htm:td, htm:colgroup, htm:br and so on) in the rest of the page.

For JSF Studio Users

If you want to have this library in the Palette, once the htmLib.jar file is added to the project, drag and drop the htmLib.tld file from the JSF Project view onto the Exadel Palette. The library will then become available for click-n-insert. No other configuration is required.

Click here to View more...

Create Custom JSF Components

This article illustrates how to build custom components for use in web applications based on JavaServer Faces (JSF). While JSF comes with a standard set of components, one of the most-publicized features is the easy addition of new components. In this article, you will see just how easy it is to create new components that are fully functional and integrated into your web applications. Specifically, this article will show how to develop a component that allows users to enter valid credit card numbers.

A Very Quick JSF Introduction

At a very high level, JSF is an implementation of the Model 2 pattern, also referred to as Model-View-Controller (MVC), for the Web. The basic idea behind the pattern is to separate the concerns of your application; namely, the business logic, the user interface that allows manipulation business data, and the glue that makes the two able to communicate. Another way to think about MVC is that you don't want to put the discount calculation into the View, because that calculation is business logic. Instead, keep all of the business logic together in coherent abstractions referred to as the Model. Then, keep the complexity of your user interface together in coherent abstractions referred to as the View. Finally have the model and view talk together with a layer of "glue" called the Controller.

Components in JSF are part of the View layer. The view is built by composing groups of components into trees that together make up the user interface. The components themselves are fairly fine-grained and are typically reusable from one user interface to another. An example would be the HtmlInputText component that is part of the JSF standard. This component provides a text field for users to type in data. A group of inputs is composed into a view, and that view allows for manipulation of a particular piece of business information through the controller that sits between the view and model objects being edited. You can find a lot more good information at the official JSF site.

Components in JSF

Now that we have presented a high level view of what JSF is, let's dive into the particulars of what a component is. In JSF, a component is a group of interacting classes that together provide a reusable piece of web-based user interface code. A component is made up of three classes that work closely together.

First is the renderer, which creates the client-side representation of the component and takes any input from the client and transforms it into something the component can understand. The typical renderer implementation will generate HTML and understand how to transform values from HTML form POSTs into values the component understands. However this is not the only client type that can be rendered by a JSF renderer; for example, the reference implementation comes with a set of XUL renderers.

Second is the UIComponent subclass. This class is responsible for the data and behavior of the component on the server side; in other words, anything that the component is responsible for that is not related to rendering is found in the component class.

Finally, most JSF components will have a JSP custom action. The main functions of this class are to allow for configuration of the component in a JSP and to attach a particular renderer to the component. As an example to make this clearer, consider the UICommand component (one of the standard components included in JSF). This component can be rendered as a link or a button. The JSP custom action is what makes the association -- for example, h:commandButton will render a button and h:commandLink will render an HTML link.

While we are discussing JSPs and JSF, I'd like to address one common misconception with JSF. JSPs are not the only way to compose a JSF user interface. In fact, it is fairly straightforward to build a JSF user interface in a servlet or in a plain Java class. JSPs were chosen as the "default" way to build JSF interfaces because of the broad knowledge base that exists in building web applications with JSPs.

Let's get out of the abstract and into the concrete. One of the standard UIComponents in JSF is the HtmlInputText. It is rendered by the TextRenderer (a concrete renderer in the reference implementation), and the final piece of the component is the h:inputText custom JSP action. These three classes together make up the standard component for users to type in small amounts of text. The tag makes the association between the component and its renderer. Figure 1 depicts the relationship between the three pieces of this component.

Figure 1 HtmlInputText Component
Figure 1. HtmlInputText component

Credit Card Input Component

Now that we are done with the basics of what a component is, let's go over the example custom component that will be fleshed out in this article. The example component allows users to input credit card numbers. A credit card number is defined to be 16 digits with or without dashes every four digits. The component will validate that the values entered match this definition. In order to implement this component, we will create four classes, the UIComponent subclass, the renderer, the JSP custom action, and a validator to ensure that any entered value matches this definition of a credit card number. Figure 2 shows the classes and their relationships.

Figure 2 Credit Card Component
Figure 2. Credit card component

The first class we will look at is the component. Since the credit card component allows users to input text values, we will subclass UIInput to make the component. Here is the code:

package example.component;

public class UICreditCardInput extends UIInput {
public static final String
CREDIT_CARD_FAMILY = "CCFAMILY";

public UICreditCardInput() {
super();
addValidator(new CreditCardValidator());
}

public String getFamily() {
return CREDIT_CARD_FAMILY;
}
}

Notice how simple this component is in terms of code content. Many custom components will be as simple as this; of course, there are many that will be more complex. And, no surprise, the complexity of the code depends directly on the complexity of the component being written. As an example, the calendar component in the MyFaces project is about 125 lines of generated code. This component is so simple because it is not adding any additional data fields to UIInput, so it's able to reuse most of the functionality of its superclass.

In order to accomplish the validation specified in the requirements for the credit card component, we add a validator in the constructor. Next is the getFamily method. This method simply returns the family of the component. This family (and thus the method that retrieves it) is significant, because this value is used to look up the renderer when it comes time to make HTML. We will see more on how the render kit uses the family to find a particular renderer later when we discuss rendering.

Next up is the validator that makes sure the credit card number fits the criteria (16 digits, with or without a dash every four characters). This is a very straightforward task with the regexp abilities built into J2SE 1.4 and later. Here is the code:

public class CreditCardValidator implements

Validator {
...
public void validate(FacesContext context,
UIComponent component, Object value)
throws ValidatorException {
if (null != value) {
if (!(value instanceof String)) {
throw new IllegalArgumentException(
"The value must be a String");
}
String ccNum = (String) value;
// do some asserts that value matches a
// regex...
Pattern withDashesPattern = Pattern
.compile("\\d\\d\\d\\d-\\d\\d\\d\\d-"
+ "\\d\\d\\d\\d-\\d\\d\\d\\d");
Pattern noDashesPattern = Pattern
.compile("\\d\\d\\d\\d\\d\\d\\d\\d"
+ "\\d\\d\\d\\d\\d\\d\\d\\d");
Matcher withDashesMatcher = withDashesPattern
.matcher(ccNum);
Matcher noDashesMatcher = noDashesPattern
.matcher(ccNum);
if (!withDashesMatcher.matches()
&& !noDashesMatcher.matches()) {
throw new ValidatorException(
new FacesMessage(
"The Credit Card Number must "
+ "have 16 digits with or "
+ "without dashes every "
+ "four digits"));
}
}
}
...
}

The important thing to note here is the response to error; if the string does not match one or the other of the Matchers, then a new FacesMessage is created and a ValidatorException is thrown. JSF will interpret the ValidationException and get the message from it so that you can display it in your faces interface.

While it's technically not part of the component, I suspect that the ability to have a validator connected to a component by default will be one of the reasons people will develop custom components. There is a lot more info on validation in the spec.

The next part of the component to consider is the renderer. Keep in mind that the renderer is responsible for turning the component into HTML and taking posted HTML and turning it into values suitable for the component. (This process is known as rendering or as encoding and decoding.) In other words, the renderer is responsible for building the HTML that is used in the UI and taking any form posts and passing the values in the post back to the component. Here is the code for the CreditCard renderer.

public class CreditCardInputRenderer extends

Renderer {
...
public void decode(FacesContext context,
UIComponent component) {
assertValidInput(context, component);

if (component instanceof UIInput) {
UIInput input = (UIInput) component;
String clientId = input
.getClientId(context);
Map requestMap = context
.getExternalContext()
.getRequestParameterMap();
String newValue = (String) requestMap
.get(clientId);
if (null != newValue) {
input.setSubmittedValue(newValue);
}
}
}

public void encodeEnd(FacesContext ctx,
UIComponent component) throws IOException {
assertValidInput(ctx, component);
ResponseWriter writer = ctx
.getResponseWriter();
writer.startElement("input", component);
writer.writeAttribute("type", "text", "text");
String id = (String) component
.getClientId(ctx);
writer.writeAttribute("id", id, "id");
writer.writeAttribute("name", id, "id");
String size = (String) component
.getAttributes().get("size");
if (null != size) {
writer.writeAttribute("size", size, "size");
}
Object currentValue = getValue(component);
writer.writeAttribute("value",
formatValue(currentValue), "value");
writer.endElement("input");
}

protected Object getValue(UIComponent component) {
Object value = null;
if (component instanceof UIInput) {
value = ((UIInput) component)
.getSubmittedValue();
}
// if its not a UIInput or the submitted value
// was null then get the value (it should
// always be a UIInput)
if (null == value
&& component instanceof ValueHolder) {
value = ((ValueHolder) component)
.getValue();
}

return value;
}

private String formatValue(Object currentValue) {
// this should be a bit more sophisticated
// in essence what should happen here is any
// conversion that needs to take place.
return currentValue.toString();
}

private void assertValidInput(
FacesContext context, UIComponent component) {
if (context == null) {
throw new NullPointerException(
"context should not be null");
} else if (component == null) {
throw new NullPointerException(
"component should not be null");
}
}

}

This class has the bulk of the complexity for our example. This class is so complex because the particular renderers (text, button, etc.) are not publicly part of the specification and thus we can't subclass them directly. I don't think that is likely to change because rendering is one place in which commercial vendors can compete. Enough about politics; let's look at what is this class actually doing.

The first method is decode(FacesContext, UIComponent). This method is responsible for taking any parameters that were passed in from a form post and setting the value on the component. The first thing the method does is to assert that the context and component parameters are not null. This is part of the specification and should be done in every method of similar signature in any renderer. Next, the method avoids anything but UIInput components. If the component is a UIInput, then any new value is extracted from the request and put on the component as the submittedValue. Notice that no attempt to validate the value is made here in the renderer. Validation is handled separately by JSF during either the Process Validations or the Apply Request Values phase depending on the immediate property (there is a lot more detail on validation in section 3.5 of the final JSF specification).

The next method is encodeEnd(FacesContext, UIComponent). This method is responsible for building the HTML to represent the component in the browser. There are actually three encoding methods: encodeBegin(FacesContext, UIComponent), encodeChildren(FacesContext, UIComponent), and the one implemented here, encodeEnd(FacesContext, UIComponent). Since the UICreditCardInput component is fairly simple and does not have children, there is no need to implement the first two methods. For more complex components that render their child components, you would have the encodeBegin method start the element for the root component (the one being encoded), the encodeChildren would cause all of the children to be encoded, and finally, the encodeEnd method would close the element.

The first thing this method does is to assert that the parameters are valid. Next, this method uses the element-oriented methods on the writer that are part of the specification. This method of building the HTML is fine for very simple components like this, but for anything more complex the encodeXXX methods end up full of HTML-oriented strings. HTML strings embedded in your code are never a good idea, and make maintenance a headache. In the downloadable code, I offer an alternative implementation that uses JDom. The important thing for you to know about this method is that you are free to build the HTML in any way you want, in whatever technology you are comfortable with, as long as it eventually makes it into a stream of characters and is written into the ResponseWriter.

The last Java class we have to look at is the JSP action, or tag. This class is responsible for creating the component (handled by the UIComponentTag class from which you will typically subclass), attaching the renderer to the component, and finally, setting the fields on the components based on the values supplied in the JSP. Here is the code for the CreditCardInputTag.

public class CreditCardInputTag extends

UIComponentTag {

private static final String CCI_COMP_TYPE =
"CREDIT_CARD_INPUT";

private static final String CCI_RENDER_TYPE =
"CREDIT_CARD_RENDERER";
...
public String getComponentType() {
return CCI_COMP_TYPE;
}

public String getRendererType() {
return CCI_RENDER_TYPE;
}
...
protected void setProperties(
UIComponent component) {
FacesContext context = FacesContext
.getCurrentInstance();
super.setProperties(component);
if (null != size) {
component.getAttributes().put("size", size);
}
if (null != value) {
if (isValueReference(value)) {
ValueBinding vb = context
.getApplication().createValueBinding(
value);
component.setValueBinding("value", vb);
} else {
((UIInput) component).setValue(value);
}
}
}
}

Apart from the accessor methods (available in the download) there are three methods to look at. The first is getComponentType(). This method returns the type of the component that should be created by the tag (the type is sent to a factory for resolution to a class name and then an instance is created). The next method, getRendererType(), returns the type of the renderer. (The same factory story: the type is sent to a factory and the class name is matched, and a new instance is returned if needed. We will discuss this later in the discussion of the configuration file.) These two methods are used to make the connection between the renderer and the component.

This is a very powerful tool that we can use to associate different renderers with components. For example, let's consider one of the standard components, UICommand. This component can be rendered as an HTML link or as a button. The association is made via the JSP with the use of two different tags. To render the command as a button, we use the h:commandButton tag; to render as a link, we use the h:commandLink tag.

Next let's take a quick look at a very simple JSP that we can use to see the component in action.

<%@taglib prefix="h"

uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="f"
uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="cc"
uri="http://bill.dudney.net/cc/component"%>


Credit Card Component Example


Hello and welcome to the example










value="#{page.ccNum}"/>


action="#{page.saveNumber}"/>



This is all very standard JSP stuff: the CreditCard tag lib is imported with the taglib directive (along with the required JSF tags). The UICreditCardInput is created by the cc:creditCardInput tag, as we saw earlier in the code.

Figure 3 shows the component in action.

Figure 3 Credit Card Component rendered in a browser.
Figure 3. The credit card component rendered in a browser

Notice the error text in Figure 3. The user typed the character a into the credit card number (only numbers are allowed) and the validator rejected the input and supplied an error message.

Finally, let's take a quick look at the configuration file that tells JSF about the component and its renderer. Here is the code for the faces-config.xml file used in this example to configure the UICreditCardInput component and its renderer.



"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
"http://java.sun.com/dtd/web-facesconfig_1_0.dtd">



CREDIT_CARD_INPUT


example.component.UICreditCardInput







Renderer for the credit card component.

CCFAMILY

CREDIT_CARD_RENDERER


example.renderer.CreditCardInputRenderer




The component tag tells JSF the component type and the class. This is where the association is made between the type and the class of the component (that was alluded to in the earlier discussion of the CreditCardInputTag). This configuration file will end up being META-INF/faces-config.xml in the .jar file that represents this component. JSF will look for such a file name in each of the .jar files that are loaded at runtime (in the WEB-INF/lib directory for .war files) and use each of them in its configuration. In this way, multiple component .jar files can be combined into one web application, and all of the components described in each .jar will be available to the application.

Conclusion

This component is built from three parts: the UIComponent subclass, the renderer, and the JSP custom action. We have seen the implementation of all three parts as well as the JSP that puts them all together. All told, the credit card input component and example amount to only a few dozen lines of code. See how easy that is? Of course, as your components increase in complexity, the amount of code will increase, as well. The beauty of the JSF model is that the additional code is related to the complexity of the component and not JSF.

Good luck building your own components! You can download the code for this article. I hope you enjoy building your own components.


Click here to View more...

Using JSF with AJAX

he Java Enterprise Edition 5 platform includes JavaServer Faces (JSF) technology, which provides a mature and extensible user interface component model. The design of this model makes it easy for application developers to create custom components by extending the standard components included with JSF and to reuse these components across applications. Creating a component shields the page author from the complexities of AJAX by rendering all the HTML and JavaScript code that is required to incorporate AJAX capabilities into an application. There are many ways to wrap AJAX functionality using JSF, and this document will briefly mention several strategies. You can see the detailed write up on each related startegy in the following documents:

Solution

Developers who want to include AJAX support in JSF applications are faced with many design questions. For example,

  • Should AJAX request handling be done in a separate servlet controller or should it be handled by the JSF life cycle?
  • How can existing components be AJAX-enabled without rewriting them?
  • Should JavaScript code be embedded in Java code or externalized in a separate script file?
Those questions and more are addressed in each strategy.

Developers who want to include AJAX support in JSF applications have more than one strategy to choose from. We will cover two types of startegies at this time. One point to stress is that the programming model differs between component writer and page developer. The strategies covered here can be used to add AJAX support to just a part of your application or to create re-useable JSF components. Though it is a bit of extra work to create an AJAX enabled JSF component, it makes it very easy for page authors to re-use that component.

In the first strategy, using a PhaseListener to fulfill AJAX requests in JSF components, the JSF life cycle and the custom component handles or decorates the AJAX requests. The second strategy, using a Servlet to act as a controller, introduces a Servlet to process AJAX requests to be used with the JSF components. In the second strategy, all asynchronous requests will therefore be handled outside of the JSF life cycle processing. In general, the first startegy is more common and the second startegy is more of a special case.

References

Click here to View more...

Automatic JSP reloading

To view changes to your theme and skins JSPs without restarting the portal server, you can force the application server to automatically check for new versions of JSPs. While this is ideal for development and testing purposes, automatic JSP reloading should be disabled in a production environment because of performance issues.

Follow these steps to enable automatic JSP reloading:

  1. Open the file
was_profile_root/config/cells/cell_name/
applications/wps.ear/deployments/wps/wps.war
/WEB-INF/ibm-web-ext.xmi

  1. Find the following entry in this file:
    reloadingEnabled="false" do it

            
  2. Change the value for reloadingEnabled to true.
  3. Save the file.
  4. Restart the portal server.

After completing these steps, JSPs are automatically reloaded when they are changed. However, to view changes to a JSP that is included by another (parent) JSP, you must also change the parent JSP to indicate that it must be reloaded by the server.

Click here to View more...

Some Books Available in GWT

Books Available on GWT

Below is a set of books that have been published regarding the Google Web Toolkit, including a short description of each.

Please note that the books linked from this page are provided by third-parties and are not endorsed by Google. A dollar sign ($) denotes that the third-party vendor charges a fee for the tool. Please direct any questions about these resources to the appropriate contact listed below.

  • Google Web Toolkit: Taking the pain out of Ajax $

    This eBook by Ed Burnette guides you through the GWT installation process and through the creation of your first application. This book teaches you about the UI elements, Remote Procedure Calls, and the ins and outs of the framework.

  • Google Web Toolkit Solutions (Digital Short Cut): Cool & Useful Stuff $

    This shortcut, by David Geary, addresses several more advanced topics of GWT (like implementing drag and drop and Hibernate integration). It is especially appropriate for those of you who are already familiar with the basics of using GWT, and want to dive deeper.

  • Google Web Toolkit Solutions: More Cool & Useful Stuff $

    While the Digital Short Cut (above) walks through sample apps of some advanced GWT topics, this book covers an even more comprehensive set of advanced topics and goes into greater detail on each of them chapter by chapter. This book is ideal for GWT developers who want to take a deeper and more complete look at advanced GWT development.

  • Google Web Toolkit Applications $

    Ryan Dewsbury has translated his extensive experience and passion for the GWT platform into written word for this book. It explains both basic and advanced concepts involved in building large-scale, non-trivial GWT applications. Highly recommended for those who wish to want to learn the best practices in GWT application development.

  • GWT in Action $

    Robert Hanson and Adam Tacy have developed a comprehensive tutorial for Java developers interested in building the next generation of rich, web-based applications. By following a running example in the book, you can learn GWT from the ground up.

  • GWT in Practice (Early Access version) $

    Robert Cooper and Charles Collins have written an example-driven, code-rich book designed for web developers who already know the basics of GWT. After a quick review of GWT fundamentals, the book provides handy, reusable solutions to the problems you face when moving beyond "Hello World" and proof-of-concept apps.

  • The Google Web Toolkit $ Coming Soon!

    Bruce Johnson and Joel Webber, creators of the Google Web Toolkit (GWT), have signed with Addison-Wesley to write the definitive guide to GWT. This book will be published in 2007.

Click here to View more...