JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







JSF Event Handling

Action Events Listener

Action Listeners can be implemented in 2 ways::-
  • Using "actionListener" attribute of the component tag
    • limit you to use only one listener for the component
  • Using <f:actionListener /> tag
    • permits you to include more than one event listeners.
Using "actionListener" attribute of the component tag

<h:commandButton id="cb1" value="#{ActionBean.buttonText}"
immediate="true" actionListener="#{ActionBean.processMyAction}"/>

  • You attach a listener to a command element with the actionListener attribute.
  • In the above example, command button is attached with an action listener method processMyAction() in ActionBean.java. 
  • When the button is clicked, the JSF implementation calls this action listener method.
  • You can perform any processing you need to inside the method. 
  • The method can have any name, must be public, return void, and accept an ActionEvent as its only parameter.

Using <f:actionListener /> tag

  • This tag is used to add a action listener to the component associated with the enclosing tag.
  • When user does an event on the component then this action takes place.
  • The ActionListener interface must be implemented to capture an ActionEvent.
  • This interface provides processAction() method which is called when the ActionEvent for which
    the ActionListener is registered occurs
public void processAction(ActionEvent event) throws AbortProcessingException

Example:-


actionevent.jsp
<%taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<html>
<head>
<title>JSF Action Listener Example</title>
</head>
<body>
<h3>JSF Action Listener Example</h3>
<f:view>
  <h:form>
    Please press the Button it.
     <h:commandButton id="cb1" value="#{ActionBean.buttonText}"
      immediate="true" actionListener="#{ActionBean.processMyAction}" />
  </h:form>
</f:view>
</body>
</html>

ActionBean.java
package myjsf;

import java.util.*;
import javax.faces.component.*;
import javax.faces.event.ActionEvent;

public class ActionBean {

  String value1;
  boolean disable;
  String buttonText = "Disable";

  public String getValue1() {
    return value1;
  }

  public void setValue1(String value1) {
    System.out.println("set value1: " + value1);
    this.value1 = value1;
  }

  public boolean isDisable() {
    return disable;
  }

  public void setDisable(boolean disable) {
    this.disable = disable;
  }

  public String getButtonText() {
    return buttonText;
  }

  public void setButtonText(String buttonText) {
    this.buttonText = buttonText;
  }

  /* Action listener method */
  public void processMyAction(ActionEvent event) {

    disable = !disable;
    System.out.println("disable: " + disable);
    if (buttonText.equals("Disable")) {
      buttonText = "Enable";
      System.out.println("buttonText: " + buttonText);
    else {
      buttonText = "Disable";
      System.out.println("buttonText: " + buttonText);
    }

  }
}


faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="1.2" xmlns="http://java.sun
.com/xml/ns/javaee"

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http:/
/java.sun.com/xml/ns/javaee http://java.
sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
>

  <managed-bean>
    <managed-bean-name>ActionBean</managed-bean-name>
    <managed-bean-class>myjsf.ActionBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
  </managed-bean>


</faces-config>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://j
ava.sun.com/xml/ns/javaee" 
xmlns:xsi="http:/
/www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation
=
"http://java.sun.com/xml/ns/javaee http://java.sun.com/
xml/ns/javaee/web-app_2_5.xsd"
>
   
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet
</servlet-
class>
        <load-on-startup>1</load-on-startup>
        </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>

  <welcome-file-list>
        <welcome-file>actionevent.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

Directory Structure



Output:-On deploying the application the action.jsp will be run as given below.


  • When the user click the button the ActionBean class's method processMyAction the event.
  •  In the processMyAction method we changing the label of the button from enable to disable as given below.



Download Source with lib
Download Source without lib


Value Change Events Listener

Value Change Listener can be implemented in 2 ways:
  • Using "valueChangeListener" attribute of the component tag
    • limit you to use only one listener for the component
  • Using <f:valueChangeListener /> tag
    • permits you to include more than one listeners.

<h:selectOneMenu id="songList" value="#{ValueChangeBean.selectedSong}"
valueChangeListener="#{ValueChangeBean.processMyValueChange}"
immediate="true" onchange="this.form.submit()">
<f:selectItems value="#{ValueChangeBean.songList}"/>
</h:selectOneMenu>


  • You attach a value change listener with the valueChangeListener attribute of the component.
  • In the above example, Single-select menu component is attached with an
    value change listener method processMyValueChange() in ValueChangeBean.java.
  •  When value is changed, the JSF implementation calls this value change listener method.
  • You can perform any processing you need to inside the method. 
  • The method can have any name, must be public, return void, and accept an ValueChangeEvent as its only parameter.
public void processMyValueChange(ValueChangeEvent vce){
songvalue = (Stringvce.getNewValue();
setSongDetail((String)detail.get(songvalue));
/*Render the response*/
FacesContext.getCurrentInstance().renderResponse();
}

Using <f:valueChangeListener /> tag

  • This tag is used to add a value change listener to the component associated with the enclosing tag.
  • When user does an event on the component then this action takes place. 
  • Value change event is fired when the user changes the input value.
  •  This event can be fired with any component which takes user input (select or input components).
  • The class which is registered with the component implements ValueChangeListener interface and
    implements the method processValueChange(). 
  • We write our logic of action in this method.
public void processValueChange(ValueChangeEvent event) throws AbortProcessingException

Example:
<h:inputText id="name" immediate="true" onchange="this.form.submit()"
required="true">
<f:valueChangeListener type="roseindia.MyValueChangeBean" />
</h:inputText>

MyValueChangeBean.java
import java.util.*;
import javax.faces.event.*;
import javax.faces.context.FacesContext;
public class MyValueChangeBean implements
ValueChangeListener 
{
public void processValueChange(ValueChangeEvent eventthrows
AbortProcessingException {
if (null != event.getNewValue())
FacesContext.getCurrentInstance().getExternalContext().
getSessionMap
().put("n
ame", event.getNewValue());
}
}
}



Example:-

select.jsp
<%taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<html>
<head>
<title>JSF Immediate Event Handling Example</title>
</head>
<body>
<f:view>



  <h1>JSF valueChangeListener example</h1>

  <h:form>

    <h:panelGrid columns="2">
      
        Selected country locale : 
        <h:inputText id="country" value="#{country.
localeCode}" 
size="20" />
          
        Select a country {method binding}
        <h:selectOneMenu value="#{country.localeCode}"
 
onchange="submit()"
        valueChangeListener="#{country.countryLocale
CodeChanged}"
>
        <f:selectItems value="#{country.countryInMap}" />
      </h:selectOneMenu>

      <ui:remove>
        <!-- comment above
valueChangeListener attribute and delete the
ui:remove tags 
for testing -->
        Select a country {ValueChangeListener class}
        <h:selectOneMenu value="#{country.localeCode}"
onchange="submit()">
          <f:valueChangeListener type="myjsf.Country
ValueListener" 
/>
          <f:selectItems value="#{country.countryInMap}" />
        </h:selectOneMenu>
      </ui:remove>

    </h:panelGrid>


  </h:form>

</f:view>
</body>
</html>

CountryBean.java
package myjsf;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;

public class CountryBean implements Serializable {

  private static Map<String, String> countries;

  private String localeCode = "en"// default value

  static {
    countries = new LinkedHashMap<String, String>();
    countries.put("United Kingdom""en")// label, value
    countries.put("French""fr");
    countries.put("German""de");
    countries.put("China""zh_CN");
  }

  public void countryLocaleCodeChanged(ValueChangeEvent e) {
    // assign new value to localeCode
    localeCode = e.getNewValue().toString();

  }

  public Map<String, String> getCountryInMap() {
    return this.countries;
  }

  public String getLocaleCode() {
    return localeCode;
  }

  public void setLocaleCode(String localeCode) {
    this.localeCode = localeCode;
  }

}


CountryValueListener.java
package myjsf;

import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;

public class CountryValueListener
 
implements ValueChangeListener {

  @Override
  public void processValueChange(ValueChangeEvent event)
      throws AbortProcessingException {

    // access country bean directly
    CountryBean country =
(CountryBeanFacesContext.getCurrentInstance()
        .getExternalContext()
.getSessionMap
().get("country");

    country.setLocaleCode(event.getNewValue().toString());

  }

}

faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="1.2" xmlns="http:
//java.sun.com/xml/ns/javaee"

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://
java.sun.com/xml/ns/javaee http:/
/java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
>

  <managed-bean>
    <managed-bean-name>country</managed-bean-name>
    <managed-bean-class>myjsf.CountryBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
  </managed-bean>

</faces-config>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://
java.sun.com/xml/ns/javaee" 
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation=
"http://java.sun.com/xml/ns/
javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
>
   
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>
javax.faces.webapp.FacesServlet</servlet-
class>
        <load-on-startup>1</load-on-startup>
        </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>

  <welcome-file-list>
        <welcome-file>select.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

Output:- On deploying the application the default page is shown as given below



  • When the user select the country local  the country will automatically change
  • When user select fr local the country will be french as given below.


Same here, when the local is de the country will be German.


Download Source with lib
Download Source without lib



Phase Listener

  • JSF life-cycle includes six phases and phase events are fired during the start and end of each phase.
  • We can capture phase events by defining a Phase Listener class.
  • The class should implement PhaseListener interface.
  • You can implement beforePhase() and afterPhase() methods according to the your need.