我从 JSF(Mojarra 2.2 和 Glassfish 4)开始,目前正在练习一个 Web 应用程序,该应用程序的工作是将客户及其订单存储在数据库中。
创建新订单时,一项功能是允许从 JSF 中选择现有客户端<h:selectOneMenu>
。Order 实体将 Client 实体存储在其他属性中......
我遵循了 BalusC 关于<h:selectOneMenu>
从数据库(此处)预填充 a 的出色答案,并已成功地从存储在急切的 ApplicationScoped ManagedBean 中的数据中填充了我的内容,但我无法设法将支持 bean 中的选定项目作为复杂对象检索。它始终为空。
这让我发疯,您的帮助将不胜感激!以下是相关的代码片段:
@ManagedBean(eager = true)
@ApplicationScoped
public class Data implements Serializable {
private static final long serialVersionUID = 1L;
@EJB
private ClientDao clientDao;
private List<Client> clients;
@PostConstruct
private void init() {
clients = clientDao.lister();
}
public List<Client> getClients() {
return clients;
}
}
订单创建 bean(注意:'commande' 表示订单;)
@ManagedBean
@RequestScoped
public class CreerCommandeBean implements Serializable {
private static final long serialVersionUID = 1L;
private Commande commande;
private String choixNouveauClient = "nouveauClient";
@EJB
private CommandeDao commandeDao;
public CreerCommandeBean() {
commande = new Commande();
}
public void inscrire() {
System.out.println("client : " + commande.getClient()); // prints **NULL**
// ... orderService to store in DB
}
... getters and setters
客户端转换器:
@FacesConverter(value = "clientConverter", forClass = Client.class)
public class ClientConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null) {
return null;
}
Data data = context.getApplication().evaluateExpressionGet(context, "#{data}", Data.class);
for (Client c : data.getClients()) {
if (c.getId().toString().equals(value)) {
return c;
}
}
throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to Client", value)));
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return (value instanceof Client) ? String.valueOf(((Client) value).getId()) : null;
}
}
面子摘录:
<p:outputPanel id="gridContainerAncienClient">
<p:selectOneMenu value="#{creerCommandeBean.commande.client}"
rendered="#{creerCommandeBean.choixNouveauClient == 'ancienClient'}">
<f:converter converterId="clientConverter" />
<f:selectItems value="#{data.clients}" var="cli"
itemValue="#{cli}" itemLabel="#{cli.prenom} #{cli.nom}" />
</p:selectOneMenu>
</p:outputPanel>