@FacesConverter
使用注释时,每次引用它们时都会创建一次转换器。这意味着如果你在那里执行慢代码,它会给你带来问题。
或者,您可以使用所需的范围对它们进行注释,并将@ManagedBean
它们与EL 引用而不是原始转换器 id 一起使用。如果您想以某种方式初始化它们,您的解决方案是为它们设置整个应用程序的范围并使它们急切地初始化,因此它们将在应用程序启动时创建:
转换器:
@ManagedBean(eager = true)
@ApplicationScoped
public class WorkerConverter implements Converter {
public WorkerConverter() {
System.out.println("Building converter...");
}
@Override
public Object getAsObject(FacesContext context, UIComponent component,
String value) {
Integer id = Integer.parseInt(value);
if (id == 1) {
return new Worker(1, "John");
} else {
return new Worker(1, "Larry");
}
}
@Override
public String getAsString(FacesContext context, UIComponent component,
Object value) {
return ((Worker) value).getId().toString();
}
}
托管豆:
@ManagedBean
@ViewScoped
public class SelectWorkerBean {
public static class Worker {
Integer id;
String name;
public Worker(Integer id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Worker other = (Worker) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
@Override
public int hashCode() {
return id;
}
@Override
public String toString() {
return "Worker [name=" + name + "]";
}
}
private Worker selectedWorker;
private List<Worker> workers = Arrays.asList(new Worker(1, "John"),
new Worker(2, "Larry"));
public Worker getSelectedWorker() {
return selectedWorker;
}
public List<Worker> getWorkers() {
return workers;
}
public void send() {
System.out.println(selectedWorker + " selected");
}
public void setSelectedWorker(Worker selectedWorker) {
this.selectedWorker = selectedWorker;
}
}
页:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Test page</title>
</h:head>
<h:body>
<h:form>
<h:selectOneMenu value="#{selectWorkerBean.selectedWorker}"
converter="#{workerConverter}">
<f:selectItems value="#{selectWorkerBean.workers}" var="worker"
itemLabel="#{worker.name}" />
</h:selectOneMenu>
<h:commandButton value="send" action="#{selectWorkerBean.send}" />
</h:form>
</h:body>
</html>