mkyong

mkyong

Software Engineer • Writer • Dad

20+ years hands-on, writing about Java, Spring, and AI. Every code example here is tested.

1,960 posts

Posts by mkyong

In JSF, “f:setPropertyActionListener” tag is allow you to set a value directly into the property of your backing bean. For example, <h:commandButton action="#{user.outcome}" value="Submit"> <f:setPropertyActionListener target="#{user.username}" value="mkyong" /> </h:commandButton> In above JSF code snippets, if the button is clicked, it will set the “mkyong” value to the “username” property via setUsername() method. @ManagedBean(name="user") @SessionScoped public […]

Read more JSF 2 setPropertyActionListener example

In JSF, “f:attribute” tag allow you to pass a attribute value to a component, or a parameter to a component via action listener. For example, 1. Assign a attribute value to a component. <h:commandButton"> <f:attribute name="value" value="Click Me" /> </h:commandButton> //is equal to <h:commandButton value="Click Me" /> 2. Assign parameter to a component and get […]

Read more JSF 2 attribute example

In JSF, “f:param” tag allow you to pass a parameter to a component, but it’s behavior is different depends on which type of component it’s attached. For example, 1. f:param + h:outputFormat If attach a “f:param” tag to “h:outputFormat“, the parameter is specifies the placeholder. <h:outputFormat value="Hello,{0}. You are from {1}."> <f:param value="JSF User" /> […]

Read more JSF 2 param example

In JSF, “Action Events” are fired by clicking on a button or link component, e.g h:commandButton or h:commandLink. actions vs action listeners Do not confuse these two tags, actions is used to perform business logic and navigation task; While action listeners are used to perform UI interface logic or action invoke observation. Common use case […]

Read more JSF 2 actionListener example

In JSF application, you can change your application locale programmatically like this : //this example change locale to france FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(‘fr’); It makes JSF support for internationalization or multiple languages easily. Complete JSF internationalization example In this tutorial, we show you a JSF 2.0 web application, which display a welcome page, retrieve a welcome message […]

Read more JSF 2 internationalization example

Problem How can a JSF event listener class access another managed bean? See scenario below : JSF page… <h:selectOneMenu value="#{country.localeCode}" onchange="submit()"> <f:valueChangeListener type="com.mkyong.CountryValueListener" /> <f:selectItems value="#{country.countryInMap}" /> </h:selectOneMenu> country managed bean… package com.mkyong; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name="country") @SessionScoped public class CountryBean implements Serializable{ private String localeCode; public void setLocaleCode(String localeCode) { this.localeCode […]

Read more Access a managed bean from event listener – JSF

When user make changes in input components, such as h:inputText or h:selectOneMenu, the JSF “value change event” will be fired. Two ways to implement it : 1. Method binding – In input component, specified a bean’s method directly in the “valueChangeListener” attribute. JSF… <h:selectOneMenu value="#{bean.value}" onchange="submit()" valueChangeListener="#{bean.valueChangeMethod}"> <f:selectItems value="#{bean.values}" /> </h:selectOneMenu> Java… The method which […]

Read more JSF 2 valueChangeListener example

In this article, we will show you how to create a custom validator in JSF 2.0 Steps Create a validator class by implements javax.faces.validator.Validator interface. Override validate() method. Assign an unique validator ID via @FacesValidator annotation. Reference custom validator class to JSF component via f:validator tag. A detail guide to create a custom validator name […]

Read more Custom validator in JSF 2.0

In this article, we show you how to create a custom converter in JSF 2.0. Steps 1. Create a converter class by implementing javax.faces.convert.Converter interface. 2. Override both getAsObject() and getAsString() methods. 3. Assign an unique converter ID with @FacesConverter annotation. 4. Link your custom converter class to JSF component via f:converter tag. Custom converter […]

Read more Custom converter in JSF 2.0

A short example to show the use of apache.commons.validator.UrlValidator class to validate an URL in Java. import org.apache.commons.validator.UrlValidator; public class ValidateUrlExample{ public static void main(String[] args) { UrlValidator urlValidator = new UrlValidator(); //valid URL if (urlValidator.isValid("https://mkyong.com")) { System.out.println("url is valid"); } else { System.out.println("url is invalid"); } //invalid URL if (urlValidator.isValid("http://invalidURL^$&%$&^")) { System.out.println("url is valid"); […]

Read more How to validate URL in Java

Problem Validate an URL with Apache common URLValidator to validate an URL, but it hits following error message ? java.lang.NoClassDefFoundError: org/apache/oro/text/perl/Perl5Util at org.apache.commons.validator.UrlValidator.isValid(UrlValidator.java:242) … Caused by: java.lang.ClassNotFoundException: org.apache.oro.text.perl.Perl5Util at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) … 28 more Solution The URLValidator class is required Jakarta-ORO library, make sure you include the oro-xxx.jar into your project class […]

Read more java.lang.NoClassDefFoundError: org/apache/oro/text/perl/Perl5Util

The standard JSF conversion and validation error messages are too detail, technical or sometime, not really human readable. In this article, it shows you how to customize standard conversion or validation error message in JSF 2.0. Summary Guide Find your message key from jsf-api-2.x.jar, “Messages.properties” file. Create your own properties file, and put the same […]

Read more Customize validation error message in JSF 2.0

Problem See following JSF example : <h:inputSecret id="password" value="#{user.password}" size="20" required="true" label="Password"> <f:validateRegex pattern="((?=.*\d).{6,20})" /> </h:inputSecret> <h:message for="password" style="color:red" /> <h:commandButton value="Cancel" action="cancel" /> <h:commandButton value="Submit" action="result" /> If you click on the “cancel” button, the password validation will be fired and stop you proceed on the cancel page, which is doesn’t make sense. Is […]

Read more How to skip validation in JSF

“f:validateRegex” is a new validator tag in JSF 2.0, which is used to validate JSF component with a given regular expression pattern. For example, <h:inputSecret id="password" value="#{user.password}"> <f:validateRegex pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})" /> </h:inputSecret> The above regex pattern is required 6 to 20 characters string with at least one digit, one upper case letter, one lower case letter […]

Read more JSF 2 validateRegex example

“f:validateRequired” is a new validator tag in JSF 2.0, which is used to make sure the input field is not empty. For example, <h:inputSecret id="password" value="#{user.password}"> <f:validateRequired /> </h:inputSecret> Alternatively, you can use the “required” attribute also, both are doing the same empty value validation. <h:inputSecret id="password" value="#{user.password}" required="true" /> “f:validateRequired” example A JSF 2.0 […]

Read more JSF 2 validateRequired example

“f:validateDoubleRange” is a JSF range validator tag, which is used to validate the range of a floating point value. For example, <h:inputText id="salary" value="#{user.salary}"> <f:validateDoubleRange minimum="10.11" maximum="10000.11" /> </h:inputText> When this form is submitted, the validator will make sure the “salary” value is within the range from “10.11” to “10000.11”. “f:validateDoubleRange” example A JSF 2.0 […]

Read more JSF 2 validateDoubleRange example

“f:validateLongRange” is a JSF range validator tag, which is used to check the range of a numeric value. For example, <h:inputText id="age" value="#{user.age}"> <f:validateLongRange minimum="1" maximum="150" /> </h:inputText> When this form is submitted, the validator will make sure the “age” value is within the range from 1 to 150. “f:validateLongRange” example A JSF 2.0 example […]

Read more JSF 2 validateLongRange example

“f:validateLength” is a JSF string length validator tag, which is used to check the length of a string. For example, <h:inputText id="username" value="#{user.username}"> <f:validateLength minimum="5" maximum="10" /> </h:inputText> When this form is submitted, the validator will make sure the “username” text field contains a minimum length of 5, maximum length of 10. “f:validateLength” example A […]

Read more JSF 2 validateLength example

Problem In JSF web application , load a message bundle in application level like this : 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_2_0.xsd" version="2.0"> <application> <message-bundle> com.mkyong.payment_error </message-bundle> </application> </faces-config> When the page is rendered, it hits “Can’t find bundle for base name com.mkyong.payment_error, locale en_US“? Solution Obviously, the bundle or properties file […]

Read more Can’t find bundle for base name xxx, locale en_US

Problem A Java web application deployed in Tomcat, hits the following error message : javax.servlet.ServletException: java.lang.NoClassDefFoundError: javax/el/ExpressionFactory org.apache.jasper.servlet.JspServlet.service(JspServlet.java:268) //… java.lang.ClassNotFoundException: javax.el.ExpressionFactory java.net.URLClassLoader$1.run(URLClassLoader.java:200) java.security.AccessController.doPrivileged(Native Method) java.net.URLClassLoader.findClass(URLClassLoader.java:188) //… javax.servlet.http.HttpServlet.service(HttpServlet.java:717) note The full stack trace of the root cause is available in the Apache Tomcat/6.0.26 logs. Solution The “javax.el.ExpressionFactory” class is belong to the “el-api.jar” library, you can […]

Read more java.lang.ClassNotFoundException: javax.el.ExpressionFactory

f:convertDateTime” is a standard JSF converter tag, which converts String into a specified “Date” format. In addition, it’s used to implement the date validation as well. The following JSF 2.0 example shows you how to use this “f:convertDateTime” tag. 1. Managed Bean A simple managed bean, with a “date” property. package com.mkyong; import java.io.Serializable; import […]

Read more JSF 2 convertDateTime example

In JSF, “f:convertNumber” is a standard converter, which converts String into a specified “Number” format. In addition, it’s also used as a validator to make sure the input value is a valid number. See following common used examples : Note : Assuming #{receipt.amount} contains a “0.1” value. 1. minFractionDigits attribute <h:outputText value="#{receipt.amount}" > <f:convertNumber minFractionDigits="2" […]

Read more JSF 2 convertNumber example

In the previous JSF 2 dataTable sorting example, showed the simplest way, a custom comparator to sort a list and display in dataTable. DataModel Decorator In this example, it shows another way to sort the list in dataTable, which is mentioned in the “Core JavaServer Faces (3rd Edition)“, called DataModel Decorator. 1. DataModel Create a […]

Read more JSF 2 dataTable sorting example – DataModel

Here’s the idea to sort a JSF dataTable list : 1. Column Header Put a commandLink in the column header, if this link is clicked, sort the dataTable list. <h:column> <f:facet name="header"> <h:commandLink action="#{order.sortByOrderNo}"> Order No </h:commandLink> </f:facet> #{o.orderNo} </h:column> 2. Implementation In the managed bean, uses Collections.sort() and custom comparator to sort the list. […]

Read more JSF 2 dataTable sorting example

The ui:repeat is always uses as an alternative to h:dataTable, to loop over array or list to display the data in HTML table format. See following examples : 1. h:dataTable In dataTable, JSF helps you to generate all the HTML table tags. <h:dataTable value="#{order.orderList}" var="o"> <h:column> #{o.orderNo} </h:column> <h:column> #{o.productName} </h:column> <h:column> #{o.price} </h:column> <h:column> […]

Read more JSF 2 repeat tag example

JSF dataTable does not contains any method to display the currently selected row numbers. However, you can hack it with javax.faces.model.DataModel class, which has a getRowIndex() method to return the currently selected row number. JSF + DataModel Here’s a JSF 2.0 example to show you how to use DataModel to return the currently selected row […]

Read more How to display dataTable row numbers in JSF

This example is enhancing the previous JSF 2 dataTable example, by adding a “delete” function to delete the row in dataTable. Delete Concept The overall concept is quite simple : 1. Assign a “Delete” link to the end of each row. //… <h:dataTable value="#{order.orderList}" var="o"> <h:column> <f:facet name="header">Action</f:facet> <h:commandLink value="Delete" action="#{order.deleteAction(o)}" /> </h:column> 2. If […]

Read more How to delete row in JSF dataTable

This example is enhancing previous delete dataTable row example, by adding a “add” function to add a row in dataTable. Here’s a JSF 2.0 example to show you how to add a row in dataTable. 1. Managed Bean A managed bean named “order”, self-explanatory. package com.mkyong; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import […]

Read more How to add row in JSF dataTable

Since JSF 2.0, you are allow to pass parameter values in method expression like “#{bean.method(param)}“, but this feature will raising a “EL parsing error” on Tomcat server. For example, Managed Bean @ManagedBean(name="order") @SessionScoped public class OrderBean implements Serializable{ public String editAction(String id) { //… } } JSF page //… <h:commandLink value="Edit" action="#{order.editAction(123)}" /> //… If […]

Read more How to pass parameters in method expression – JSF 2.0

In JSF, “h:dataTable” tag is used to display data in a HTML table format. The following JSF 2.0 example show you how to use “h:dataTable” tag to loop over an array of “order” object, and display it in a HTML table format. 1. Project Folder Project folder structure of this example. 2. Managed bean A […]

Read more JSF 2 dataTable example

Problem In JSF 2.0, comment out a JSF tag like this JSF… <?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:body> <!– <h:commandButton type="button" value="#{msg.buttonLabel}" /> –> </h:body> </html> But JSF still process the value expression and output the result to the generated HTML page. Assuming that #{msg.buttonLabel} […]

Read more How to use comments in JSF 2.0

In JSF 2.0, you are allow to create your custom tag to render a pre-defined content. A custom tag is look like a normal JSF tag, and uses “ui:composition” to insert content into the page. Here’s the summary steps to create a custom tag in JSF 2.0. Uses :ui:compisition” tag to create a predefined content […]

Read more Custom tags in JSF 2.0

In JSF 2.0 web application, you can use “ui:param” facelets tag to pass parameters to an include file or a template file. 1. Parameter in “ui:include” Example to pass a “tagLine” parameter to an include file. <ui:insert name="header" > <ui:include src="/template/common/commonHeader.xhtml"> <ui:param name="tagLine" value="JSF a day, bug away" /> </ui:include> </ui:insert> In the commonHeader.xhtml file, […]

Read more How to pass parameters to JSF 2.0 template file?

In JSF, <h:selectManyMenu /> tag is used to render a multiple select dropdown box – HTML select element with “multiple” and “size=1” attribute. //JSF… <h:selectManyMenu value="#{user.favCoffee1}"> <f:selectItem itemValue="Cream Latte" itemLabel="Coffee3 – Cream Latte" /> <f:selectItem itemValue="Extreme Mocha" itemLabel="Coffee3 – Extreme Mocha" /> <f:selectItem itemValue="Buena Vista" itemLabel="Coffee3 – Buena Vista" /> </h:selectManyMenu> //HTML output… <select name="j_idt6:j_idt8" […]

Read more JSF 2 multiple select dropdown box example

In JSF, <h:selectOneMenu /> tag is used to render a dropdown box – HTML select element with “size=1” attribute. //JSF… <h:selectOneMenu value="#{user.favCoffee1}"> <f:selectItem itemValue="Cream Latte" itemLabel="Coffee3 – Cream Latte" /> <f:selectItem itemValue="Extreme Mocha" itemLabel="Coffee3 – Extreme Mocha" /> <f:selectItem itemValue="Buena Vista" itemLabel="Coffee3 – Buena Vista" /> </h:selectOneMenu> //HTML output… <select name="j_idt6:j_idt8" size="1"> <option value="Cream Latte">Coffee3 […]

Read more JSF 2 dropdown box example

In JSF, <h:selectManyListbox /> tag is used to render a multiple select listbox – HTML select element with “multiple” and “size” attribute. //JSF… <h:selectManyListbox value="#{user.favFood1}"> <f:selectItem itemValue="Fry Checken" itemLabel="Food1 – Fry Checken" /> <f:selectItem itemValue="Tomyam Soup" itemLabel="Food1 – Tomyam Soup" /> <f:selectItem itemValue="Mixed Rice" itemLabel="Food1 – Mixed Rice" /> </h:selectManyListbox> //HTML output… <select name="j_idt6:j_idt8" multiple="multiple" […]

Read more JSF 2 multiple select listbox example