Converter class getAsObject pass parameter to Service class which accepts object

我的梦境 提交于 2019-11-28 12:58:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!