Let's
suppose that we have an enum an a helper class, as below:
PlayerEnum
package
my.artifacts;
public enum
PlayerEnum {
RAFAEL_NADAL, ROGER_FEDERER, ANDY_MURRAY,
NOVAK_DJOKOVIC, MILOS_RAONIC;
public String getFriendlyName(){
String
firstName = name().substring(0, name().indexOf("_"));
String
secondName = name().substring(name().indexOf("_")+1);
return
firstName.charAt(0) + firstName.substring(1).toLowerCase() + " " +
secondName.charAt(0) + secondName.substring(1).toLowerCase();
}
}
PlayerHelper
package
my.artifacts;
import
java.util.Random;
public final
class PlayerHelper {
public static String addPlayerRank(String
name) {
Random rnd = new Random();
if
(rnd.nextInt(10) < 5) {
return "Successfully added, " + name + "!";
}
return
"Ooops! That player " + name + " exist in ATP ranking!";
}
}
Now, in the
JSF page, we want to invoke the PlayerHelper#addPlayerRank() method with the
argument, PlayerEnum#ANDY_MURRAY#getFriendlyName()
- this could be also a constant of type public static final ... .
The problem is that we cannot access constants or such helper classes via EL. Of course, we
can wrap the enum
in a bean property and the helper class methods in custom Facelets taglib
functions, but it will be much simpler to use OmniFaces <o:inportConstants> and
<o:inportFunctions>,
which allows us to do this:
<o:importConstants
type="my.artifacts.PlayerEnum"/>
<o:importFunctions
type="my.artifacts.PlayerHelper"/>
<h5>Insert
Andy Murray (PlayerEnum.ANDY_MURRAY) in ATP</h5><br/>
#{PlayerHelper:addPlayerRank(PlayerEnum.ANDY_MURRAY.getFriendlyName())}
or, using a var
attribute:
<o:importConstants
type="my.artifacts.PlayerEnum" var="pe"/>
<o:importFunctions
type="my.artifacts.PlayerHelper" var="ph"/>
<h5>Insert
Andy Murray (PlayerEnum.ANDY_MURRAY) in ATP</h5><br/>
#{ph:addPlayerRank(pe.ANDY_MURRAY.getFriendlyName())}
Complete
source code in GitHub.
More
examples in OmniFaces Showcase.
Niciun comentariu :
Trimiteți un comentariu