Showing posts with label JSF. Show all posts
Showing posts with label JSF. Show all posts

Saturday, February 26, 2011

What is a Framework?

Framework is special software that is capable of developing applications based on certain architecture having ability to generate certain logics of application development dynamically.

Thursday, October 21, 2010

Problems if <h:form> is not used in JSF

I will be explainingpProblems if <h:form> is not used in JSF with a simple example.
1)I created a new project in JSF and added comman button to the jsp page  without using <h:form&gt tag
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<%--
    This file is an entry point for JavaServer Faces application.
--%>
<f:view>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
            <title>JSP Page</title>
        </head>
        <body>
            <h1><h:outputText value="JavaServer Faces"/></h1>
                <h:commandButton id="bt_SAVE"  value="Save" action="#{test.saveProcess}" />
        </body>
    </html>
</f:view>

2) Made necessary mapping in faces-config.xml.
<managed-bean>
        <managed-bean-name>test</managed-bean-name>
        <managed-bean-class>bean.test</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean> 


3) Created package bean and added test class to the bean package
 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

/**
 *
 * @author subin_s
 */
public class test {

    public void saveProcess() {
        System.out.println("Debug inside saveProcess");
    }
}



Now if you run the project and click on save button  saveProcess method will not be executed you may think why button is not working ,problem is  you have not given <h:form> tag.

Tuesday, October 12, 2010

Making RichCalender Editable

Few days back we i have posted  Server Side Date Validator Today we will discuss  topic how to manually enter date in  rich calender only you need to do is set enale ManualInput to true  in jsp file as shown below.
<rich:calendar id="dc_FROM_DATE" ajaxSingle="true" enableManualInput="true" binding="#{checkUserRequest.dc_FROM_DATE}" inputStyle="font-size:10pt;width:100px;height:25px" datePattern="dd-MM-yyyy">
</rich:calendar>



Sunday, October 3, 2010

Problems in using Value binding in JSF

Today we will see one of the major problem while using value binding in JSF and solution for it.Suppose if we have two fields subject1 and subject2 .In  focus lost of subject2 if we try to get value of subject1 using get method it will give you null value because values are not updated using valuebinding reason for this is while we use value biding  value will be updated in Update Model Value Phase  and value change listener is called  before Update Model Phase.

How to overcome this problem
        PhaseId phaseId = evt.getPhaseId();
        if (phaseId.equals(PhaseId.ANY_PHASE)) {
            evt.setPhaseId(PhaseId.UPDATE_MODEL_VALUES);
            evt.queue();
            return;
        }

Place the above code at the beginning of the method, So automatically updates all the values of the submitted form.

Sunday, September 26, 2010

Tags in JSF

Basically there are two kinds of  tags in JSF.
JSF Core & HTML Tags
Today we will see different  attributes in JSF HTML and Core Tags

JSF HTML Tags :

  • column                              creates column in a dataTable
  • commandButton                creates button
  • commandLink                   creates link that acts like a pushbutton
  • dataTable                         creates a  table control
  • form                                 creates a form
  • graphicImage                    displays an image
  • inputHidden                      creates hidden field
  • inputSecret                       creates input control for password
  • inputText                          creates  text input control (single line)
  • inputTextarea                    creates  text input control (multiline)
  • message                           displays the most recent message for a component
  • messages                          displays all messages
  • outputFormat                    creates  outputText, but formats compound messages
  • outputLabel                      creates label 
  • outputLink                        creates anchor
  • outputText                        creates single line text output
  • panelGrid                         creates html table with specified number of columns
  • panelGroup                      used to group other components where the specification requires one child element
  • selectBooleanCheckbox   creates checkbox
  • selectManyCheckbox       creates set of checkboxes
  • selectManyListbox           creates multiselect listbox
  • selectManyMenu              creates multiselect menu
  • selectOneListbox              creates single select listbox
  • selectOneMenu                creates single select menu
  • selectOneRadio                creates set of radio buttons 

JSF CORE Tags: 

  • f :view                                 Creates the top-level view
  • f:subview                             Creates a subview of a view
  • f:attribute           Adds an attribute  to a component
  • f:param                                Constructs a parameter component
  • f:converter            Adds an arbitrary converter to a component
  • f:converterDateTime      Adds a datetime converter to a component
  • f:converterNumber      Adds a number converter to a component
  • f:actionListener          Adds an action listener to a component
  • f:valueChangeListener     Adds a valuechange listener to a component
  • f:validator             Adds a validator to a component
  • f:validateDoubleRange    Validates a double range for a component’s value
  • f:validateLength         Validates the length of a component’s value
  • f:validateLongRange      Validates a long range for a component’s value
  • f:facet                 Adds a facet to a component
  • f:loadBundle            Loads a resource bundle, stores properties as a Map
  • f:selectitems            Specifies items for a select one or select many component
  • f:selectitem             Specifies an item for a select one or select many component 
  • f:verbatim              Adds markup to a JSF page

Thursday, September 23, 2010

Server Side Numeric Validator

Few days back i discussed JavaScript function to restrict input to numeric.
Today we will see Server Side Numeric Validator for JSF you can also see AlphaNumeric Validator in JSF  and Server Side Date Validator 
Steps for creating Numeric Validator
1) Create numeric.jsp file
numeric.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="jc" uri="http://jsf-components" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%--
This file is an entry point for JavaServer Faces application.
--%>
<f:view>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>JSP Page</title>
</head>
<body>
<h:form >
<jc:AlertMessage />
<h:panelGroup>
<h:outputText id="lb_No"value="Label.:" />
<h:inputText id="tf_NO" autocomplete="off" binding="#{numeric.tf_NO}" >
<f:validator validatorId="onlyNum"/>
<f:validateLength minimum="1" maximum="6"/>
</h:inputText>
<h:commandButton id="cb_save" value="Save" action="#{numeric.bt_SAVEActionPerformed}" > </h:commandButton>
</h:panelGroup>
</h:form>
</body>
</html>
</f:view>
------------------------------------------------------------------------------------------------------------------------------
2) Create a package subin and inside subin package create two javaclass files (Numeric.java and OnlyNumericValidator.java)
Numeric.java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package subin;

import javax.faces.component.html.HtmlInputText;

/**
*
* @author SubinSuresh
*/
public class Numeric {

public void bt_SAVEActionPerformed() {
System.out.println("Debug bt_SAVEActionPerformed");
}
private HtmlInputText tf_NO =new HtmlInputText();

/**
* @return the tf_NO
*/
public HtmlInputText getTf_NO() {
return tf_NO;
}

/**
* @param tf_NO the tf_NO to set
*/
public void setTf_NO(HtmlInputText tf_NO) {
this.tf_NO = tf_NO;
}
}
--------------------------------------------------------------------------------------------------------------------------
OnlyNumericValidator.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package subin;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
*
* @author SubinSuresh
*/
public class OnlyNumericValidator implements Validator {

public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
String compValue = null;
boolean flag = false;
if (component != null && component instanceof HtmlInputText) {
compValue = (String) ((HtmlInputText) component).getSubmittedValue();
} else if (component != null && component instanceof HtmlInputTextarea) {
compValue = (String) ((HtmlInputTextarea) component).getSubmittedValue();
}
if (compValue != null && !compValue.equalsIgnoreCase("")) {
flag = compValue.matches("[0-9]*");
if (!flag) {
if (component instanceof HtmlInputText) {
((HtmlInputText) component).setTitle("Only numbers are allowed here");
((HtmlInputText) component).setSubmittedValue("");
} else if (component instanceof HtmlInputTextarea) {
((HtmlInputTextarea) component).setTitle("Only numbers are allowed here");
} else if (component instanceof HtmlSelectOneMenu) {
((HtmlSelectOneMenu) component).setTitle("Page got some un-conditional Data");
}
throw new ValidatorException(new FacesMessage("Only numbers are allowed here"));
}
}
}
}
-------------------------------------------------------------------------------------------------------------------------
3)Mapping in faces-config.xml file
<managed-bean>
<managed-bean-name>numeric</managed-bean-name>
<managed-bean-class>subin.Numeric</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<validator>
<validator-id>onlyNum</validator-id>
<validator-class>subin.OnlyNumericValidator</validator-class>
</validator>


JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

Tuesday, September 21, 2010

Server Side Address Validator

In my last post i wrote  Server Side Date Validator today we will see Server Side Address Validator
Steps for creating Server Side Address Validator
1) Create address.jsp file
address.jsp

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="jc" uri="http://jsf-components" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%--
This file is an entry point for JavaServer Faces application.
--%>
<f:view>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>JSP Page</title>
</head>
<body>
<h:form >
<jc:AlertMessage />
<h:panelGroup>
<h:outputText id="lb_No"value="Address.:" />
<h:inputText id="tf_NO" autocomplete="off" binding="#{address.tf_NO}" >
<f:validator validatorId="addressValidator"/>
<f:validateLength minimum="10" maximum="30"/>
</h:inputText>
<h:commandButton id="cb_save" value="Save" action="#{address.bt_SAVEActionPerformed}" > </h:commandButton>
</h:panelGroup>
</h:form>
</body>
</html>
</f:view>
-------------------------------------------------------------------------------------------------------
2) Create a package subin and inside subin package create two javaclass files (Address.java and AddressValidator.java)
Address.java
 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package subin;

import javax.faces.component.html.HtmlInputText;

/**
 *
 * @author SubinSuresh
 */
public class Address {

    public void bt_SAVEActionPerformed() {
        System.out.println("Debug bt_SAVEActionPerformed");
    }
    private HtmlInputText tf_NO = new HtmlInputText();

    /**
     * @return the tf_NO
     */
    public HtmlInputText getTf_NO() {
        return tf_NO;
    }
    /**
     * @param tf_NO the tf_NO to set
     */
    public void setTf_NO(HtmlInputText tf_NO) {
        this.tf_NO = tf_NO;
    }
}
-------------------------------------------------------------------------------------------------------
AddressValidator.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package subin;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author subin_s
 */
public class AddressValidator implements Validator {

    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String compValue = null;
        boolean flag = false;
        if (component != null && component instanceof HtmlInputText) {
            compValue = (String) ((HtmlInputText) component).getSubmittedValue();
        } else if (component != null && component instanceof HtmlInputTextarea) {
            compValue = (String) ((HtmlInputTextarea) component).getSubmittedValue();
        }
        if (compValue != null && !compValue.equalsIgnoreCase("")) {
            flag = compValue.matches("[a-zA-Z 0-9/.&-,]*");
        }
        if (!flag) {
            if (component instanceof HtmlInputText) {
                ((HtmlInputText) component).setTitle("No special symbols are allowed here");
            } else if (component instanceof HtmlInputTextarea) {
                ((HtmlInputTextarea) component).setTitle("No special symbols are allowed here");
            } else if (component instanceof HtmlSelectOneMenu) {
                ((HtmlSelectOneMenu) component).setTitle("Page got some un-conditional Data");
            }
            throw new ValidatorException(new FacesMessage("Characters you have entered are not allowed here"));
        }
    }
}
-----------------------------------------------------------------------------------------------------------
3)Mapping in faces-config.xml file
<managed-bean>
<managed-bean-name>address</managed-bean-name>
<managed-bean-class>subin.Address</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<validator>
<validator-id>addressValidator</validator-id>
<validator-class>subin.AddressValidator</validator-class>
</validator>

 Note: In  AddressValidator.java we can allow any number character by keeping in regular expression compValue.matches("[a-zA-Z 0-9/.&-,]*")
 

Monday, September 20, 2010

Server Side Date Validator

Steps for creating ServerSide Date Validator
1) Create datevalidate.jsp file
datevalidate.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="jc" uri="http://jsf-components" %>
<%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<%--
This file is an entry point for JavaServer Faces application.
--%>
<f:view>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>JSP Page</title>
</head>
<body>
<h:form >
<jc:AlertMessage />
<h:panelGroup>
<h:outputText id="lb_No"value="EnterDate.:" />
<rich:calendar id="dc_SOLD_ON" binding="#{validate.dc_SOLD_ON}" inputStyle="font-size:10pt;width:55px;height:20px"datePattern="dd-MM-yyyy" >
<f:validator validatorId="dateValidator"/>
</rich:calendar>
<h:commandButton id="cb_save" value="Save" action="#{validate.bt_SAVEActionPerformed}" > </h:commandButton>
</h:panelGroup>
</h:form>
</body>
</html>
</f:view>
---------------------------------------------------------------------------------------------------------
2) Create a package subin and inside subin package create two javaclass files (DateValidate.java and DateValidator.java)
DateValidate.java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package subin;

import org.richfaces.component.html.HtmlCalendar;
/**
*
* @author SubinSuresh
*/
public class DateValidate {
public void bt_SAVEActionPerformed() {
System.out.println("Debug bt_SAVEActionPerformed");
}
private HtmlCalendar dc_SOLD_ON= new HtmlCalendar();
/**
* @return the dc_SOLD_ON
*/
public HtmlCalendar getDc_SOLD_ON() {
return dc_SOLD_ON;
}
/**
* @param dc_SOLD_ON the dc_SOLD_ON to set
*/
public void setDc_SOLD_ON(HtmlCalendar dc_SOLD_ON) {
this.dc_SOLD_ON = dc_SOLD_ON;
}
}
--------------------------------------------------------------------------------------------------------------------------
DateValidator.java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package subin;

import java.util.Date;
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;
import org.richfaces.component.html.HtmlCalendar;

/**
*
* @author SubinSuresh
*/
public class DateValidator implements Validator {

public String DATE_FORMAT = "dd-MM-yyyy";
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
System.out.println("Debug Inside DateValidator" + ((HtmlCalendar) component).getSubmittedValue());
String date = (String) ((HtmlCalendar) component).getSubmittedValue();
try {
Date dt = converStringToDate(date);
System.out.println("Debug Inside dt " + dt);
} catch (Exception ex) {
ex.printStackTrace();
((HtmlCalendar) component).setSubmittedValue("");
throw new ValidatorException(new FacesMessage("Invalid Date"));
}
}
/**
* Convert String to Date
* @param dateString
* @return
*/
public Date converStringToDate(String dateString) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
java.util.Date dt = null;
try {
dt = sdf.parse(dateString);
} catch (java.text.ParseException p) {
System.out.println(p.toString());
}
return dt;
}
}
------------------------------------------------------------------------------------------------------------------
3)Mapping in faces-config.xml file
<managed-bean>
<managed-bean-name>validate</managed-bean-name>
<managed-bean-class>subin.DateValidate</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<validator>
<validator-id>dateValidator</validator-id>
<validator-class>subin.DateValidator</validator-class>
</validator>


Sunday, September 19, 2010

Scrollable datatable in JSF

Today we will see one of  the important and useful features of  JSF Framework Scrollable datatable.
This is very useful to improve look of you web page.When we click on DisplayDetails button table will be populated.
Steps for creating Scrollable datatable.
1)Create datatable.jsp file
datatable.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%--
This file is an entry point for JavaServer Faces application.
--%>
<f:view>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>JSP Page</title>
</head>
<body>
<h:form >
<jc:AlertMessage />
<h:panelGroup>
<h:commandButton id="cb_save" value="Display Details" style="position:absolute;left:490px;" action="#{scroll.bt_SAVEActionPerformed}" > </h:commandButton>
</h:panelGroup>
<h:panelGroup id="pn_DETAILS_GRP" style="overflow:auto;position:absolute;top:70px;left:400px;width:300px;height:150px;solid black">
<h:dataTable id="tb_USER_DETAILS" border="1" var="userDtls" value="#{scroll.userTable}" style="width:300px;height:150px">
<h:column id="SlNo">
<f:facet name="header">
<h:outputText value="Sl No" style="font-size:10pt" ></h:outputText>
</f:facet>
<h:outputText value="#{userDtls.userSlNo}" style="font-size:8pt"/>
</h:column>
<h:column id="firstName">
<f:facet name="header">
<h:outputText value="First Name" style="font-size:10pt"/>
</f:facet>
<h:outputText value="#{userDtls.userFirst_Name}" style="font-size:8pt"/>
</h:column>
<h:column id="lastName">
<f:facet name="header">
<h:outputText value="Last Name" style="font-size:10pt"/>
</f:facet>
<h:outputText value="#{userDtls.userLast_Name}" style="font-size:8pt"/>
</h:column>
</h:dataTable>
</h:panelGroup>
</h:form>
</body>
</html>
</f:view>
----------------------------------------------------------------------------------------------------------------------------
2) Create a package subin and inside subin package create javaclass file DataTable.java
DataTable.java
/*
* To change this template, choose Tools
Templates
* and open the template in the editor.
*/
package subin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
*
* @author SubinSuresh
*/
public class DataTable {

private HashMap userDtlsMap = new HashMap();
private List userTable = new ArrayList();

public void bt_SAVEActionPerformed() {
System.out.println("Debug bt_SAVEActionPerformed");
for (int i = 0; i < 15; i++) {
userDtlsMap = new HashMap();
System.out.println("Debug i"+i);
userDtlsMap.put("userSlNo", "" + (i + 1));
userDtlsMap.put("userFirst_Name", "subin");
userDtlsMap.put("userLast_Name", "suresh");
userTable.add(userDtlsMap);
}
}

/**
* @return the userDtlsMap
*/
public HashMap getUserDtlsMap() {
return userDtlsMap;
}

/**
* @param userDtlsMap the userDtlsMap to set
*/
public void setUserDtlsMap(HashMap userDtlsMap) {
this.userDtlsMap = userDtlsMap;
}
/**
* @return the userTable
*/

public List getUserTable() {
return userTable;
}

/**
* @param userTable the userTable to set
*/

public void setUserTable(List userTable) {
this.userTable = userTable;
}
}

-------------------------------------------------------------------------------------------------------------------
3)Mapping in faces-config.xml file
<managed-bean>
<managed-bean-name>scroll</managed-bean-name>
<managed-bean-class>subin.DataTable</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>



JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

Saturday, September 18, 2010

AlphaNumeric Validator in JSF

Few days back i discussed Javascript function to restrict special characters,
Today we will see serverside alphanumeric validator for Jsf.
This serverside validator is used to validate and restrict special character entering into database.

Steps for creating AlphaNumeric Validator
1) Create AlphaNumeric.jsp file
AlphaNumeric.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="jc" uri="http://jsf-components" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%--
This file is an entry point for JavaServer Faces application.
--%>
<f:view>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>JSP Page</title>
</head>
<body>
<h:form >
<jc:AlertMessage />
<h:panelGroup>
<h:outputText id="lb_No"value="Label.:" />
<h:inputText id="tf_NO" autocomplete="off" binding="#{alphanumeric.tf_NO}" >
<f:validateLength maximum="6" minimum="1"/>
<f:validator validatorId="alphaNumeric"/>
</h:inputText>
<h:commandButton id="cb_save" value="Save" action="#{alphanumeric.bt_SAVEActionPerformed}" > </h:commandButton>
</h:panelGroup>
</h:form>
</body>
</html>
</f:view>
------------------------------------------------------------------------------------------------------------------------------
2) Create a package subin and inside subin package create two javaclass files (AlphaNumeric.java and AlphaNumericValidator.java)
AlphaNumeric.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package subin;
import javax.faces.component.html.HtmlInputText;
/**
*
* @author SubinSuresh
*/
public class AlphaNumeric {

public void bt_SAVEActionPerformed() {
System.out.println("Debug bt_SAVEActionPerformed");
}
private HtmlInputText tf_NO =new HtmlInputText();

/**
* @return the tf_NO
*/
public HtmlInputText getTf_NO() {
return tf_NO;
}

/**
* @param tf_NO the tf_NO to set
*/
public void setTf_NO(HtmlInputText tf_NO) {
this.tf_NO = tf_NO;
}
}
--------------------------------------------------------------------------------------------------------------------------
AlphaNumericValidator.java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package subin;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
*
* @author subin
*/
public class AlphaNumericValidator implements Validator {

public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
String compValue = null;
boolean flag = false;
if (component != null && component instanceof HtmlInputText) {
compValue = (String) ((HtmlInputText) component).getSubmittedValue();
} else if (component != null && component instanceof HtmlInputTextarea) {
compValue = (String) ((HtmlInputTextarea) component).getSubmittedValue();
}
if (compValue != null && !compValue.equalsIgnoreCase("")) {
flag = compValue.matches("[a-zA-Z0-9]*");
}
if (!flag) {
if (component instanceof HtmlInputText) {
((HtmlInputText) component).setTitle("No special symbols are allowed here");
} else if (component instanceof HtmlInputTextarea) {
((HtmlInputTextarea) component).setTitle("No special symbols are allowed here");
} else if (component instanceof HtmlSelectOneMenu) {
((HtmlSelectOneMenu) component).setTitle("Page got some un-conditional Data");
}
throw new ValidatorException(new FacesMessage("No special symbols are allowed"));
}
}
}
-------------------------------------------------------------------------------------------------------------------------
3)Mapping in faces-config.xml file

<managed-bean>
<managed-bean-name>alphanumeric</managed-bean-name>
<managed-bean-class>subin.AlphaNumeric</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<validator>
<validator-id>alphaNumeric</validator-id>
<validator-class>subin.AlphaNumericValidator</validator-class>
</validator>

When we enter some specialcharacter in textbox and click on save button it shows a popup alert No special symbols are allowed.
Note:This validation occur before entering action method of save button i.e why "Debug bt_SAVEActionPerformed" is not printed in the output console.


JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

Thursday, September 16, 2010

Reading Postgres Database Connection from properties file using ResourceBundle class

DB.java

import java.sql.*;
import java.util.*;

public class DB
{
static ResourceBundle rb = ResourceBundle.getBundle("myapp", Locale.getDefault());

public static Connection getConnection ()
{
Connection conn = null;

try {
Class.forName (rb.getString("dbDriver"));
conn = DriverManager.getConnection(rb.getString("dbURL"), rb.getString("Username"), rb.getString("Password"));
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}


public static void closeConnection (Connection conn)
{

try {
if (conn !=null)
{
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
--------------------------------------------------------------------------------

CallDB.java

import java.sql.*;
import java.util.*;


public class CallDB
{
static ResourceBundle rb = ResourceBundle.getBundle("sql", Locale.getDefault());

public static void loadAndShowResultSet()
{
Connection conn = null;
Statement stmt = null;

try {
conn = DB.getConnection ();
stmt = conn.createStatement();

ResultSet rset = stmt.executeQuery(rb.getString("sql.query"));
while (rset.next())
{
System.out.println (rset.getString(1));
}

}
catch (Exception e) {
e.printStackTrace();
}
finally
{
try {
stmt.close();
DB.closeConnection (conn);
}
catch (Exception e) {
e.printStackTrace();
}
}
}

public static void main(String args[])
{
try {
CallDB callDB= new CallDB();
callDB.loadAndShowResultSet();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

------------------------------------------------------
myapp.properties

dbDriver=org.postgresql.Driver
dbURL=jdbc:postgresql://localhost:5432/dbname
Username=postgres
Password=postgres

--------------------------------------------------------

sql.properties

sql.query=select first_name from username;

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

Saturday, September 4, 2010

Navigation Rule in JSF

The JavaServer Faces (JSF) Navigation Framework provides navigation rules that allow you to define navigation from view to view (mostly JSP pages) in a Web application. These navigation rules are defined in JSF configuration files along with other definitions for a JSF application. Usually, this file is named faces-config.xml. 
Here we will see  Navigation Rule Example in JSF
First create two jsp's login.jsp and home.jsp
In login.jsp type the below code
<h:outputLabel id="lb_USR_NAME" value="UserName:" styleClass="label"/>
<h:inputText  id="tf_USR_NAME"  autocomplete="off"  value="#{userlogin.tf_USR_NAME}"   />
 <h:outputLabel id="lb_PASS" value="Password:" styleClass="label"/>
 <h:inputText  id="tf_PASS" autocomplete="off" value="#{userlogin.tf_PASS}" />
<h:commandButton id="cb_login" value="Login" action="#{userlogin.submit}"/>
In home.jsp
 <body>
         <h1>Welcome to homepage </h1>
    </body>
In login.java paste the below code login.java is inside main package
package client.gui.main;


/**
 *
 * @author Subin Suresh
 */
public class Login{

  public String submit(){
 String status = null;
String userName = (String) getTf_USR_NAME().toString();
        String passWord = (String) getTf_PASS().toString();
 if (((userName.equals("subin"))) && ((passWord.equals("subin")))) {
status = "sucess";
}else{
status = "failure";
}

}

}
In faces-config.xml paste below code  

<managed-bean>
        <managed-bean-name>userlogin</managed-bean-name>
        <managed-bean-class>client.gui.main.Login</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>

 <!-- ========== Navigation Rules Start  ========== -->
    <navigation-rule>
        <description>Navigation Rule for Login page</description>
        <from-view-id>/login.jsp</from-view-id>
        <navigation-case>
            <description>Redirects the page on "SUCCESS" outcome from login.bt_LOGINActionPerformed()</description>
            <from-action>#{userlogin.submit}</from-action>
            <from-outcome>sucess</from-outcome>
            <to-view-id>/home.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <description>Redirects the page on "Failure" outcome from login.bt_LOGINActionPerformed()</description>
            <from-action>#{userlogin.submit}</from-action>
            <from-outcome>failure</from-outcome>
            <to-view-id>/login.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
  <!-- =========== Navigation Rules Ends ========== -->



JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

Wednesday, August 25, 2010

PopUp AlertMessagebox for JSF

In my last post i have written Javascript function for email validation. Today i will be discussing  PopUp AlertMessagebox for JSF
When we develop websites we often have to display to user some alerts if user makes some mistakes
In such cases we can use jsf-components.
Steps to implementation
1) Download  jsf-components.jar..
2)Include this taglib <%@taglib prefix="jc" uri="http://jsf-components" %>
and also add<jc:AlertMessage /> tag after <h:form>tag
3)Add below method .If you are having a java class for common methods
it's better to add this method there for reuseibility
/**
* Add a Message to the Faces Context
* @param msg
*/
public static void showMessage(String msg) {
msg = "" + msg;
FacesMessage fm = new FacesMessage(msg);
FacesContext.getCurrentInstance().addMessage(msg, fm);
}
4)Use it
configure managebean in faces-config.xml
<managed-bean>
<managed-bean-name>userlogin</managed-bean-name>
<managed-bean-class>client.gui.main.Login</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

In JSP paste the below code
<h:outputLabel id="lb_USR_NAME" value="UserName:" styleClass="label"/>
<h:inputText id="tf_USR_NAME" autocomplete="off" value="#{userlogin.tf_USR_NAME}" />
<h:outputLabel id="lb_PASS" value="Password:" styleClass="label"/>
<h:inputText id="tf_PASS" autocomplete="off" value="#{userlogin.tf_PASS}" />
<h:commandButton id="cb_login" value="Login" action="#{userlogin.submit}"/>

In Java Class paste the below code
package client.gui.main;
/**
*
* @author Subin Suresh
*/
public class Login{
public String submit(){
String status = null;
String userName = (String) getTf_USR_NAME().toString();
String passWord = (String) getTf_PASS().toString();
if (((userName.equals("subin"))) && ((passWord.equals("subin")))) {
showMessage("UserName and Password Does not Matches .");
status = "failure";
}else{
status = "success";
}
return status; 
}
}

Download  jsf-components.jar..

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

Monday, August 23, 2010

ServerSide Email Validator

In my last post i have written Javascript function for email validation. In this i will be discussing about ServerSide Email Validator. For application to be safe it is necessary to have both client and server side validators.
Steps for implementing ServerSide Email Validator
1. In jsp define the email component in the following way
  <h:outputLabel id="lb_MAIL_ID" value="Mail ID:" styleClass="label"/>
<h:inputText id="tf_MAIL_ID" autocomplete="off" value="#{userlogin.tf_MAIL_ID}" />
2. In java class get email component value and apply serverside email validator for it as shown below

/*
* Getting the tf_MAIL_ID component value
*/
String emailId = (String) getTf_MAIL_ID().toString();
 if (emailId == null || !emailId.matches("^[A-z0-9_\\-\\.]+[@][A-z0-9_\\-]+([.][A-z0-9_\\-]+)+[A-z]{2,4}")) {
             System.out.println("Please enter Valid Email-Id");
        }

Instead of  using  System.out.println you can use PopUp AlertMessagebox for JSF  as it clear idea for the user who is using it. 

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Sunday, August 22, 2010

Deploying a war file(project) in Tomcat web server in Windows

Steps for Deploying a project in Tomcat web server in Windows

1.Open the NetBeans IDE
2.Open the project
3.Right click on the project in projects tab
4.Click on the 'clean and build' option
5.Click on 'Deploy' option
6.Now go to folder where your project is reside in your system
say D:\projects\nameoftheproject\dist folder
7.You can find the nameoftheproject.war file in dist folder
8.Open the tomcat foder in your system say c:\program files\ApacheSoftwareFoundation\Tomcat6.0
9.Open the logs folder
10.Delete all the log files which are present upto now
11.Open the work folder--->catalina--->localhost
12.Delete all the folders(all these folders are temporary folders created by the tomcat)
13.Open the webapps folder
14.Delete the war file and project folder(if it is already present, before this you need to stop the tomcat server)
15.Copy the war file and paste in the c:\program files\ApacheSoftwareFoundation\Tomcat6.0\webapps folder
16.Run the project in the firefox with appropriate url say:http://localhost:8080/nameoftheproject

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Tuesday, August 17, 2010

Bean Scopes in JSF

There are three types of scopes for the JSF backing beans.

   1. Request Scope
   2. Session Scope
   3. Application Scope

Request:

Objects with this scope are visible from the start of the request until the end of the request. Request scope starts at the beginning of a request and ends when the response has been sent to the client. If the request is forwarded, the objects are visible in the forwarded page, because that page is still part of the same request/response cycle. Objects with request scope can use other objects with none, request, session, or application scope.

Session:

An object with session scope is visible for any request/response cycle that belongs to a session. Objects with this scope have their state persisted between requests and last until the object or the session is invalidated. Objects with session scope can use other objects with none, session, or application scope.

Application:

An object with application scope is visible in all request/response cycles for all clients using the application, for as long as the application is active. Objects with application scope can use other objects with none or application scope.

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Thursday, August 12, 2010

Javascript function for email validation

 Email Validator In JSF Using JavaScript
In Javascript write the following function

function emailcheck(str) {
    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)
    if (str.indexOf(at)==-1){
        alert("Invalid E-mail ID")
        return false
    }
    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
        alert("Invalid E-mail ID")
        return false
    }
    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        alert("Invalid E-mail ID")
        return false
    }

    if (str.indexOf(at,(lat+1))!=-1){
        alert("Invalid E-mail ID")
        return false
    }

    if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        alert("Invalid E-mail ID")
        return false
    }

    if (str.indexOf(dot,(lat+2))==-1){
        alert("Invalid E-mail ID")
        return false
    }

    if (str.indexOf(" ")!=-1){
        alert("Invalid E-mail ID")
        return false
    }

    return true
}

function validateUser()
{
    var flag = true;   
    var mailid = document.frmuser.tf_USER_MAILID;//frmuser is the form id

    if(mailid != null && mailid.value == "" ){
        flag = false;
        alert ("Mailid cannot be Empty...");
    }

    if (flag ) {
            flag =  emailcheck(mailid.value);
        }

    return flag;
}

In JSP:

Include javascript file into jsp using following code  
Call the javascript function using following code
<h:commandButton id="bt_SAVE" value="SAVE" onclick="javascript:return validateUser();" action="#{createuser.saveUserDetails}" style="font-size:16;font-weight:bold"/>

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Sunday, June 27, 2010

Getting client and server sessionId in JSF

Code for Generating ClientSide SessionId:
var sesid = document.cookie;//this will give client sessionid and stores in sesid variable


Code for Generating ServerSide SessionId:
//this method will return the server side session id using getId() method
private String serverSessionid() {
HttpServletRequest hrq = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpSession session = hrq.getSession();
rtnString = session.getId();
//System.out.println("SESSION ID"+rtnString);
return rtnString;
}

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Thursday, June 24, 2010

Accessing Javascript variable from the Java file(backenbean) in JSF

In JavaScript:
function clntCookie(){
var sesid = document.cookie;//this will give client sessionid and stores in sesid variable
document.getElementById("tf_CheckValue").value = sesid;//assigning sesid value to the tf_CheckValue which is inputhidden field
}
In JSP:
<h:outputText id="text" value=" ">
<h:inputHidden id="tf_CheckValue" value="#{pendingApplication.tf_CheckValue}"/>
</h:outputText>
place the above code under <h:form> tag

In java (backenbean) file:
private String tf_CheckValue = new String();//generate set and get methods
String sesval = getTf_CheckValue();//this will get the client session id from javascript and place in the sesval.

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Tips for the components(inputtextfields,inputtextarea etc) in JSF

In jsp write the following javascript function under script tag
<script type="text/javascript">
function tipsMsg (val)
{
document.getElementById("msg").innerHTML = '';
if ( "tf_user_no1" == val )
{
document.getElementById("msg").innerHTML = 'User Number1 should be [a-z,A-Z,0-9]';
}
else if ( "tf_user_no2" == val )
{
document.getElementById("msg").innerHTML = 'User Number2 should be [0-9]';
}
}
</script>

call the above function in the following way
<h:inputText id="tf_USER_NO1" size="6" binding="#{printcheckdetails.tf_USER_NO1}" onkeyup="makeCaps('tf_USER_NO1')" onfocus="javascript:tipsMsg('tf_user_no1')" autocomplete="off" maxlength="6"/>

<h:inputText id="tf_USER_NO2" size="4" binding="#{printcheckdetails.tf_USER_NO2}" autocomplete="off" onfocus="javascript:tipsMsg('tf_user_no2')" onblur="formatNubmerPart(4)" maxlength="4"/>

if we put cursor in the userNumber text field it will give the message

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....