My JSF Books/Videos My JSF Tutorials OmniFaces/JSF PPTs
JSF 2.3 Tutorial
JSF Caching Tutorial
JSF Navigation Tutorial
JSF Scopes Tutorial
JSF Page Author Beginner's Guide
OmniFaces 2.3 Tutorial Examples
OmniFaces 2.2 Tutorial Examples
JSF Events Tutorial
OmniFaces Callbacks Usages
JSF State Tutorial
JSF and Design Patterns
JSF 2.3 New Features (2.3-m04)
Introduction to OmniFaces
25+ Reasons to use OmniFaces in JSF
OmniFaces Validators
OmniFaces Converters
JSF Design Patterns
Mastering OmniFaces
Reusable and less-verbose JSF code

My JSF Resources ...

Java EE Guardian
Member of JCG Program
Member MVB DZone
Blog curated on ZEEF
OmniFaces is an utility library for JSF, including PrimeFaces, RichFaces, ICEfaces ...

[OmniFaces Utilities] - Find the right JSF OmniFaces 2 utilities methods/functions

Search on blog

Petition by Java EE Guardians

Twitter

luni, 30 noiembrie 2015

[JSF Page Author Beginner's Guide] JSF <f:param>

The <f:param> is useful for attaching extra parameters to 
outcomes, external URLs, formatted output and commands
Common/basic usage in JSF (I) - setting parameters of a fomatted output (<f:param/> and <h:outputFormat/>):

<?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://xmlns.jcp.org/jsf/html"
 xmlns:f="http://xmlns.jcp.org/jsf/core">
 <h:head>
  <title>JSF f:param examples</title>
 </h:head>
 <h:body>
  <h:outputFormat value="Hello {0} &amp; {1} fans!">
   <f:param value="OmniFaces"/>
   <f:param value="JSF"/>
  </h:outputFormat>
 </h:body>
</html>

The <h:outputFormat/> tag will be rendered in HTML as:

Hello OmniFaces &amp; JSF fans!


Common/basic usage in JSF (II) - attach request parameters (query string) to a link (<f:param/> and <h:link/>):

<?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://xmlns.jcp.org/jsf/html"
 xmlns:f="http://xmlns.jcp.org/jsf/core">
 <h:head>
  <title>JSF f:param examples</title>
 </h:head>
 <h:body>
  <h:link value="Welcome page" outcome="welcome">
   <f:param name="name" value="Rafael Nadal"/>
  </h:link>
 </h:body>
</html>

The welcome.xhtml page looks like this:

 <<?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://xmlns.jcp.org/jsf/html">
 <h:head>
  <title></title>
 </h:head>
 <h:body>
  #{param['name']}
  <br/><br/>
  <h:link value="Back" outcome="index"/>
 </h:body>
</html>

The <h:link/> tag will be rendered in HTML as:

<a href="/JSFparamExamples/faces/welcome.xhtml?name=Rafael+Nadal">Welcome page</a> 

Data flow in image:

Note The <f:param/> tag cannot be fortified with declarative/imperative validations and/or conversions. You need to accomplish this task by yourself. Do not try to place the <f:param/> tag inside the <h:inputText/> tag or any other input component. That will simply not work.

More examples:

Attaching extra parameters via commands (command button and command link)

<?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://xmlns.jcp.org/jsf/html"
 xmlns:f="http://xmlns.jcp.org/jsf/core">
 <h:head>
  <title>JSF f:param examples</title>
 </h:head>
 <h:body>
  <h:form>
   <h:commandLink value="Send" action="#{myBean.saveAndParam()}">
    <f:param name="countryCode" value="RO"/>
    <f:param name="homepage" value="http://www.omnifaces-fans.org/"/>
   </h:commandLink>
  </h:form>
 
  <h:form>
   <h:commandButton value="Send" action="#{myBean.saveAndParam()}">
    <f:param name="countryCode" value="RO"/>
    <f:param name="homepage" value="http://www.omnifaces-fans.org/"/>
   </h:commandButton>  
  </h:form>
 </h:body>
</html>

And the MyBean managed bean is:

package beans;

// imports

@Named
@RequestScoped
public class MyBean {

 public MyBean() {
 }

 public void saveAndParam() {
  System.out.println("Saving data [saveAndParam()] ...");
  FacesContext fc = FacesContext.getCurrentInstance();
  Map<String, String> params = fc.getExternalContext().getRequestParameterMap();

  String code = params.get("countryCode");
  String webURL = params.get("homepage");

  System.out.println("Country code: " + code + " ; web url: " + webURL);
 }
}

Now, when we submit a form via <h:commandLink/> or <h:commandButton/>, the  saveAndParam() method will access the request parameter map and return:

Country code: RO ; web url: http://www.omnifaces-fans.org/

Passing extra parameters in external URLs (<f:param> and <h:outputLink>)

<?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://xmlns.jcp.org/jsf/html"
 xmlns:f=http://xmlns.jcp.org/jsf/core>
 <h:head>
  <title>JSF f:param examples</title>
 </h:head>
 <h:body>
  <h:outputLink value="#{myBean.article.url}">
   <f:param name="p" value="#{myBean.article.id}"/>
   PrimeFaces 5.3 Released
  </h:outputLink>
 </h:body>
</html>

The <h:outputLink/> tag will be rendered in HTML as:

<a href="http://blog.primefaces.org/?id=3639"> PrimeFaces 5.3 Released </a>

The managed bean is:

package beans;

// imports

@Named
@RequestScoped
public class MyBean {

 private Article article;

 public MyBean() {
  this.article = new Article("http://blog.primefaces.org/", 3639);
 }

 // Getters and setters
}

The Article class is shown below:

package beans;

import java.io.Serializable;

public class Article implements Serializable {

 private static final long serialVersionUID = 1L;

 private String url;
 private Integer id;

 public Article() {
 }

 public Article(String name, Integer id) {
  this.url = name;
  this.id = id;
 }

 // Getters and setters
}

Styling output format parameters

Check out the below example:

<h:outputFormat value="Hello {0} &amp; {1} fans!" escape="false">
 <f:param>
  <h:outputText value="OmniFaces" style="color:red"/>
 </f:param>
 <f:param>
  <h:outputText value="JSF" style="color:red"/>
 </f:param>
</h:outputFormat>

Unfortunately, <h:outputFormat/> is not capable to use its children as a value and the above code will result in something like below:


As a solution, the OmniFaces <o:param/> component has the capability to return the encoded output of its children as a value. Just replace <f:param> with <o:param>:

<h:outputFormat value="Hello {0} &amp; {1} fans!" escape="false">
 <o:param>
  <h:outputText value="OmniFaces" style="color:red"/>
 </o:param>
 <o:param>
  <h:outputText value="JSF" style="color:red"/>
 </o:param>
</h:outputFormat>
Will be rendered in HTML as:

Hello <span style="color:red">OmniFaces</span> & <span style="color:red">JSF</span> fans!

Setting parameters as managed bean properties via @ManagedProperty

<h:commandButton value="Send Rafael Nadal" action="#{playersBean.parametersAction()}">
 <f:param id="playerName" name="playerNameParam" value="Rafael"/>              
 <f:param id="playerSurname" name="playerSurnameParam" value="Nadal"/>              
</h:commandButton>

And in the managed bean do this:

@ManagedProperty(value = "#{param.playerNameParam}")
private String playerName;
@ManagedProperty(value = "#{param.playerSurnameParam}")
private String playerSurname;

AJAX and <f:param>

<h:form>
 <h:inputText id="nameInputId" value="#{ajaxBean.name}"/>
 <h:commandButton value="Send" action="#{ajaxBean.ajaxAction()}">
  <f:ajax execute ="nameInputId" render="nameOutputId">
   <f:param name="surnameInputId" value="Nadal"/>
  </f:ajax>
 </h:commandButton>
 <h:outputText id="nameOutputId" value="#{ajaxBean.name}"/>
</h:form>

Remember that the parameter that was passed is available in the request parameter map:

FacesContext fc = FacesContext.getCurrentInstance();
Map<String, String> params = fc.getExternalContext().getRequestParameterMap();

logger.log(Level.INFO, "Surname: {0}", params.get("surnameInputId"));

Complete source code on GitHub.
See also Mkyong.com.
More resources on Constantin Alin, ZEEF page.

[OmniFaces utilities 2.0] Format the given number as currency with the given symbol


[OmniFaces utilities] The formatCurrency() function format the given number as currency with the given symbol. This is useful when you want to format numbers as currency in for example the title attribute of an UI component, or the itemLabel attribute of select item, or wherever you can't use the <f:convertNumber> tag. The format locale will be set to the one as obtained by Faces#getLocale().

Function:
See also: Faces#getLocale()
Usage:

Let's suppose that we have a map that contains several JSF books names and their prices as floats, as below:

// in real cases, you may hit a database
private final Map<Float, String> booksMap
        = Collections.unmodifiableMap(new HashMap<Float, String>() {
 {
  put(27.76f, "Mastering JavaServer Faces 2.2");
  put(37.20f, "Mastering OmniFaces");
  put(33.78f, "JavaServer Faces 2.2");
  put(29.44f, "JavaServer Faces 2.0, The Complete Reference");
  put(38.68f, "Pro JSF and HTML5");
 }
});

public Map<Float, String> getBooksMap() {
 return booksMap;
}  

Now, we can display a table containing these books names and prices. The prices are formatted via of:formatCurrency() using $ symbol:

<h:dataTable value="#{bookBean.booksMap.entrySet()}" var="book">
 <h:column>
  <f:facet name="header">Book</f:facet>
  #{book.value}
 </h:column>
 <h:column>
  <f:facet name="header">Price</f:facet>
  #{of:formatCurrency(book.key, "$")}
 </h:column>
</h:dataTable>

duminică, 29 noiembrie 2015

[OmniFaces utilities 2.0/2.4] Format the given bytes to nearest 10^n with IEC binary unit (KiB, MiB, etc)


[OmniFaces utilities] The formatBytes() function formats the given bytes to nearest 10n with IEC binary unit (KiB, MiB, etc) with rounding precision of 1 fraction. For example:
  • 1023 bytes will appear as 1023 B
  • 1024 bytes will appear as 1.0 KiB
  • 500000 bytes will appear as 488.3 KiB
  • 1048576 bytes will appear as 1.0 MiB
. The format locale will be set to the one as obtained by Faces#getLocale().

Function:

OmniFaces 2.4OmniFaces 2.0
See also: Faces#getLocale()
Usage:

Let's suppose that we have a map that contains several files names and their sizes in bytes, as below:

// in real cases, you may loop a folder to extract the files
private final Map<Long, String> fileMap
         = Collections.unmodifiableMap(new HashMap<Long, String>() {
 {
  put(13523424L, "flowers.png");
  put(2343L, "script.txt");
  put(343L, "Demo.java");
  put(4565652L, "paint.jpg");
  put(1024L, "fire.jpg");
 }
});

public Map<Long, String> getFileMap() {
 return fileMap;
}

Now, we can display a table containing these files names and sizes. The sizes are formatted via of:formatBytes():

<h:dataTable value="#{fileBean.fileMap.entrySet()}" var="file">
 <h:column>
  <f:facet name="header">File</f:facet>
  #{file.value}
 </h:column>
 <h:column>
  <f:facet name="header">Size</f:facet>
  #{of:formatBytes(file.key)}
 </h:column>
</h:dataTable>

Output:

sâmbătă, 28 noiembrie 2015

[OmniFaces utilities 2.0] A mapping of days names (full/short names) by day numbers for the current locale


[OmniFaces utilities] The getDaysOfWeek() function returns a mapping of day of week names in ISO 8601 order (Monday first) for the current locale. For example: "Monday=1", "Tuesday=2", etc. This is useful if you want to for example populate a <f:selectItems> which shows all days of week. The locale is obtained by Faces#getLocale(). The mapping is per locale stored in a local cache to improve retrieving performance.

[OmniFaces utilities] The getShortDaysOfWeek() function returns a mapping of short day of week names in ISO 8601 order (Monday first) for the current locale. For example: "Mon=1", "Tue=2", etc. This is useful if you want to for example populate a <f:selectItems> which shows all short days of week. The locale is obtained by Faces#getLocale(). The mapping is per locale stored in a local cache to improve retrieving performance.

[OmniFaces utilities] The getDayOfWeek() function returns the day of week name from the mapping associated with the given day of week number in ISO 8601 order (Monday first) for the current locale. For example: "1=Monday", "2=Tuesday", etc. The locale is obtained by Faces#getLocale().

[OmniFaces utilities] The getShortDayOfWeek() function returns the short day of week name from the mapping associated with the given day of week number in ISO 8601 order (Monday first) for the current locale. For example: "1=Mon", "2=Tue", etc. The locale is obtained by Faces#getLocale().

Function(full names):
Function(short names):

Functions (get day name (full/short name) by day number)

In OmniFaces Showcase you can see how an example of how to populate a <f:selectItems/> which shows all days of week. Below, you can see an example of displaying the days of week numbers and names in a data table.

Full names via of:getDaysOfWeek():

<h:dataTable value="#{of:getDaysOfWeek().entrySet()}" var="t">
 <h:column>
  <f:facet name="header">No.</f:facet>
  #{t.value}
 </h:column>
 <h:column>
  <f:facet name="header">Name</f:facet>
  #{t.key}
 </h:column>
</h:dataTable>

Short names via of:getShortDaysOfWeek():

<h:dataTable value="#{of:getShortDaysOfWeek().entrySet()}" var="t">
 <h:column>
  <f:facet name="header">No.</f:facet>
  #{t.value}
 </h:column>
 <h:column>
  <f:facet name="header">Name</f:facet>
  #{t.key}
 </h:column>
</h:dataTable>

Moreover, we can obtain a day name (short name) by its number via of:getDayOfWeek() and of:getShortDayOfWeek():

The day 4 of the week is: #{of:getDayOfWeek(4)}
Output: Thursday 
The day 4 of the week is: #{of:getShortDayOfWeek(4)}
Output: Thu

The day number can be provided from a managed bean also:

#{of:getDayOfWeek(fooBean.daynumer)}
#{of:getShortDayOfWeek(fooBean.daynumer)}

vineri, 27 noiembrie 2015

[OmniFaces utilities 2.0] A mapping of month names (full/short names) by month numbers for the current locale


[OmniFaces utilities] The getMonths() function returns a mapping of month names by month numbers for the current locale. For example: "January=1", "February=2", etc. This is useful if you want to for example populate a <f:selectItems> which shows all months. The locale is obtained by Faces#getLocale(). The mapping is per locale stored in a local cache to improve retrieving performance.

[OmniFaces utilities] The getShortMonths() function returns a mapping of short month names by month numbers for the current locale. For example: "Jan=1", "Feb=2", etc. This is useful if you want to for example populate a <f:selectItems> which shows all short months. The locale is obtained by Faces#getLocale(). The mapping is per locale stored in a local cache to improve retrieving performance.

[OmniFaces utilities] The getMonth() function returns the month name from the mapping associated with the given month number for the current locale. For example: "1=January", "2=February", etc. The locale is obtained by Faces#getLocale().

[OmniFaces utilities] The getShortMonth() function returns the short month name from the mapping associated with the given month number for the current locale. For example: "1=Jan", "2=Feb", etc. The locale is obtained by Faces#getLocale().

Function (full names):

Function (short names):

Functions (get month name (full/short name) by month number)

Usage:

In OmniFaces Showcase you can see how an example of how to populate a <f:selectItems/> which shows all months. Below, you can see an example of displaying the month numbers and names in a data table.

Full names via of:getMonths():

<h:dataTable value="#{of:getMonths().entrySet()}" var="t">
 <h:column>
  <f:facet name="header">No.</f:facet>
  #{t.value}
 </h:column>
 <h:column>
  <f:facet name="header">Name</f:facet>
  #{t.key}
 </h:column>
</h:dataTable>

Short names via of:getShortMonths():

<h:dataTable value="#{of:getShortMonths().entrySet()}" var="t">
 <h:column>
  <f:facet name="header">No.</f:facet>
  #{t.value}
 </h:column>
 <h:column>
  <f:facet name="header">Name</f:facet>
  #{t.key}
 </h:column>
</h:dataTable>

Moreover, we can obtain a month name (short name) by its number via of:getMonth() and of:getShortMonth():

The 10 month of the year is: #{of:getMonth(10)}
Output: October
The 10 month of the year is: #{of:getShortMonth(10)}
Output: Oct

The month number can be provided from a managed bean also:

#{of:getMonth(fooBean.monthnumer)}
#{of:getShortMonth(fooBean.monthnumer)}

JSF Scopes Tutorial - JSF None Scope

The none scoped beans lives to serve other beans
The none scoped beans lives to serve other beans. The none scope seems to be the "black sheep" of JSF scopes. Even its name doesn't inspire something useful. Practically, a managed bean in this scope lives as long as a single EL expression evaluation and is not visible in any JSF page - JSF will not store it, which means that the caller can use it only if it stores the evaluated reference itself. If the application scope lives the longest, this scope lives the shortest. But, if you inject the none scoped managed beans in other managed beans, then they will live as long as their hosts.  The none scoped objects used in the configuration file indicate managed beans that are used by other managed beans in the application. So, whenever you need a humble managed bean that is ready to be a part of a cool scope, such as a request or a session, you can annotate it with @NoneScoped, available in the javax.faces.bean package. Moreover, objects with the none scope can use other objects with the none scope.

Let's see a simple example:

@ManagedBean
@NoneScoped
public class InitBean implements Serializable {
   
 private static final Logger LOG = Logger.getLogger(InitBean.class.getName());
       
 private int init;

 public InitBean() {
  LOG.info("InitBean#Constructor invoked ...");
  init = 5;
 }

 public int getInit() {
  return init;
 }

 public void setInit(int init) {
  this.init = init;
 }
}

<h:body>              
 Current init value: #{initBean.init}  
 Current init value: #{initBean.init}  
 Current init value: #{initBean.init}  
</h:body>

Since we are using the init property in three ELs, the none scoped bean will be constructed three times (three different instances). But, this is happening in a single request! So, for each EL that uses a property from a none scoped bean, JSF will create a separate instance of that bean!


But, as we said above, the none scoped beans lives to serve other beans. Per example, let's inject the InitBean into a session bean, CountBean, as below:

@ManagedBean
@SessionScoped
public class CountBean implements Serializable {

 @ManagedProperty(value = "#{initBean}")
 private InitBean initBean;

 private static final Logger LOG = Logger.getLogger(CountBean.class.getName());

 private int count;

 public CountBean() {
  LOG.info("CountBean#Initializing counter ...");
  count = 0; // will be override in the init() method
 }

 @PostConstruct
 public void init() {
  LOG.info("CountBean#Initializing counter with @PostConstruct ...");
  count = initBean.getInit();
 }

 public void increaseCount() {
  count++;
  initBean.setInit(count);
  LOG.log(Level.INFO, "Current value: {0}", count);
 }

 public InitBean getInitBean() {
  return initBean;
 }

 public void setInitBean(InitBean initBean) {
  this.initBean = initBean;
 }

 public int getCount() {
  return count;
 }

 public void setCount(int count) {
  this.count = count;
 }
}
And, we adjust the JSF page as below:

<h:body>             
 Current init value: #{initBean.init}
 Current init value: #{initBean.init}
 Current init value: #{initBean.init}   
 <hr/>
 Current init value (via session bean): #{countBean.initBean.init}
 Current count value (via session bean): #{countBean.count}         
 <h:form>
  <h:commandButton value="Count" action="#{countBean.increaseCount()}"/>
 </h:form>      
</h:body>

Now, notice that the injected instance lives as long as its "host" lives - the session scoped bean, CountBean. You can notice this from the below two screenshots:



The complete application is available here.

Below you can see the diagrams for injecting JSF none scoped beans exemplified on a session scoped bean:


So, once you understand the none scope, it starts to look pretty useful. Compared to the rest of scopes this one is quite flexible. It allows us to "attach" a scope to scope-less data via injection. Practically, we can use @ManagedProperty in any bean of any scope for injecting scope-less data and expose them further as bean properties. Per example, in the same time, we can inject the a none scoped bean in a request, a session and an application scoped bean without the need to duplicate the bean and annotate them with acceptable scopes to be eligible for injection (remember that JSF doesn't allow us to use objects that have shorter lifespan than the objects you are calling it from).

See you in the next post about the CDI singleton pseudo-scope.

JSF BOOKS COLLECTION

Postări populare

OmniFaces/JSF Fans

Follow by Email

Visitors Starting 4 September 2015

Locations of Site Visitors