Hi i have created a custom converter in jsf for combo box using h:selectOneMenu,
my backing bean code in as follows
@ManagedBean(name="studentMgBean")
public class StudentMBean {
..............
............
.....
public StudentVO getMyStudent(Integer studentId) {
return this.myStudents.get(studentId);
}
private List<SelectItem> studentList;
// getter setter of studentList
private Map<Integer,StudentVO> myStudents;
private StudentVO selectedStudent;
// getter setter of selectedStudent
@PostConstruct
public void loadStudents(){
..........
........
if(this.getStudentList() == null){
this.setStudentList(new ArrayList<SelectItem>());
}else{
this.getStudentList().clear();
}
this.myStudents = new HashMap<Integer, StudentVO>();
while(rs.next()){
vo = new StudentVO(String.valueOf(rs.getInt("studentId")),
rs.getString("studentName"), rs.getString("contactNo"));
selectItem = new SelectItem(vo.getStudentId(), vo.getStudentName());
this.getStudentList().add(selectItem);
this.myStudents.put(Integer.parseInt(vo.getStudentId()),vo);
}
}
}
this is my converter,
@FacesConverter(value="studentComboConv")
public class StudentComboBoxConverter implements Converter{
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
FacesContext ctx = null;
ValueExpression vex = null;
StudentMBean studentMgmtBean = null;
StudentVO studentVO = null;
.........
........
......
vex = ctx.getApplication().getExpressionFactory()
.createValueExpression(ctx.getELContext(),"#{studentMgBean}", StudentMBean.class);
studentMgmtBean = (StudentMBean) vex.getValue(ctx.getELContext());
studentVO = studentMgmtBean.getMyStudent(Integer.parseInt(value));
...........
........
.....
return studentVO;
}
and this is my jsp where i am applying my converter to the combo box
<td align="left">SELECT STUDENT</td>
<td align="right">
<h:selectOneMenu value="#{studentMgBean.selectedStudent}" id="cmbo" converter="studentComboConv">
<f:selectItems value="#{studentMgBean.studentList}" />
</h:selectOneMenu>
.....
....
..
Now my question is what does this line do in my converter
vex = ctx.getApplication().getExpressionFactory()
.createValueExpression(ctx.getELContext(),"#{studentMgBean}", StudentMBean.class);
studentMgmtBean = (StudentMBean) vex.getValue(ctx.getELContext());
What does ctx.getElContext() do ?
It obtains the
ELContext(<– click the link to see the javadoc), so that you’re able to evaluate an EL expression#{}programmatically in Java code. In your particular case, you’re basically programmatically evaluating the EL expression#{studentMgBean}to get the current instance ofStudentMBean.In JSF 2.0 there’s by the way a shortcut by
Application#evaluateExpressionGet()which does basically the same and hides theELContextdetails under the hoods:That said, your approach is pretty clumsy. If the converter is that tight coupled to a backing bean, you’d probably better make it a property of the backing bean instead:
with the converter as an inner class.