JSF UI Component Tag Attributes Example Tutorial

Filed Under: JSF

JSF provides a wide variety of ui component tags along with a long range of attributes. Today we will look into most important and widely used UI component attributes.

id attribute

The id attribute uniquely identifies a component. If the id attribute is not specified, JSF automatically generates an id. The id attribute is used when we want to refer to a component at the server side class. To associate a component we will have to specify the name using for attribute in the JSF tags. The name in the for clause can then be used to map other to the id of the UI component.

For example, we can declare id as


<h:outputLabel for="cname">Car Name:</h:outputLabel>
<h:inputText id="cname" size="45"></h:inputText>

Here we define the id attribute in inputText tag with “cname” for the car name field. Whenever we want to fetch the value from the JSF page we use the “cname” which contains the value entered by the user for the car name field. This mapping is made possible since we define a unique id to this field.

value attribute

The value attribute is assigned the current value of a component. The common syntax is the bean name followed by the field name. For example, if the bean name is car and model is the field we can assign the value as #{car.model}.

Consider the following piece of code to demonstrate the usage of value attribute;


<h:inputText id="model"  value ="#{car.model}" ></h:inputText>

Here we set the value to the model attribute using the car bean that contains getter and setter methods through which the user entered value is set.

The code for car bean would be as below.


package com.journaldev.jsf.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class Car {

private String model;

public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }
}

style and styleClass attributes

The style attribute is used to specify the css properties like color, font, alignment etc. for a component. The styleClass specifies the CSS class name to be applied for the component. For example if the user wants to see the error messages in red color then the user specifies the style as color:red in the message tag.

For example;


<h:message for="cname" style="color: red"></h:message>

Here we use the style attribute with the specification for color as red as such the message for cname field will be displayed in red.

We can also specify the class name in the dataTable tag which accepts the class name attribute.


<h:dataTable id ="cars"  styleClass="carTable" value="#{car.carlist}" ></h:dataTable>

We define the css styles in the styleClass carTable and the styles are rendered in the output.

rendered attribute

The rendered attribute indicates whether the component should be rendered or not. Rendered attributes restricts users to use rvalue expression which can only read data but cannot write back to the specified source components. Expressions can use arithmetic operators and literals that can use rvalue.


<h:commandLink id="car"
    rendered="#{car.carlist > 0}">
    <h:outputText
        value="#{car.CarCheck}"/>
</h:commandLink>

Here the cars are fetched and checked if the number of the cars are greater than 0. If the count of the cars is greater than 0 then the value is set by the carCheck method.

onblur attribute

The onblur invokes the javascript function that has to be executed when the focus on a particular component is lost. For example, in a scenario such as – if we want to validate the data entered by the user when an element loses its focus or on tab out. The following piece of code validates the data entered by the user for a name field.

<h:inputtext id=”name” onblur=”validatename()”>

The validatename javascript function is invoked on the name attribute.

The javascript code for validatename function is;


function validatename(cname) {
        var elem = cname.id;
        var name = document.getElementById(elem).value;
        var len = name.length;
        
           if(len &lt; 4 ) {
            document.getElementById("mesg").textContent = "Car Name:Valid input";
        }    else {
            document.getElementById("mesg").textContent ="Car Name:Invalid input"
        }
    }

The document.getElementById is used to fetch the value of the name entered in the field and stored in the variable name. The length of the name is checked by invoking the length function. If the length of the name is less than 4 “Car Name:Valid input” message is printed. For the length value greater than 4 “Car Name:Invalid input” is printed.

onclick attribute

The onclick invokes the javascript function to be executed when the mouse is clicked over a component. In the onclick attribute we specify the javascript function name that has to be called and define this function in the header part of the jsf page containing the functionality that has to be to be accomplished for the event triggered.

The invocation of the onclick function can be done as shown below


 <h:commandButton id="submit"
   action="cardetails" value="Submit" onclick="validateInput()"/>

In the command button tag we are calling the validateInput javascript function that will be triggered on click of this button.The validateInput function can be defined as


function validateInput {
        var elem = cname.id;
        var name = document.getElementById(elem).value;
        var len = name.length;
        
           if(len == 4 ) {
            document.write( "Car Name:Matches the number of characters expected");
        }     
  }

This function looks for a string with length of 4 characters and prints the message as specified in the function.

immediate attribute

The immediate attribute is a boolean flag which accepts the values of either true or false. If the flag is set to true, the events and validation are to be executed in the apply request value phase of the JSF lifecycle management instead of waiting for the process validation phase. For example, consider the car details page where the user can enter the details of the car like color,model,name etc and click on submit button to save the details entered. If the immediate attribute is set to true for the field, on click of the submit button, the new value entered in the fields are available for processing. All the events validations associated with the field are processed immediately rather than the process validation stage of the lifecycle.

required attribute

The required attribute is a boolean flag with values true or false and is generally used on fields for mandatory checks. If the required flag is set to true, the field becomes mandatory and further processing will not happen until the value is entered. For instance,the required flag can be used in textArea tag as;


<h:inputText value="#{car.id}" id="Id" required="true"></h:inputText>

Here the required="true" indicates that car id is a mandatory field and hence the built in error message is displayed to the user – “Value is required”.

requiredMessage attribute

The requiredMessage attribute allows the user to specify their own error messages for the fields in the JSF page. The requiredMessage attribute is preceded by the required attribute.

The requiredMessage attribute can be invoked as shown below;


<h:inputText value="#{car.id}" id="Id" required="true" requiredMessage="Car Id is mandatory"></h:inputText>

Here the Message is specified in requiredMessage attribute in the inputText tag.

for attribute

The for attribute identifies a component for which the label component has to be generated.
The for attribute can be declared and associated with id as


<h:outputLabel for="cname">Car Name:</h:outputLabel>
 <h:inputText id="cname" value="#{carLabel.cname}"></h:inputText>

The for attribute points to the id component for which the label is intended to.

size attribute

The size attribute sets the width of the characters that the input text allows. The size of the field can be specified as shown below;


<h:inputText id="cname"  size="45"></h:inputText>

The maximum characters allowed in the cname field is 45 characters.

JSF UI Component Attributes Example

Consider an example JSF page named attributes.xhtml showing various attributes;


<?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">
<h:head>
	<title>Adding a Label</title>

	<script type="text/javascript">
        function validatename(cname) {
        
        var elem = cname.id;
        
        var name = document.getElementById(elem).value;
         
        var len = name.length;
         
        if(len &lt; 4 ) {
            document.getElementById("mesg").textContent = "Car Name:Valid input";
        }
        
        else {
            document.getElementById("mesg").textContent ="Car Name:Invalid input"
        }
    }
    </script>
</h:head>
<h:body>
	<h3>Adding a label</h3>
	<h:form>
		<h:panelGrid columns="3">
			<h:outputLabel for="cname">Car Name:</h:outputLabel>
			<h:inputText id="cname" value="#{car.cname}"
				onblur="validatename(this)"></h:inputText>
			<br />
			<br />
			<h:outputLabel for="color">Car Color:</h:outputLabel>
			<h:inputText id="color" value="#{car.color}" immediate="true"
				size="20" required="true" requiredMessage="Color is mandatory"
				style="color: aqua"></h:inputText>
		</h:panelGrid>
		<br />
		<br />
		<div id="mesg"></div>
		<h:commandButton value="Submit"></h:commandButton>
	</h:form>

</h:body>
</html>

Now we have a Managed Bean Car.java as below.


package com.journaldev.jsf.beans;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class Car {
    
    private String cname;
    private String color;

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
       
}

Run the application in your favorite container and you will get below output pages.

JSF-UI-Attributes-1

JSF-UI-Attributes-2

JSF-UI-Attributes-3

That’s all for different JSF UI attributes, we will look into more of JSF features in coming posts.

Comments

  1. Mounika says:

    Is there any video tutorials to learn complete JSF primefaces.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages