问题
I have question regarding Converter class getAsObject
method
I have a service called EmployeeService employeeService
public List<Employees> getEmployees(Employees employees);
If I want to call the above method from getAsObject of Converter class which as arguments
public Object getAsObject(FacesContext facesContext, UIComponent component,
String value)
employeeService.getEmployees(<?>)
How do I pass employees
object to getEmployees
method from getAsObject
?
Any help is highly appreciated.
Update 1
@Entity
public class Employees implements Serializable {
private String employeeNumber;
private String employeeName;
回答1:
Use a following converter, that simply converts number (which is a String
, according to your code) to Employee
object:
@Named("employeeConverter")
public class EmployeeConverter implements Converter {
@Inject
private EmployeeService employeeService;
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(value == null || value.equals("")) {
return null;
}
Employee employee = employeeService.getEmployeeByNumber(value);//or if it is not a String, replace value with Integer.parseInt(value)
if(employee == null) {
throw new ConverterException(new FacesMessage("Employee with number: " + value + " not found."));
}
return employee;
}
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (!(value instanceof Employee) || (value == null)) {
return null;
}
return ((Employee)value).getEmployeeNumber();
}
}
and use it in your views by converter="#{employeeConverter}"
.
来源:https://stackoverflow.com/questions/15021233/converter-class-getasobject-pass-parameter-to-service-class-which-accepts-object