Welcome!

Java IoT Authors: Pat Romanski, Elizabeth White, Liz McMillan, Yeshim Deniz, Frank Lupo

Related Topics: Java IoT, Machine Learning

Java IoT: Blog Post

Learning JSF2: AJAX in JSF

JSF 2 comes with one tag that provides Ajax functionality

As you probably know JSF 2 is a major upgrade over JSF 1.2. One of the major additions to this version of JSF is standard Ajax support. This article covers Ajax features in JSF 2. If you are familiar with RichFaces and specifically the a4j:support tag then learning how to use Ajax features in JSF 2 is going to be very easy. Many concepts and features are being carried over from RichFaces.  Let’s start. 

JSF 2 comes with one tag that provides Ajax functionality. The tag is called f:ajax (sounds familiar to a4j:support – right?) When I do RichFaces trainings, I like to divide the core ideas into three parts: sending an Ajax request, partial view rendering and partial view processing. I will use the same approach here.

Sending an Ajax request
JSF comes with one tag to send an Ajax request, the tag is called . This tag is actually a client side behavior (here is a great post by Andy Schwartz on JSF 2 client behaviors). Being a behavior implies it’s never just used by itself on a page, it is always added as a child tag (behavior) to another UI component (or can even wrap several components). Let’s use a small echo application to demonstrate usage of this tag.

<h:form> 
   <h:panelGrid>
      <h:inputText value="#{bean.text}" >
         <f:ajax event="keyup"/>
      </h:inputText>
      <h:outputText id="text" value="#{bean.text}" />
   </h:panelGrid>
</h:form>

Code snippet above takes care of firing an Ajax request based on onkeyup event. Notice the actual event name is keyup. This takes care of firing an Ajax request. Next we need to figure out how to do partial view rendering.

Attribute Description
event String on which event Ajax request will be fired. If not specified, a default behavior based on parent component will be applied. The default event is action for ActionSource (ie: button) components and valueChange for EditableValueHolder components (ie: input). action and valueChange are actual String values that can be applied applied event attribute.

HTML Tables

Partial view rendering

With JSF 1.2 (and without RichFaces) every request would render the entire view back to us. That was simple, we didn’t have to worry which parts of the JSF view we want to be updated. Of course the basic concept behind Ajax is to only update those parts of the page that we actually need to. In order to accomplish this, we should only render those components on the server whose markup we want to update in browser. What all this means is we now need to specify which components in JSF view we want to render back. Partial view is still rendered on the server. Some updated portion is sent as XML to the browser where the DOM is updated.  Our example is rather simple, there is just one component with id text. tag has render attribute which points to id’s of components to render back. It could also take an EL expression. Adding it to our example, it looks like this:

<h:form> 
   <h:panelGrid>
      <h:inputText value="#{bean.text}" >
         <f:ajax event="keyup" render="text"/>
      </h:inputText>
      <h:outputText id="text" value="#{bean.text}" />
   </h:panelGrid>
</h:form>

If you have been using RichFaces, than the same attribute in RichFaces is called reRender. The event that is specified via event attribute must be an event that the parent component supports. If you look at the generated HTML, you will see something like this:

<input id="j_idt5:j_idt7" type="text" name="j_idt5:j_idt7" 
onkeyup="mojarra.ab(this,event,'keyup',0,'j_idt5:text')" />

If you specify an event that is not available on the parent component, an error message will be displayed when you run the page.

That’s it. Here is the bean code in case you want to run this page:

@ManagedBean(name = "bean") 
public class Bean {
   private String text; // getter and setter
   ...
}

Let’s say we also want to show and update a counter that shows the length of a string we entered. Adding new property to bean:

private Integer count; // getter and setter

Also adding Ajax listener to do the counting, notice that method takes a new AjaxBehaviorEvent object:

public void countListener(AjaxBehaviorEvent event) { 
   count = text.length();
}
Attribute Description
listener Listener method to invoke during Ajax request.

Updating the page:

<h:form> 
   <h:panelGrid>
      <h:inputText value="#{bean.text}" >
         <f:ajax event="keyup" render="text count" listener="#{bean.countListener}"/>
      </h:inputText>
      <h:outputText id="text" value="#{bean.text}" />
      <h:outputText id="count" value="#{bean.count}" />
   </h:panelGrid>
</h:form>

Notice that we added count id to render attribute. You use space as a separator for id’s.

In our examples above we actually specified on which even to fire an Ajax request. As it turns out we don’t have to specify an event. If we don’t specify one, each UI component has a default event on which Ajax request would be send. Taking h:inputText, the default Ajax event is onchange. Our example would almost work however, instead of onkeyup, you would now have to tab out or click outside the input field to fire the Ajax request:  So, we could have written our example like this (without event attribute):

<h:inputText value="#{bean.text}" > 
   <f:ajax render="text count" listener="#{bean.countListener}"/>
</h:inputText>
Attribute Description
render Determines id’s of components to be rendered. 

In our example, render pointed to actual component id we want to render back. render attribute could be set to the following values:

Possible values for render attribute Description
@all Render all components in view
@none Render no components in view (this is also the default value if render is not specified)
@this Render only this component, the component that triggered the Ajax request
@form Render all components within this form (from which Ajax request was fired)
id’s One or more id’s of components to be rendered
EL EL expression which resolves to Collection of Strings

render could also point to EL expression. In this case it’s possible to determine which components to render in run time. Here is how it works when using EL:

  • You bind render=”#{bean.renderComponents}”. Initial page is rendered. #{bean.renderComponents} is resolved during page rendering, for example to id’s compId1 and compId2.
  • On next Ajax request, compId1 and compId2 will be rerendered. During this request, #{bean.renderComponents} could be changed in runtime. For example, it is now set to compId3 and compId4. You also have to remember to rerender this control (in order to update the ids)
  • Page is rendered (from step 3). Values of compId3 and compId4 are now present (rendered) in the page.
  • On next Ajax request, components with id’s compId3 and compId4 will be rerendered.

Note: this behavior is slightly different than what you get do in RichFaces 3. In RichFaces reRender attribute when bound to an EL expression is resolved in the current request.

It’s also possible to issue Ajax requests programmatically using the jsf.ajax.request() JavaScript API:

<h:head> 
<h:outputScript name="jsf.js" library="javax.faces"/>
</h:head>
...
<h:body>
<h:form id="form">
<h:inputText value="#{bean.text}" 
     onkeyup="jsf.ajax.request(this, event, {render:'form:text'});"/>
<h:outputText id="text" value="#{bean.text}" />
<h:form>
</h:body>

A few things to look for. First, you need to include jsf.js file which provides all the JavaScript functionality. Second, for render you need to use client id (not just component id).

Let’s look at an example using a button:

<h:form> 
    <h:panelGrid >
    <h:commandButton value="Get time" >
      <f:ajax event="click" render="time"/>
    </h:commandButton>
    <h:outputText value="#{bean.now}" id="time"/>
</h:panelGrid>
</h:form>

Java bean:

public class Bean {
public Date getNow () {
return (new Date());
}
}

In example above, we are adding Ajax behavior to standard JSF button. We specified both event and render. But, the example could also be rewritten like this:

<h:form> 
    <h:panelGrid >
    <h:commandButton value="Get time" >
      <f:ajax render="time"/>
    </h:commandButton>
    <h:outputText value="#{bean.now}" id="time"/>
</h:panelGrid>
</h:form>

So far we covered sending an Ajax request and partial view rendering. Let’s now cover the third part: partial view processing.

Partial view processing
In JSF 1.x (and without RichFaces) when a form was submitted, the entire form was processed on the server. Processed means that all components went through phases Apply Request Values, Process Validation and Update Model. When Ajax, there are situations when you don’t want to process all the components in the form. To control which components will get processed, we use execute attribute on f:ajax tag.

<h:commandButton value="Click" > 
  <f:ajax execute="@form" render="time"/>
</h:commandButton>

In above example, when button is clicked an Ajax request is fired and the entire form will be processed on the server.

Attribute Description
execute Determines id’s of components to be processed on server
Possible values for render attribute Description
@all Process all components in view
@none Process no components
@this Process only this component, the component that triggered the Ajax request (default)
@form Process all components within this form (from which Ajax request was fired)

 

id’s Implicit id’s of components to be processed, space separated
EL Must resolve to Collection of Strings

 

More Examples
Let’s look at more examples using f:ajax tag.

If you have multiple controls that fire an Ajax request you could next f:ajax inside each one. Alternatively, you can also put f:ajax around those controls:

<f:ajax> 
  <h:panelGrid>  
    <h:selectBooleanCheckbox>
    <h:inputText>
    <h:commandButton>
  </h:panelGrid>
</f:ajax>  

From example above, f:ajax will be added to each control using their default Ajax events:

h:panelGrid no default behavior, so no Ajax event will be added
h:selectBooleanCheckbox onchange
h:inputTexzt onchange
h:commandButton onchange

We can also specify an event which would then be applied to children components:

<f:ajax event="click"> 
  <h:panelGrid>  
    <h:selectBooleanCheckbox>
    <h:inputText>
    <h:commandButton>
     <f:ajax event="focus"/>
    </h:commanButton>
  </h:panelGrid>
</f:ajax>  

In example above, onclick event will be added to panelGrid, inputText and commandButton. commandButton would also have onfocus event applied to it.

<f:ajax event="valueChange"> 
  <h:panelGrid>  
    <h:selectBooleanCheckbox>
    <h:inputText>
    <h:commandButton>
     <f:ajax event="focus"/>
    </h:commanButton>
  </h:panelGrid>
</f:ajax>

In example above we are applying the default valueChange event. It’s not possible to apply valueChange to panelGrid, so nothing will be applied to it. h:selectBooleanCheckbox and h:inputText will have valueChange applied to both. As valueChange is not a valid event for h:commanButton, the event will not be applied and h:commandButton will have only onfocus applied to it.

Hopefully this gives you a good introduction how to use f:ajax tag in JSF 2.

RichFaces
If you have been using RichFaces and specifically a4j:support tag then you might be wondering what’s going to happen to it? In RichFaces 4 (JSF 2 based) a4j:support is going to be renamed to a4j:ajax to match the standard tag name. a4j:ajax will use the standard f:ajax under the covers but will also provide numerous advanced features and attributes that you get today in RichFaces and which are not available in JSF 2. You will also have tags such as a4j:poll, a4j:jsFunction, a4j:outputPanel which are not available in JSF 2 and which give you more power and flexibility.

Read the original blog entry...

More Stories By Max Katz

Max Katz heads Developer Relations for Appery.io, a cloud-based mobile app platform. He loves trying out new and cool REST APIs in mobile apps. Max is the author of two books “Practical RichFaces” (Apress 2008, 2011), DZone MVB (Most Valuable Blogger), and is a frequent speaker at developer conferences. You can find out what Max is up to on his blog: http://maxkatz.org and Twitter: @maxkatz.

@ThingsExpo Stories
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
Amazon is pursuing new markets and disrupting industries at an incredible pace. Almost every industry seems to be in its crosshairs. Companies and industries that once thought they were safe are now worried about being “Amazoned.”. The new watch word should be “Be afraid. Be very afraid.” In his session 21st Cloud Expo, Chris Kocher, a co-founder of Grey Heron, will address questions such as: What new areas is Amazon disrupting? How are they doing this? Where are they likely to go? What are th...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.