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());
}
}