Что делает ELContext в моем JSF-конвертере - PullRequest
1 голос
/ 22 ноября 2011

Привет! Я создал собственный конвертер в jsf для поля со списком, используя h: selectOneMenu,

мой код поддержки бина в следующем

@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 ()?

1 Ответ

2 голосов
/ 22 ноября 2011

Он получает ELContext (<- щелкните ссылку, чтобы увидеть javadoc), чтобы вы могли программно оценить выражение EL <code>#{} в коде Java.В вашем конкретном случае вы в основном программно оцениваете выражение EL #{studentMgBean}, чтобы получить текущий экземпляр StudentMBean.

В JSF 2.0, кстати, есть ярлык на Application#evaluateExpressionGet(), который делает то же самое и скрывает детали ELContext под капотами:

StudentMBean studentMgBean = (StudentMBean) ctx.getApplication().evaluateExpressionGet(ctx, "#{studentMgBean}", StudentMBean.class);

Тем не менее, ваш подход довольно неуклюж.Если конвертер тесно связан с компонентом поддержки, лучше вместо этого сделать его свойством компонента:

converter="#{studentMgBean.studentConverter}"

с преобразователем в качестве внутреннего класса.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...