HomeJSF

Using JavaScript or doing client side validation in JSF 1.2

Like Tweet Pin it Share Share Email

Step by step tutorial for using JavaScript in JSF

In this example I will demonstrate you using JavaScript in JSF. Everyone knows using JavaScript in simple HTML. In JSF framework syntax of JavaScript is a bit different. It is not same like used in plain JSP or HTML.

Let us demonstrate this syntax by taking a simple client side validation example.

Objective of Example : Using JavaScript with JSF
1. In this example we will demonstrate how to work or use JavaScript in JSF.
2. While using java script with JSF suppose form id is “validationInJSFFormID” and attribute Id is “userNameId” then we will get attribute Id like

var userName = document.getElementById("validationInJSFFormID:userNameId");

Now we can get get value of attribute like this

var userNameValue = userName.value;

Requirements to do this Example:
Before doing this example I would like to refer this tutorial – First Sample Hello World Example in JSF . If we know How to create a simple dynamic web application in JSF. We can learn using java script in JSF very easily. For this example I have created a dynamic web application named “UsingJavaScriptInJSF” . After creating web application with name  “UsingJavaScriptInJSF” we can go further to do example using java script in JSF.
Please see the Eclipse project hierarchy in the image.

Java Script Validation In JSF
Java Script Validation Project – Eclipse Image

Please follow these steps to do example java script in jsf.

1. Create JSP Pages :
Now we have to create two JSP pages.

  1. UserForm.jsp – This is a form page, in which user will fill his own details.
  2. jsfValidationSuccessWelcomeGreeting.jsp – Another page will be welcome page which will show the information user has entered in the form fields.

1. userForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"  pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>using Java Script in JSF example</title>
<script type="text/javascript">
    function validateForm() {
        var userName = document.getElementById("validationInJSFFormID:userNameId");
        var yourCompanyNameId = document.getElementById("validationInJSFFormID:yourCompanyNameId");
        var workingTechnologiesId = document.getElementById("validationInJSFFormID:technologiesYouWorkId");
        if (userName != null && userName.value == '') {
            alert('Please Enter Your Good Name');
            return false;
        }
        if (yourCompanyNameId != null && yourCompanyNameId.value == '') {
            alert('Please Enter Name of Your Company');
            return false;
        }
        if (workingTechnologiesId != null && workingTechnologiesId.value == '') {
            alert('Please Enter Technologies You are working');
            return false;
        }
        return true;
    }
</script>
</head>
<body>
    <f:view>
        <h:form id="validationInJSFFormID" onsubmit="return validateForm()">
            <h:panelGrid border="0" cellpadding="2" cellspacing="2" columns="2">
                <h:outputText>Your Good Name :</h:outputText>
                <h:inputText id="userNameId" value="#{formValidationMBean.userFormView.userName}"></h:inputText>
                <h:outputText>Working Company :</h:outputText>
                <h:inputText id="yourCompanyNameId" value="#{formValidationMBean.userFormView.yourCompanyName}"></h:inputText>
                <h:outputText>Working Technologies :</h:outputText>
                <h:inputTextarea id="technologiesYouWorkId" value="#{formValidationMBean.userFormView.technologiesYouWork}"></h:inputTextarea>
            </h:panelGrid>
            <h:panelGroup style="text-align:center;">
                <h:commandButton value="Check Validation" id="commandButton" action="#{formValidationMBean.validationSuccess}"></h:commandButton>
            </h:panelGroup>
        </h:form>
    </f:view>
</body>
</html>

2.  jsfValidationSuccessWelcomeGreeting.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>using Java Script in JSF example</title>
</head>
<body>
    <f:view>
        <h:panelGrid border="0" cellpadding="2" cellspacing="2" columns="1">
            <h:panelGroup>
                <h:outputText value="Welcome "></h:outputText>
                <h:outputText style="font-family:arial;color:red;font-size:32px;"
                    value="#{formValidationMBean.userFormView.userName} !"></h:outputText>
            </h:panelGroup>
            <h:outputText value="You have entered all the details successfully."></h:outputText>
            <h:panelGroup>
            <h:outputText
                value="Your works in a very nice company named - "></h:outputText>
            <h:outputText style="font-family:arial;color:red;font-size:32px;"
                value="#{formValidationMBean.userFormView.yourCompanyName}"></h:outputText>
            </h:panelGroup>
            <h:panelGroup>
            <h:outputText
                value="Technologies you are working are - "></h:outputText>
            <h:outputText style="font-family:arial;color:red;font-size:32px;"
                value="#{formValidationMBean.userFormView.technologiesYouWork}"></h:outputText>
            </h:panelGroup>
        </h:panelGrid>
    </f:view>
</body>
</html>

2. Create Managed Bean For this Example :
Throughout this Java Script with JSF example you can see these value binded attributes
“formValidationMBean.userFormView.userName”.
Here
formValidationMBean – Manged Bean
userFormView – View Model (Used to get & set values of the form field attribute)

formValidationMBean will be defined in faces-config.xml file. Please see faces-config.xml file for this example.
Below code is for Managed Bean JSFFormValidationManagedBean.java. This JSFFormValidationManagedBean.java file is for example using java script in JSF.

package com.sitenol.JSFFormValidation;
import java.io.Serializable;
public class JSFFormValidationManagedBean implements Serializable{
    private static final long serialVersionUID = 1L;
    private UserFormView userFormView;
    public JSFFormValidationManagedBean(){
            this.userFormView = new UserFormView();
        }
        public UserFormView getUserFormView() {
            return userFormView;
        }
        public void setUserFormView(UserFormView userFormView) {
            this.userFormView = userFormView;
        }
        public String validationSuccess(){
            return "validationSuccess";
        }
}

3. Create View Model For this Example :
Inside Managed Bean JSFFormValidation.java you can see private UserFormView userFormView;
UserFormView.java is view model. Please find the code below. This UserFormView.java file is for example using java script in JSF.


package com.sitenol.JSFFormValidation;
public class UserFormView {
    private String userName;
    private String technologiesYouWork;
    private String yourCompanyName;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getTechnologiesYouWork() {
        return technologiesYouWork;
    }
    public void setTechnologiesYouWork(String technologiesYouWork) {
        this.technologiesYouWork = technologiesYouWork;
    }
    public String getYourCompanyName() {
        return yourCompanyName;
    }
    public void setYourCompanyName(String yourCompanyName) {
        this.yourCompanyName = yourCompanyName;
    }
}

4. Create faces-config.xml file :
Please find the faces-config.xml file code here. This faces-config.xml file is for example using java script in JSF.

Faces-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<faces-config 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"
    version="1.2">
    <managed-bean>
        <managed-bean-name>formValidationMBean</managed-bean-name>
        <managed-bean-class>com.sitenol.JSFFormValidation.JSFFormValidationManagedBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <from-view-id>/userForm.jsp</from-view-id>
        <navigation-case>
            <from-outcome>validationSuccess</from-outcome>
            <to-view-id>/jsfValidationSuccessWelcomeGreeting.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
</faces-config>

5. Create web.xml file :

Please find the web.xml file code here. This web.xml file is for example using java script in JSF.
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>UsingJavaScriptInJSF</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <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>*.faces</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>server</param-value>
  </context-param>
  <context-param>
    <description>
	This parameter tells MyFaces if javascript code should be allowed in
	the rendered HTML output.
	If javascript is allowed, command_link anchors will have javascript code
	that submits the corresponding form.
	If javascript is not allowed, the state saving info and nested parameters
	will be added as url parameters.
	Default is 'true'</description>
    <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
    <param-value>true</param-value>
  </context-param>
  <context-param>
    <description>
	If true, rendered HTML code will be formatted, so that it is 'human-readable'
	i.e. additional line separators and whitespace will be written, that do not
	influence the HTML code.
	Default is 'true'</description>
    <param-name>org.apache.myfaces.PRETTY_HTML</param-name>
    <param-value>true</param-value>
  </context-param>
  <context-param>
    <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
    <param-value>false</param-value>
  </context-param>
  <context-param>
    <description>
	If true, a javascript function will be rendered that is able to restore the
	former vertical scroll on every request. Convenient feature if you have pages
	with long lists and you do not want the browser page to always jump to the top
	if you trigger a link or button action that stays on the same page.
	Default is 'false'
</description>
    <param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
    <param-value>true</param-value>
  </context-param>
  <listener>
    <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
  </listener>
</web-app>

6. Deploy Application to Server :
In this step we have to deploy our application to web application server installed in our system.
In this example we are using Apache Tomcat Server 6.20.  We  have installed the UsingJavaScriptInJSF.war  file to apache tomcat which is installed in the eclipse.
Manually we can installed the war file to webapps folder of apache tomcat server.

7. Run The Application :
After successfully war deployment. Please start the server. After that open Internet Explorer and hit this “http://localhost:8081/UsingJavaScriptInJSF/userForm.faces”.

So now we can see our java script with JSF example output.

First Screen :

client Side Validation In JSF output Screen One
First Output Screen



In this screen you have to enter Your Good Name, Working Company, Working Technologies. We are validating these fields at client side using Java Script. If you will fail to enter any of these fields you will receive one alert message for each attribute. When you will enter all the fields completely you will receive Second Screen.
Second Screen :

Validating JSF Form Page
Welcome Page of Client Side Validation JSF

Comments (0)

Leave a Reply

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