Implement graphical JSF Components

Source: Internet
Author: User
Tags tld

Developers believe that if appropriate tools are available to create interactive web interfaces, they can focus their time on core requirements and customization, and deliver applications in a timely manner within the specified time. Compared with other technologies such as assumerver pages or Apache struts, The assumerver faces (JSF) technology facilitates the creation of interactive web applications. JSF draws a clear line between Program Logic and GUI representation, improves the maintenance capability of web programs, and provides a framework for the development and reuse of Web user interface components.

Today, many web application developers are switching to JSF, but they find that pre-customized jsf ui components are limited by basic DHTML widgets. Advanced applications, such as regulatory or business process monitoring, need advanced visualization components that are compatible with the JSF framework. The standardization of the JSF framework makes it easy to develop reusable custom web GUI components. In addition, Web component developers can now provide more complex components and promise that web application developers can easily use these components. These JSF user interface components must be integrated and deployed in the JSF runtime framework, fully expanded, and well integrated into the IDE that provides JSF support during design.

Although JSF brings a standard user interface framework, there are several defects and vulnerabilities in developing the first custom JSF component. Let's see how to create a graphical JSF component that cannot be easily created by pure HTML. The features of the graphical JSF component require not only DHTML generation, but also supplementary support for Image Generation and client interaction. We will illustrate these features with an example of a graphical component. This graphic component provides graphs and facilitates client navigation and interaction. We will also understand the steps required to integrate this graphic component into the JSF-enabled IDE. By understanding the design of graphical components, you will have a better understanding of how to implement JSF components, which should enable you to develop custom JSF graphical components.

What is JSF?

JSF is a standard server-side framework that simplifies the presentation layer structure of Web applications. JSR 127, which defines the JSF framework (see references), has a reference implementation that provides basic UI components (such as input columns and buttons. You can combine reusable user interface components to create web pages, bind these components to the application data source, and use the server-side event control program to process client events. According to the description, the component supplier can compile components integrated with the JSF runtime framework and integrate them into the IDE compatible with JSF during design.

To a large extent, JSF components are directly consistent with HTML components and tags available under the technical requirements of HTML 2.0. For many web applications, this set of relatively simple components is enough. However, many applications, such as regulators or monitoring programs, require more complex data display and interaction, such as tabulation, plotting, and ing. Due to the limited ability of JSF components to directly submit complex graphical widgets in HTML, the ability to design these advanced components is not outstanding. The solution requires the server component to transmit images to the customer, but it will bring problems to itself, because the interaction on the basic HTML image is limited. Finally, when using JavaScript, you must be able to call client interaction to enable users to navigate and interact with data.

Let's take a look at the steps required to develop a simple JSF component that inputs CSS into the HTML page. When developing an advanced JSF graphical component, the description and sample code of this simple component are used as the background. Figure 1 shows how to use the component to be developed and shows the expected result. The advantage of using this component is that you can change the appearance of the entire page by changing the component value of a JSF action.

Figure 1: shows how to use a very simple JSF component to input CSS into an HTML page and get the result.

Development components

The JSF component contains several Java classes and configuration files. To create a custom JSF component, you need to develop a Java class that extends the basic JSF component class; Develop a rendering program for the default rendering software package; develop a Java class that will be used to describe tags on the JSP page, compile a tag library definition (TLD) file, and compile the JSF configuration file. Let's take a deeper look at these five steps.

Development component Java class. The component class is responsible for managing the attributes that represent the component status. Therefore, you must select an appropriate base class for the component based on its behavior (such as input or output components) (see Listing 1 ). The components described here can be extended by javax. Faces. component. uioutput to display the URL pointing to a style sheet file or Inline style table content. This component can be used to convert a style table to another style table in the JSF action. The correlation property specifies the value type: either a URL or an inline style. This component must also be able to store and fix its own status using the JSF framework-processed objects during request sending to the server. The component Status consists of the important attribute values required for the reconstruction object. The JSF framework automatically calls the savestate () and restorestate () methods. We can implement these two methods in the component to achieve this goal.

List1.Component class management displays the attributes of component status. You can select an appropriate base class for a component based on its behavior. In this example, the component extends javax. Faces. component. uioutput to display the URL pointing to a style sheet file or the content of an inline style table.

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]; } }

Develop the rendering program.The rendering program has two functions. First, the rendering program is responsible for sending an appropriate HTML segment, which can present components in the client. Generally, this HTML segment consists of HTML tags suitable for rendering the entire web browser. This JSF lifecycle is called the encoding or presentation-response phase. This response phase can also send JavaScript code that enhances client interaction.

The second role of the rendering program is to parse the data from the client and update the component Status on the server (for example, the text entered by the user in the text field ). The standard rendering program package is mandatory, but other rendering program packages can also be provided to provide alternative client notation or languages such as SVG (see references ). By checking the component connection properties, the rendering program you implement (see Listing 2) will select the CSS style sent on the HTML page.

List2.The standard rendering program package is mandatory. However, you can use other rendering program packages to provide replaceable client representations or languages. By checking the Connection Properties of the component, the rendering program you implement will select the CSS style sent out on the HTML page.

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"); }}}

Development label class.Similarly, the JSF framework provides a base class for extension to compile tags related to components. The label class defines and presents the component style that will be applied in the faces-config.xml file (the description of this style is very short ). It is also responsible for creating JSF components (processed by the JSF framework) and passing the attributes contained in the jsf tag for initializing components (see listing 3 ).

List3.The label class defines the style and rendering of the component that will be applied in the faces-config.xml file.

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));elsecomponent.getAttributes().put("value", value);if (link != null) if (isValueReference(link))component.setValueBinding("link",app.createValueBinding(link));elsecomponent.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;}}

This tag provides setter and getter to Manage Links and value attributes. Once a component is created, the setproperties () method is called to initialize the tag attributes. Each tag attribute has two types: Text value or bean attribute binding.

Write a tag library definition (TLD).TLD is an XML file that describes tags by associating tag names with corresponding Java classes. TLD also describes the attributes allowed by tags (see Listing 4 ). This TLD defines a tag named CSS, which is bound to the csstag class. It also declares the link and value tag attributes.

List4.TLD is an XML file that describes tags by associating tag names with corresponding Java classes. TLD defines a tag named CSS to bind it to the csstag class. It also declares the link and value tag attributes.

<?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 file</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 abacking bean. If this attribute is set, the tag does not create the component itself butretrieves it from the bean property. Thisattribute 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 file 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>

Compile JSFConfiguration file.To integrate a JSF component into the framework, you must provide a configuration file named faces-config.xml. This file associates the component type and rendering program type (for JSP custom tag handler) with the corresponding Java class. It can also describe the rendering program used with each component (see listing 5 ). This file defines the faces. cssfamily component family. In this example, this family is composed of the faces. csscomponent component type (this type is bound to the csscomponent class. Finally, the rendering program of the HTML. linkorinlinerenderer type (implemented by the csscomponent class) must be associated with the faces. cssfamily family.

Listing 5.This file associates the component type and rendering program type with the corresponding Java class and describes the rendering program used with each component. It also defines the faces. cssfamily component family.

<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN" "http://java.sun.com/dtd/web-facesconfig_1_0.dtd"><faces-config><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-config>

Start plotting

If you want to integrate your components into JSF-enabled IDE, You can provide additional instructions. For example, in addition to other design-time information, an xml configuration file named sun-faces-config.xml can be provided to describe the component properties that should be made public in the IDE.

Now that you have seen how to create a simple JSF component, let's take a look at how to create a graphical JSF component. We will follow the same basic steps to design an advanced JSF graphical component. Let's take a graphical component (such as the ilog JSF graphical component) as an example. Through a group of categories, this component provides a visual representation of data value distribution. This chart can display data sets in various display methods, such as bar chart, circle grid chart, and bubble chart. The JSF graphic component has two initial design restrictions:

We already have the Java image bean component, which has all the graphic display capabilities. This component can display many images and is highly customizable. Ideally, we want to use the bean component and its functions to form the foundation of our JSF component.

Normal JSF applications need to reload the entire page to update the view. This method is suitable for form-based applications, but in many cases it is not applicable to highly graphical user interfaces. Therefore, our JSF graphical components must be able to process some simple navigation without updating the entire page to provide a better user experience.

The JSF graphical component manages the graphical bean component, including creating a graphical bean, customizing the bean, and enabling the bean to be used for server operations. The rendering of the JSF component is completed in two phases. The JSF rendering program generates a label and a set of JavaScript objects (see figure 2 ). The client sends the request server back an image. This request is completed by a servlet. The servlet obtains the image bean and generates an image using the method provided by the image (see figure 3 ). Any further user interaction (amplification, scanning, and style sheet modification) that only changes the appearance of the image will cause an incremental update of the image. If the client does not only require updates to the image, the page is submitted (see figure 4 ).

Figure 2jsf graphical components manage graphical Bean components, including creating and customizing graphical beans and enabling them to be used for server-side actions. The JSF rendering program generates a label and a set of JavaScript objects.

Figure 3 the client requests the server to obtain an image through servlet. The servlet obtains the image bean and generates an image using the method provided by the image.

Figure 4 if the client does not only require updating the image appearance, the page will be submitted.

The JSF graphical component also has an additional set of JSF components.OverviewThe overall view of the image is displayed, and a rectangle representing the view is displayed. Users should also be allowed to scan the visible area.LegendA widget displays information about a data set. It can also be displayed in a graph, depending on the style of the data to be displayed. It can also provide clientInteractorsSuch as scanning and amplification, these functions can be seen as client interaction, indicating that the interaction with the image will not reload the entire page as a normal JSF interaction.

To present a graphical component, you only need to use the chartview label:

<Jvcf: chartview id = "C" style = "width: 500px; Height: 300px "... />

The data is displayed as an image on the HTML page. The image is created by the servlet and is designed to respond to an HTTP request (this request includes parameters such as the specified result image, image ing, and inline legends ). The result image is embedded into the client Dom, and only the image part of the page is updated.

Application Core Components

Let's take a look at some differences between simple custom JSF components and advanced graphics components. The JSF graphical component class is similar to a standard component, but has the graphical attribute of an accessible image Bean (the image bean is responsible for generating the image displayed on the HTML page. The JSF component can use a bound value or perform a local search for the image bean in the current session. When the JSF graphical component becomes the core component of an application, the optional JSF component (such as the overview or legend) is associated with the main graph to display additional information (see Listing 6 ).

List6.When the JSF graphical component becomes the core component of an application, the optional JSF component is associated with the main graph to display additional information.

<jvcf:chartZoomInteractor id="chartZoomInteractor" XZoomAllowed="true" YZoomAllowed="true" /> <jvcf:chartView id="chartView"  chart="#{myBean.chart}"  servlet="demo.ImageMapServlet" interactorId="chartZoomInteractor"  width="500" height="300"  styleSheets="/data/line.css" waitingImage="data/images/wait.gif"  imageFormat="PNG"  /><jvcf:chartOverview id="chartOverview" style="height:100;width:150px" viewId="chartView" lineWidth="3" lineColor="red" /><jvcf:chartLegend id="legendView" viewId="chartView"  width="400" height="180" layout="vertical" waitingImage="data/images/wait.gif" />

Rendering programs are a major difficulty in implementing this JSF. As mentioned above, the rendering program does not generate simple HTML, but generates Dynamic HTML (DHTML) consisting of HTML ( tag) and JavaScript proxy (proxy ).

Proxy is a javascript class instance that manages the image display of client components. This object is displayed on the client as a server-side Java component class. It has the same attributes as the component class. Each component, image, and accessory on the page has a proxy instance. When rendering JavaScript, using the facescontext. getexternalcontext (). encodenamespace (name) method on each visible JavaScript variable is a good practice. In this way, components will be easily integrated into the JSR 168-compliant port environment in the future.

For example, the proxy on the client must be imported to the JavaScript support library on the page. To keep the client as thin as possible, the Javascript library must be modularized Based on the proxy class supported by the Javascript library. Therefore, you need to input a set of different libraries that may overlap each proxy class. The difficult aspect of graph rendering occurs at the stage of sending these script libraries. Each component's rendering program must declare the library it needs and when to send the referenced library. It must recognize the sent library to avoid duplication. The script manager is responsible for this filtering only when the page is displayed. Each time the rendering program sends a full set of library input, it provides a list to the script manager that filters out the sent library.

The client proxy is designed to allow scripting and avoid unnecessary page updates. Once the image is displayed, you can use the proxy on the client to dynamically install the interactor and display or hide the image ing. Proxy objects can also be used by common JSF components that support JavaScript mouse event processing.

<jvcf:chartView id="chartView" .. />

The problem with modifying the proxy of the Component client is that its status is no longer synchronized with that of the Java component on the server. To solve this problem, the proxy uses a hidden input tag (<input type = "hidden">) to save the new State on the client. When a standard JSF action is executed and the page is submitted, the rendering program parses the hidden state to synchronize the client with the server. This behavior requires a special cracking behavior in the program class. The standard cracking method is improved to parse the status of the client and update the status of the server component.

Test instance

Association between graphs and their related components is completed by TAG reference and binding. To make the page design flexible, a component can be referenced before rendering. Therefore, during the rendering time, if a Component Property references another component that has not yet been rendered, it will delay sending JavaScript code that relies on the client to solve until the referenced component is rendered. This can be done by the dependency manager.

To verify this, you may wish to look at a typical instance that involves an overview that references a graph.

<jvcf:overview viewId="chart" [...] /> <jvcf:chartView id="chart" [....] />

There are two cases. The referenced graphic component has been rendered, so there is no problem

JSP:<jvcf:chartView id="chart" [....] /><jvcf:overview viewId="chart" id="overview" [...] /> render:[...]var chart = new IlvChartViewProxy ( .. );[...]var overview= new IlvFacesOverviewProxy ( .. );overview.setView(chart);[...]

Components with referenced images are not displayed before the dependent overview component. In this case, you can register a component on the dependency manager to create a monitor. When a graphical component is referenced for final rendering, its rendering program notifies you of the dependency manager created by you. In this case, the Code required to solve the dependency is sent:

JSP:<jvf:overview viewId="chart" id="overview" [...] /> <jvdf:chartView id="chart" [....] />render:[...]var overview = new IlvFacesOverviewProxy ( .. );[...]var chart = new IlvChartViewProxy ( .. );overview.setView(chart);[...]

One of the purposes of developing JSF components is to be able to apply them to any JSF-compatible ide. However, JSF compatibility is not enough to ensure that integration works in this design. The following are some simple ideas to facilitate integration with IDE during the development of JSF components:

First, the custom JSF component should provide a basic HTML Rendering program. During the design, JSF ide cannot present the requested valid data or dynamic graphical components connected to the app server. Therefore, components with complex or non-traditional (for example, not html) Rendering programs should use beans. isdesigntime () is used to determine whether to provide a basic HTML representation or a real component rendering program.

Another design problem is the component location and size. Different ides use different labels and attributes. Components that can be resized (such as an image) should be able to process different methods of defining the size.

Finally, to integrate with the IDE, the component must provide additional information that has not been defined as described by JSF. Unfortunately, each ide currently requires a special handler to integrate components, that is, XML files are required in one case, and Eclipse plug-ins are required in the other case, and so on. One of the main purposes of the next jsf jsr (Version 2.0) is to specify the additional metadata format.

As you can see, writing a simple JSF component is not difficult, because the framework has completed most of the work. The JSF framework manages component statuses, rendering programs, and so on. In this article, we have extended these basic concepts to design an advanced graphical JSF component that can display complex metadata, provide incremental updates, support a large number of client interactions, and collaborate with supporting components. To support these features, you need to make many improvements to the structure of the basic JSF component. Of course, the concept of incremental update will be a perfect improvement for the JSF framework in the future, because it only allows the presentation of the changed part of the page, avoiding the whole page update. Working in compliance with the JSF specification is often insufficient to ensure that components are fully integrated into the JSF ide; A new JSR should be able to address these challenges in a timely manner. Despite the defects, the JSF framework can greatly accelerate Web component development and easily integrate components from various resources to create complete and complex web applications.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.