我的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
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());
}
}
不要将字符串分配给项值,您需要分配转换后的对象(Employee)本身。
更改为itemValue="#{emp}"
请参阅BalusC对此问题的回答。
在getAsObject
方法中,您对所达到的值没有做任何操作。在这里,您将收到您的#{emp.employeeNumber}
,因此您必须将其转换为Employee
(可能您必须实现一个方法,该方法使用服务定位器通过id加载Employee
),并返回对象本身。
您还使用EL(#{employeeConverter}
)引用转换器,必须以直接的方式进行。最后,元素列表必须由SelectItem
组成,才能使f:selectItems
标签工作。