Sunday, February 13, 2011

Adding very basic AJAX Support to our JSF 2.x pages.

The last couple of days i tried to find out how to add AJAX support to my JSF UI components, so i can update them without refreshing the page... and also because other benefits of using AJAX.

A couple of guys from stackOverflow helped me out, and it was a complete success.

1-This is the selectOneMenu where the user picks a desired item
<h:selectOneMenu value="#{searchController.selectedCategory}">
<f:selectItems value="#{searchController.formatedCategories()}"></f:selectItems>
<!-- in f:ajax listener is not needed, but we can add it if we need it -->
<f:ajax event="change" execute="@this" listener="#{searchController.selectedCategoryMenu}"
render="menuType" />

2-This is how the new element that needs to be rendered looks like(The rendered attribute controls when each panel should be rendered)

<h:panelGroup id="menuType">
<h:panelGroup rendered="#{searchController.selectedCategory == 'cat1'}">
</h:panelGroup >
                         <h:panelGroup rendered="#{searchController.selectedCategory == 'cat2'}">
</h:panelGroup >
                        <h:panelGroup rendered="#{searchController.selectedCategory == 'cat3'}">
</h:panelGroup >

3(Optional)-Handling the change even in the managed bean

public void selectedCategoryMenu(AjaxBehaviorEvent e) { //...

This was my first experience combining JSF and AJAX. I was surprised how easy it was, a way easier than i thought.


  1. It would be very helpful if you add that this will only work in JSF 2.x :)


Share with your friends