我的JSF页面中有p:selectOneMenu,当我运行JSF页面时,我从Converter类收到以下异常。
java.lang.IllegalArgumentException: object 5634 is of type java.lang.String; expected type: test.entity.Employee
我该如何解决这个问题?
我在实体类中有以下内容
@Entity public class Employee implements Serializable { private String employeeNumber; private String employeeName; /* getters and setters */
EmployeeConverter类
@Component("employeeConverter") @FacesConverter(forClass = Employee.class) @Inject EmployeeService employeeService; @Override public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } EmployeeService employeeService= (EmployeeService ) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "employeeService"); return employeeService.getEmployees(); } @Override public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Employee) { Employee emp = (Employee) object; String val = emp.getEmployeeNumber(); return val; } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Employee.class.getName()); } }
并在jsf页面中
<p:selectOneMenu value="#{mb.employee}" converter="#{employeeConverter}"> <f:selectItems value="#{cmb.employeeList}" var="emp" itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeNumber}"/> <p:ajax listener="#{mb.handleChange}" process="@this"/> </p:selectOneMenu>
更新1
修改的转换器方法 getAsObject
getAsObject
private List<Employee> employee; @Override public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { System.out.println("reached in converter"); try { if (value == null || value.length() == 0) { return null; } else { employee = getEmployeeService().getEmployees(); for (Employee emp : employee) { if (emp.getEmployeeNUmber() == value) { return emp; } } } } catch (Exception e) { System.out.println("exception from getAsObject " + e.getMessage()); } return null; }
更新2
ManagedBean @PostConstruct public void loadEmployees(){ try { List<Employee> emp = getEmployeeService().getEmployees(); employeeList = emp; } catch(Exception e){ e.printStackTrace(); System.out.println("exception from loadEmployees "+e.getMessage()); } }
用您的getAsObject方法,您无法达到自己的价值。在这里,您将收到#{emp.employeeNumber},因此您必须将其转换为Employee(可能必须实现Employee使用Service locator 加载by id的方法)并返回对象本身。
#{emp.employeeNumber}
Employee
您还使用EL(#{employeeConverter})引用了转换器,因此必须直接进行操作。最后,元素列表必须由组成SelectItem,以使f:selectItems标签起作用。
#{employeeConverter}
SelectItem
f:selectItems