Integrating Ajax Support in JSF 2 using f:ajax

JavaServer Faces technology supports Ajax by using a built-in JavaScript resource library that is provided as part of the JavaServer Faces core libraries. f:ajax tag adds Ajax functionality to any UI component without additional coding and configuration.

f:ajax Attribute

– render
• The elements to redisplay on the page. Often h:outputText
– The target of the render must be inside the same h:form
– There are four special values: @this, @form, @none, and @all. However, these are more often used for the xecute attribute than the render attribute.
– execute
• The elements to send to server to process. Generally input elements such as h:inputText or h:selectOneMenu.
– There are 4 special values: @this, @form, @none, @all
• @this. The element enclosing f:ajax. Default.
• @form. The h:form enclosing f:ajax. Convenient if you have several input fields and don’t want to list each one in “render”. Also, input fields don’t need explicit ids when you use @form.
• @none. Nothing sent. Useful if the element you render changes values each time you evaluate it.
• @all. All JSF UI elements on page.
– event
• The DOM event to respond to (e.g., keyup, blur, change)
– onevent
• A JavaScript function to run when event is fired
-immediate
-A Boolean value that indicates whether inputs are to be processed early in the lifecycle.
-listener
-The name of the listener method that is called when a javax.faces.event.AjaxBehaviorEvent has been broadcast for the listener.
-The listener is not a property. If your method in the java bean is getTestBySubjectId(), put it like that (brackets are not needed) in the attribute.
<f:ajax event="change" render="tests" listener="#{test.getTestsBySubjectId}" ⁄>
-disabled
-A Boolean value that identifies the tag status. A value of true indicates that the Ajax behavior should not be rendered. A value of false indicates that the Ajax behavior should be rendered. The default value is false.
-onerror
-The name of the JavaScript function that handles errors.

To activate Ajax functionality, the web application must create an Ajax request and send it to the server. The server then processes the request.

The application uses the attributes of the f:ajax tag to create the Ajax request. The following sections displays an example of creating and sending an Ajax request using some of these attributes.

index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets">
    <h:head>
        <title>Ajax Example</title>
        <style>
            tfoot{
                text-align: center;
            }
            thead{
                background-color: darkgreen;
                color: white;
            }
            td{
                font-weight: bold;
            }
            .msg{
                font-size: small;
                color: green;
            }
        </style>
    </h:head>
    <h:body>
        <h:panelGrid id="panelmain" columns="2" border="1">
            <h:form>
                <h:panelGrid id="panel1" columns="1" border="1" 
                             cellpadding="5" cellspacing="1">
                    <f:facet name="header">
                        <h:outputText value="Display Current Time"/>
                    </f:facet>
                    <h:commandButton value="Update Time" action="nothing">
                        <f:ajax render="timeResult"/>
                    </h:commandButton>
                    <h:outputText value="#{sumBean.time}" id="timeResult"/>
                </h:panelGrid>
            </h:form>
            <h:form>
                <h:panelGrid id="panel2" columns="2" border="1" 
                             cellpadding="5" cellspacing="1">
                    <f:facet name="header">
                        <h:outputText value="Display Sum of Two Numbers"/>
                    </f:facet>
                    <h:outputLabel value="First number:"/>
                    <h:inputText value="#{sumBean.num1}"/>
                    <h:outputLabel value="Second number:"/>
                    <h:inputText value="#{sumBean.num2}"/>
                    <h:outputLabel value="Sum:"/> 
                    <h:outputText value="#{sumBean.sum}" id="sumResult"/>
                    <f:facet name="footer">
                        <h:commandButton value="Compute Sum">
                            <f:ajax execute="@form" render="sumResult"/>
                        </h:commandButton>
                    </f:facet>
                </h:panelGrid>
            </h:form>
            </h:panelGrid>
            <br/>
            <h:form>
                <h:panelGrid id="panel3" columns="2" border="1" 
                             cellpadding="5" cellspacing="1">
                    <f:facet name="header">
                        <h:outputText value="Update User Info"/>
                    </f:facet>
                    <h:outputLabel value="Select User:"/>
                    <h:selectOneMenu value="#{userBean.selectedname}" id="ulist">
                        <f:selectItems value="#{userBean.fullName}"/>
                        <f:ajax event="change" render="fname lname email uname pass reg" listener="#{userBean.fullInfo}"/>
                    </h:selectOneMenu>
                    <h:outputLabel value="First Name:"/>
                    <h:inputText value="#{userBean.first_name}" id="fname"/>
                    <h:outputLabel value="Last Name:"/>
                    <h:inputText value="#{userBean.last_name}" id="lname"/>
                    <h:outputLabel value="Email:"/>
                    <h:inputText value="#{userBean.email}" id="email"/>
                    <h:outputLabel value="User Name:"/>
                    <h:inputText value="#{userBean.uname}" id="uname" readonly="true"/>
                    <h:outputLabel value="Password:"/>
                    <h:inputSecret value="#{userBean.pass}" id="pass"/>
                    <h:outputLabel value="Registration Date:"/>
                    <h:inputText value="#{userBean.regdate}" id="reg"/> 
                    <f:facet name="footer">
                        <h:outputLabel value="#{userBean.msg}" id="msg" styleClass="msg"/>
                        <h:commandButton value="Update Info" action="#{userBean.updateuser}">
                            <f:ajax render="msg ulist" execute="@form"/>
                        </h:commandButton>
                    </f:facet>
                </h:panelGrid>
            </h:form>        
    </h:body>
</html>

ManagedBean
SumBean.java

package com.example.javaknowledge;

import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;


@ManagedBean
@SessionScoped
public class SumBean {
private double num1, num2;

    public double getNum1() {
        return num1;
    }

    public void setNum1(double num1) {
        this.num1 = num1;
    }

    public double getNum2() {
        return num2;
    }

    public void setNum2(double num2) {
        this.num2 = num2;
    }
    public double getSum() {
    return(num1 + num2);
  }
    
    public Date getTime() {
    return(new Date());
  }

}

UserBean.java

package com.example.javaknowledge;

import com.example.javaknowledge.dao.Database;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.SelectItem;

@ManagedBean
@SessionScoped
public class UserBean {

    private String first_name, last_name, email, uname, pass, regdate, selectedname, msg="";

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public String getRegdate() {
        return regdate;
    }

    public void setRegdate(String regdate) {
        this.regdate = regdate;
    }

    public String getSelectedname() {
        return selectedname;
    }

    public void setSelectedname(String selectedname) {
        this.selectedname = selectedname;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<SelectItem> getFullName() {
        List<SelectItem> retVal = new ArrayList<SelectItem>();

        try {
            Connection con = Database.getConnection();
            Statement st = con.createStatement();
            ResultSet rs = null;
            String myQuery = "SELECT concat(first_name, ' ', last_name) as name FROM members";

            rs = st.executeQuery(myQuery);
            while (rs.next()) {
                retVal.add(new SelectItem(rs.getString("name")));
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return retVal;
    }

    public void fullInfo() {

        Connection con = null;
        Statement st = null;
        ResultSet rs2 = null;

        try {
            con = Database.getConnection();
            st = con.createStatement();
            rs2 = st.executeQuery("select * from members where concat(first_name, ' ', last_name)='" + selectedname + "'");
            while (rs2.next()) {
                setFirst_name(rs2.getString("first_name"));
                setLast_name(rs2.getString("last_name"));
                setUname(rs2.getString("uname"));
                setEmail(rs2.getString("email"));
                setPass(rs2.getString("pass"));
                setRegdate(rs2.getString("regdate"));

            }
        } catch (Exception e) {
            System.out.println("Insert Error" + e.getMessage());
        }
    }

    public void updateuser() {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            con = Database.getConnection();
            st = con.createStatement();
            int update = st.executeUpdate("update members set first_name='" + first_name + "',last_name='" + last_name + "' ,email='" + email + "',pass='" + pass + "' where uname='" + uname + "'");
            if (update > 0) {
                msg = "Member Update Successful";
            } else {
                msg = "Member Update Fail!";
            }

        } catch (Exception e) {
            System.out.println("Insert Error" + e.getMessage());
        }

    }
}

Screenshot:

jsf_ajax_example

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

6,742` Total Views

Leave a Reply

Your email address will not be published. Required fields are marked *


5 − two =