Monday, 27 August 2012

Advantage of Using JSF ? Why JSF ?

1)Allowing resusable UI components to create new UI
2)Easy event handling and validation.
3)Moving application data to and from UI is easy.
4)Follow MVC architecture.
5)Third party faces support likes Richfaces,Icefaces etc...

Simple Example on JSF with Validation--

 ValidateEmail.java

package com.nik.testValidation
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class ValidatEmail  implements Validator

{
  public ValidatEmail()
  {
  }
  //Override the validate method 
   public void validate(FacesContext context, UIComponent component, Object   val)
      throws ValidatorException {
    if (null != val) {
      if (!(val instanceof String)) {
        throw new IllegalArgumentException(
            "The value must be a String");
      }
      String email = (String) val;
     
     
       if (email.indexOf("@") > 0 || email.) {
        throw new ValidatorException(
            new FacesMessage("Invalid Email Address"));
   
      }
    }
  }
   
}

TestBean.java

package com.nik.testValidation 
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

public class TestBean
{
String email;
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
}

JSF Code

<%@ page contentType="text/html"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
  <html>
    <head>
      <title>A Simple Validation Example</title>
    </head>
    <body>
      <h:form>

<h:inputText value="#{bean.email}" required="true"
                             validator="#{bean.validateEmail}" id="email"/>
   <h:message for="email"/>
</body>
</h:form>
</html>
</f:view>

Part of faces config

<managed-bean>
    <managed-bean-name>bean</managed-bean-name>
    <managed-bean-class>com.nik.testValidation.TestBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
  </managed-bean>

Jars Required

servlet-api.jar
jsp-api.jar
jstl API jar file
jsf-api.jar
commons-beanutils.jar
commons-collections.jar
commons-digester.jar
commons-logging.jar
JSTL standard.jar
jsf-impl.jar
Most of the developers and experties says primefaces...
http://primefaces.org/whyprimefaces.html