Custom converter 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

How to validate URL in Java

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

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

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

Customize validation error message in JSF 2.0

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

How to skip validation in JSF

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

JSF 2 validateRegex example

“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 validateRequired 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 validateDoubleRange 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 validateLongRange 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 validateLength 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 panelGrid example

In JSF , “h:panelGrid” tag is used to generate HTML table tags to place JSF components in rows and columns layout, from left to right, top to bottom. For example, you used to group JSF components with HTML table tags like this : HTML <table> <tbody> <tr> <td> Enter a number : </td> <td> <h:inputText …

Read more

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

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

java.lang.ClassNotFoundException: javax.el.ExpressionFactory

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

JSF 2 convertDateTime example

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 convertNumber 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 dataTable sorting example – DataModel

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

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 repeat tag 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

How to display dataTable row numbers in JSF

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 delete row in JSF dataTable

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 add 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 update row in JSF dataTable

This example is enhancing the previous JSF 2 dataTable example, by adding a “update” function to update row in dataTable. Update Concept The overall concept is quite simple : 1. Add a “ediatble” property to keep track the row edit status. //… public class Order{ String orderNo; String productName; BigDecimal price; int qty; boolean editable; …

Read more

How to pass parameters in method expression – JSF 2.0

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

JSF 2 dataTable example

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

How to use comments in JSF 2.0

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

Custom tags 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

How to pass parameters to JSF 2.0 template file?

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

JSF 2 Templating with Facelets example

In web application, most pages are follow a similar web interface layout and styling, for example, same header and footer. In JSF 2.0, you can use Facelets tags to provide a standard web interface layout easily, in fact, it’s look similar with Apache Tiles framework. In this example, it shows the use of 4 Facelets …

Read more

JSF 2 multiple select dropdown box example

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 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 multiple select listbox 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 listbox example

In JSF, <h:selectOneListbox /> tag is used to render a single select listbox – HTML select element with “size” attribute. //JSF… <h:selectOneListbox value="#{user.favYear1}"> <f:selectItem itemValue="2000" itemLabel="Year1 – 2000" /> <f:selectItem itemValue="2010" itemLabel="Year1 – 2010" /> <f:selectItem itemValue="2020" itemLabel="Year1 – 2020" /> </h:selectOneListbox> //HTML output… <select name="j_idt6:j_idt8" size="3"> <option value="2000">Year1 – 2000</option> <option value="2010">Year1 – 2010</option> …

Read more

WARNING: JSF1063: WARNING! Setting non-serializable attribute value into HttpSession

Problem In JSF 2.0 web application, during server initialization, it hits following warning message WARNING: JSF1063: WARNING! Setting non-serializable attribute value into HttpSession (key: user, value class: com.mkyong.UserBean). UserBean.java package com.mkyong; @ManagedBean(name="user") @SessionScoped public class UserBean{ //… } Solution The “UserBean” is not serializable. To get rid of this warning message, just make this bean …

Read more

JSF 2 radio buttons example

In JSF, “h:selectOneRadio” tag is used to render a set of HTML input element of type “radio“, and format it with HTML table and label tag. //JSF… <h:selectOneRadio value="#{user.favColor1}"> <f:selectItem itemValue="Red" itemLabel="Color1 – Red" /> <f:selectItem itemValue="Green" itemLabel="Color1 – Green" /> <f:selectItem itemValue="Blue" itemLabel="Color1 – Blue" /> </h:selectOneRadio> //HTML output… <table> <tr> <td> <input type="radio" …

Read more

JSF 2 checkboxes example

In JSF, <h:selectBooleanCheckbox /> tag is used to render a single HTML input element of “checkbox” type. //JSF… <h:selectBooleanCheckbox value="#{user.rememberMe}" /> Remember Me //HTML output… <input type="checkbox" name="j_idt6:j_idt8" /> Remember Me While <h:selectManyCheckbox /> tag is used to render a set of HTML input element of type “checkbox”, and format it with HTML table and …

Read more

JSF 2 link, commandLink and outputLink example

In JSF, <h:link />, <h:commandLink /> and <h:outputLink /> tags are used to render a HTML “a” anchor element, see below examples to understand the different among them. Note In below examples, assume “/JavaServerFaces/” is the root of your project context URL. 1. JSF h:link example The “h:link” tag is a new tag in JSF …

Read more

JSF 2 button and commandButton example

In JSF 2.0, both <h:button /> and <h:commandButton /> tags are used to render HTML input element of type button, with different mechanism to handle the navigation. 1. JSF h:commandButton example The “h:commandButton” tag is released since JSF 1.x, you can declare the bean, which return the navigation outcome in the “action” attribute. If browser’s …

Read more

How to include cascading style sheets (CSS) in JSF

In JSF 2.0, you can use <h:outputStylesheet /> output a css file. For example, <h:outputStylesheet library="css" name="style.css" /> It will generate following HTML output… <link type="text/css" rel="stylesheet" href="/JavaServerFaces/faces/javax.faces.resource/style.css?ln=css" /> JSF outputStylesheet example An example to show the use of JSF 2 <h:outputStylesheet /> to render a “style.css” file, locate in the “resources/css” folder, see figure …

Read more

How to include JavaScript file in JSF

In JSF 2.0, you can use <h:outputScript /> tag to render a HTML “script” element, and link it to a js file. For example, <h:outputScript library="js" name="common.js" /> It will generate following HTML output… <script type="text/javascript" src="/JavaServerFaces/faces/javax.faces.resource/common.js?ln=js"> </script> JSF outputScript example An example to show you how to use <h:outputScript /> to render a “common.js“, …

Read more

JSF 2 graphicImage example

In JSF, you can use <h:graphicImage /> tag to render a HTML “img” element. For example, an image named “sofa.png” in a resources folder, see figure below : 1. JSF 1.x graphicImage In JSF 1.x you can hard-coded above image URL directly in the “value” attribute : JSF… <h:graphicImage value="resources/images/sofa.png" /> HTML output… <img src="resources/images/sofa.png;" …

Read more