Using Java Server Faces today - Java - Techguide

Using Java Server Faces today

 

Summary

In the first of a two-part series we show you how to create interactive Web displays using Java Server Faces technology.

Events

Echelon 2012
June 11 and 12, 2012

University Cultural Centre, National University of Singapore

Startup Asia Jakarta 2012
June 7 and 8, 2012

12th Floor, Annex Building, Wisma Nusantara Complex, Jl. M.H. Thamrin No. 59 Jakarta 10350, Indonesia

MMA Forum Singapore
April 23-25, 2012

Grand Hyatt Singapore

In the first of a two-part series we show you how to create interactive Web displays using Java Server Faces technology.

JavaServer Faces (JSF) technology brings many advantages to creating interactive Web applications versus other technologies such as JavaServer Pages or Apache Struts. JSF provides a clear separation between application logic and GUI presentation, improved maintenance capability for Web applications, and provides a framework for the development and reuse of Web user interface (UI) components.

Many Web application developers are now migrating to use JSF, but are finding the set of predefined JSF UI components limited to basic DHTML widgets. Advanced applications, such as supervision or business process monitoring, need advanced visualisation components that are compatible with the JSF framework.

The standardisation brought by the JSF framework makes it easy to develop custom Web GUI components that can be reused by application developers. In addition, Web component vendors are now able to provide more sophisticated components, with the assurance that Web application developers will be able to easily take advantage of these components. Such JSF UI components must integrate and deploy cleanly into the JSF runtime framework and integrate well at design-time into IDEs that provide JSF support.

Despite the standard UI framework brought by JSF, there are several pitfalls and traps for the person developing their fi rst custom JSF component. In this article we will describe how to build a graphical JSF component that cannot be easily built using pure HTML. The characteristics of a graphical JSF component require not only the generation of DHTML, but also some extra support for image generation and client- side interactions. This will be illustrated with an example of a charting component that is designed to provide graphical charts, as well as various client-side navigation and interaction facilities. Finally, the steps required to integrate the chart component into a JSF enabled IDE will be shown. By understanding the design of the charting component, developers will have a better understanding of how a graphical JSF component can be implemented and hopefully allow them to develop their own custom JSF graphical components.

What is JavaServer Faces?
JavaServer Faces (JSF) is a standard serverside framework that simplifi es the construction of the presentation layer of Web applications. Developers can assemble reusable UI components to create Web pages, bind these components to the application data source, and process client-side events with server-side event handlers. By following the specifi cation, component vendors can write components that integrate cleanly into the JSF runtime framework and can integrate into IDEs that are JSF compliant at design-time. JSR 127, which defines the JSF framework, comes with a reference implementation that provides basic UI components, such as input fields and buttons. For the most part, these JSF components correspond directly to the HTML components and tags available in the HTML 2.0 specification. This set of relatively simple components is sufficient for many Web applications.

However, many applications, such as supervision or monitoring, require more complex data display and interaction, such as charting, diagramming, and mapping. The design of these advanced components is not obvious because of the limited capability to render complex graphics widgets directly in HTML. The solution requires that the serverside components deliver images to the client. However, this brings its own problems because interactions on basic HTML images are limited. Finally, JavaScript must be used to enable the client-side interactions that allow the user to navigate and interact with the data.

Creating a simple JSF component
The following section will describe the steps needed to develop a very simple JSF component, one that imports CSS into an HTML page. The description and code samples for this simple component will then serve as background for developing the advanced JSF charting component in the subsequent sections.

Figure 1 shows how to use the component and the result.


Figure 1


The benefit of using such a component is to be able to change the complete look of the page by changing the component value from a JSF action.

A JSF component consists of several Java classes and confi guration fi les. In order to create a custom JSF component, developers will need to:

  1. Develop a Java class that extends one of the JSF base component classes.
  2. Develop a renderer for the default render kit.
  3. Develop a Java class that describes the tag that will be used in the JSP page.
  4. Write a Tag Library Definition file.
  5. Write the JSF configuration file.

    Step 1: Develop the component Java class.
    The component class is responsible for managing the properties that represent the component's state. This means an appropriate base class for the component must be selected, based upon whether it is an input or output component.

    The component described in Listing A extends javax.faces.component. UIOutput to display a URL pointing to a style sheet file or the contents of an inline style sheet.

    Listing A
    import javax.faces.component.*;
    public class CSSComponent extends UIOutput {
    private Boolean link;
    public String getFamily() {
    return "faces.CSSFamily";
    }
    public boolean isLink() {
    if (link != null)
    return link.booleanValue();
    ValueBinding vb = getValueBinding("link");
    if (vb != null) {
    Boolean bvb = (Boolean) vb.getValue(FacesContext.
    getCurrentInstance());
    if (bvb != null)
    return bvb.booleanValue();
    }
    return false;
    }
    public void setLink(boolean link) {
    this.link = new Boolean(link);
    }
    public Object saveState(FacesContext context) {
    return new Object[] { super.saveState(context), link };
    }
    public void restoreState(FacesContext context,
    Object stateObj) {
    Object[] state = (Object[]) stateObj;
    super.restoreState(context, state[0]);
    link = (Boolean) state[1];
    }
    }

    The 'link' property specifies the type of the value: either a URL or the inline style. The component must also be able to store and restore its state between requests to the server using an object processed by the JSF framework. The JSF framework automatically calls the saveState and restoreState methods, which we have implemented in our component to achieve this goal.

    Step 2: Develop the renderer.
    The renderer has two roles. First, it is responsible for emitting an appropriate HTML fragment that will render the component in the client. Usually, this HTML fragment will consist of some HTML tags that are suitable for rendering in general Web browsers. The rendering phase can also be used to emit JavaScript code that can be used to enhance client-side interaction.

    The second role of a renderer is to decode the data that comes from the client to update the server-side component state (for example the text that the user entered in a text field). The standard PROGRAM render kit is mandatory, but other renderer kits can be provided to offer an alternate client-side representation or language such as SVG.

    The renderer implemented in Listing B chooses the type of the CSS to be emitted in the HTML page by checking the link property of the component.

    Listing B
    import javax.faces.component.UIComponent;
    import javax.faces.context.FacesContext;
    import javax.faces.context.ResponseWriter;
    import javax.faces.render.Renderer;
    public class CSSRenderer extends Renderer {
    public void encodeEnd(FacesContext context,
    UIComponent component)
    throws IOException {
    super.encodeEnd(context, component);
    if (component instanceof CSSComponent) {
    CSSComponent cssComponent =
    (CSSComponent) component;
    String css = (String)cssComponent.getValue();
    boolean isLink = cssComponent.isLink();
    if (css != null)
    if (isLink)
    context.getResponseWriter().write("<link type='text/
    css' rel='stylesheet' href='" + css + "'/>");
    else
    context.getResponseWriter().write("<style>\n" + css
    + "\n<style/>\n");
    }
    }
    }


    Step 3: Develop the tag class.
    Again, the JSF framework provides base classes for writing the tag associated with the component. The tag class is responsible for:

    • Defining the component type and the rendering type of the component that will be used in the faces-config.xml file that we will describe in the next section.
    • Creating the JSF component (handled by the JSF framework) and passing attributes that are contained in the JSF tag to initialise the component.
    The tag in Listing C provides setters and getters to manage the link and value attributes.

    Listing C
    import javax.faces.Webapp.UIComponentTag;
    public class CSSTag
    extends UIComponentTag {
    private String value;
    private String link;
    public String getComponentType() {
    return "faces.CSSComponent";
    }
    public String getRendererType() {
    return "HTML.LinkOrInlineRenderer";
    }
    protected void setProperties(UIComponent component)
    {
    super.setProperties(component);
    Application app = getFacesContext().getApplication();
    if (value != null)
    if (isValueReference(value))
    component.setValueBinding("value",
    app.createValueBinding(value));
    else
    component.getAttributes().put("value", value);
    if (link != null)
    if (isValueReference(link))
    component.setValueBinding("link",
    app.createValueBinding(link));
    else
    component.getAttributes().put("link",
    new Boolean(link));
    }
    public String getLink() {
    return link;
    }
    public void setLink(String link) {
    this.link = link;
    }
    public String getValue() {
    return value;
    }
    public void setValue(String value) {
    this.value = value;
    }
    }


    When the component is created, the setProperties method is called to initialise its properties from the tag attributes. Each tag attribute can be either a literal value or a binding to a bean property.

    Step 4: Write the Tag Library Definition (TLD)
    The TLD is an XML file that describes the tag by associating the name of the tag with the corresponding Java class. The TLD also describes the allowed attributes of the tag.

    This TLD in Listing D defines a tag named 'css' that is bound to the CSSTag class. It also declares the link and value tag attributes.

    Listing D
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/Web-jsptaglibrary_1_
    2.dtd">
    <taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>custom</short-name>
    <uri>http://www.ilog.com/jviews/tlds/css.tld</uri>
    <description>This tag library contains a tag for a sample custom JSF Component.</description>
    <tag>
    <name>css</name>
    <tag-class>path.to.CSSTag</tag-class>
    <description>A component that displays the style inline or a link a to a css fi le</description>
    <attribute>
    <name>id</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
    <type>java.lang.String</type>
    <description>The id of this component.</description>
    </attribute>
    <attribute>
    <name>binding</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
    <type>java.lang.String</type>
    <description>The value binding expression linking this component to a
    property in a backing bean. If this attribute is set, the tag does not
    create the component itself but retrieves it from the bean property.
    This attribute must be a value binding.</description>
    </attribute>
    <attribute>
    <name>value</name>
    <required>true</required>
    <rtexprvalue>false</rtexprvalue>
    <type>java.lang.String</type>
    <description>The inline css text or the url to the css fi le to link.</description>
    </attribute>
    <attribute>
    <name>link</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
    <type>java.lang.String</type>
    <description>Whether the value is a link or the inline style.</description>
    </attribute>
    </tag>
    </taglib>


    Step 5: The JSF configuration file.
    In order to integrate a JSF component into the framework it's necessary to provide a configuration file called faces- config.xml. This file associates component types and renderer types, used in the JSP custom tag handler, to their corresponding Java class. This file also describes the renderer that should be used with each component.

    Listing E defines the faces.CSSFamily component family.

    Listing E
    <!DOCTYPE faces-confi g PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Confi g 1.0//EN"
    "http://java.sun.com/dtd/Web-facesconfi g_1_0.dtd">
    <faces-confi g>
    <component>
    <component-type>faces.CSSComponent</component-type>
    <component-class>path.to.CSSComponent</component-class>
    <component-extension>
    <component-family>faces.CSSFamily</component-family>
    <renderer-type>HTML.LinkOrInlineRenderer</renderer-type>
    </component-extension>
    </component>
    <render-kit>
    <renderer>
    <component-family>faces.CSSFamily</component-family>
    <renderer-type> HTML.LinkOrInlineRenderer </renderer-type>
    <renderer-class>path.to.CSSRenderer</renderer-class>
    </renderer>
    </render-kit>
    </faces-confi g>


    In our example, the family is made of a single component of type faces.CSSComponent. This type is bound to the CSSComponent class. Finally, the renderer of type HTML. LinkOrInlineRenderer, implemented by the CSSRenderer class, is associated with the faces.CSSFamily family.

    You can also provide additional information for integrating the component into a JSF-enabled IDE. In the case of the Sun Creator IDE, it will be necessary to provide an XML configuration file named sun-faces-config.xml. This configuration file describes the properties of the component that should to be exposed in the IDE, as well as other design-time information. For a more detailed description of Sun’s Studio Creator and building custom JSF components I'd highly recommend Sun’s developer Web site.

    Now that we have seen how to create a simple JSF component, part two of this series will show you how to create a graphical JSF component.

Talkback

Add your opinion

In order to post a comment, you need to be registered. (Sign In or register below)

Post your comment

ZDNet Asia Live

Malaysia organizations don't realize severity of cyberattacks http://t.co/PUCv68Rd

News: Radio Costa Rica by EnjoyIT 1.0: Radio Costa Rica allows you to listen to a great var... http://t.co/BLzVT5As http://t.co/1Dhcy6ki

The key for mobile operators is identifying the applications that are popular with subscribers on their network. They can then work partn...

1 hour ago by camcullen on Experience trumps content in apps monetization

Experience trumps content in apps monetization | ZDNet http://t.co/gBXcjbGd

Experience trumps content in apps monetization - ZDNet Asia News: "What we are doing currently is not to monetiz... http://t.co/S2EZtd8m

Malaysia organizations don't realize severity of cyberattacks: "Minister Maximus Johnity Ongkili said at the Sec... http://t.co/bgVlOBvx

#security Malaysia organizations don't realize severity of cyberattacks: "Minister Maximus Johnity Ongkili said ... http://t.co/hkFb4zrI

Malaysia organizations don't realize severity of cyberattacks http://t.co/EEEmRM3j via @zdnetasia

Malaysia organizations don't realize severity of cyberattacks - ZDNet Asia News http://t.co/YpNMYgb5

Malaysia organizations don't realize severity of cyberattacks http://t.co/FFems54Q

China solar cell makers seek Taiwan partnerships http://t.co/p5Hh7kJD

Big data acquisitions pave way to fast, effective innovation http://t.co/hdiEfBsz via @zdnetasia

Integration, focused investments to propel Windows Phone: By Kevin Kwang , ZDNet Asia on May 23, 2012 (2 hours a... http://t.co/E7tsZbHJ

Integration, focused investments to propel Windows Phone http://t.co/u9TqjQ8C

ZDNet Asia IT Salary Benchmark 2012 http://t.co/rVwYlV7H

AsiaClassifiedToday. Integration, focused investments to propel Windows Phone - ZDNet Asia: S... http://t.co/47tdjZyG #asia #google #biz

So much as we know , MTK6575 extremely integrated frequency1GHz ARM Cortex-A9 processor, the superiority of 3G / HSPA Modem, and help the...

1 day ago by y15822137359 on 5 SaaS adoption speed bumps to avoid

I reckon your view: "CRM is strategy, not software", if a company replicating the approach uses in ERP implementation into CRM, what they...

2 days ago by wykoong on Gartner: Mobile CRM gives better ROI than social

This video will teach you about the Excel fill handle but also provide you with a workook to download... http://www.youtube.com/watch?v=...

3 days ago by TradeBrother on A quick fill handle trick for Microsoft Excel

waiting...

5 days ago by eapete on What should count in a company's market value?

Boy, you've opened a can of worms now.

Wait for the rants & raves.

5 days ago by eapete on What should count in a company's market value?

I was puzzling before this whether to replicate the success formula we executed for a financial institute, and come out with a standard s...

5 days ago by wykoong on Drop the egos, copy ideas, then innovate