您好我使用h:selectOneMenu在jsf中为组合框创建了一个自定义转换器,
我的支持bean代码如下
@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);
}
}
}
这是我的转换器,
@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;
}
这是我的jsp,我将我的转换器应用到组合框
<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>
.....
....
..
现在我的问题是这条线在我的转换器中做了什么
vex = ctx.getApplication().getExpressionFactory()
.createValueExpression(ctx.getELContext(),"#{studentMgBean}", StudentMBean.class);
studentMgmtBean = (StudentMBean) vex.getValue(ctx.getELContext());
ctx.getElContext()做什么?
答案 0 :(得分:2)
它获取ELContext
(&lt; - 单击链接以查看javadoc),以便您能够以编程方式在Java代码中评估EL表达式#{}
。在您的特定情况下,您基本上以编程方式评估EL表达式#{studentMgBean}
以获取StudentMBean
的当前实例。
在JSF 2.0中,Application#evaluateExpressionGet()
的快捷方式基本相同,隐藏了ELContext
详细信息:
StudentMBean studentMgBean = (StudentMBean) ctx.getApplication().evaluateExpressionGet(ctx, "#{studentMgBean}", StudentMBean.class);
那就是说,你的方法非常笨拙。如果转换器紧密耦合到支持bean,你可能最好使它成为支持bean的属性:
converter="#{studentMgBean.studentConverter}"
将转换器作为内部类。