Sunday, December 19, 2010

Setting locale programmatically in jsf

In jsf you can set locale programmatically by this


UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
viewRoot.setLocale(new Locale("de"));


Friday, December 17, 2010

Setting value through EL in JSF

Sample method can be used to set new object programmatically:


public static void setObject(String expression, Object newValue) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, expression,
Object.class);

//Check that the input newValue can be cast to the property type
//expected by the managed bean.
//Rely on Auto-Unboxing if the managed Bean expects a primitive
Class bindClass = valueExp.getType(elContext);
if (bindClass.isPrimitive() || bindClass.isInstance(newValue)) {
valueExp.setValue(elContext, newValue);
}
}


Resolving Method expression programmatically In JSF

EL is used in JSF to bind java methods with userinterface actions like commandbutton and commandlink. But sometimes It is needed to resolve method binding programmatically. Sample method can be used for this purpose:


public static Object resloveMethodExpression(String expression,
Class returnType,
Class[] argTypes,
Object[] argValues) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
MethodExpression methodExpression =
elFactory.createMethodExpression(elContext, expression, returnType,
argTypes);
return methodExpression.invoke(elContext, argValues);
}


Resolving EL programmatically to retrieve value

EL is used in JSF to set values from java classes with User Interface. Sometimes, EL is needed to resolve programmatically to retrieve value. Sample method can be used for this purpose:


public static Object resolveExpression(String expression) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, expression,
Object.class);
return valueExp.getValue(elContext);
}