这是我的代码
public class Deal implements Serializable {
private int id;
private String name;
private String description;
private Customer customer;
//getter setter omitted
}
public class Customer implements Serializable {
private int id;
private String name;
private String email;
private String phone;
//getter setter and equal hashcode omitted
}
@ManagedBean(name="dealBean")
@ViewScoped
public class DealBean implements Serializable {
private List<Customer> customerList;
private List<Deal> dealList;
private Deal deal;
@PostConstruct
public void init() {
deal = new Deal();
dealList = new ArrayList<Deal>();
customerList = new ArrayList<Customer>();
customerList.add(new Customer(1, "MPRL", "mprl@mail.com", "1234455"));
customerList.add(new Customer(2, "Total", "total@mail.com", "3434323"));
customerList.add(new Customer(3, "Petronas", "petronas@mail.com", "8989876"));
}
//getter setter omitted
}
@FacesConverter("customerConverter")
public class CustomerConverter implements Converter {
@Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String customerID) {
DealBean dealBean = (DealBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("dealBean");
if (dealBean != null) {
List<Customer> customerList = dealBean.getCustomerList();
for (Customer customer : customerList) {
if (customerID.equals(String.valueOf(customer.getId()))) {
return customer;
}
}
}
return null;
}
@Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object obj) {
if (obj != null) {
return String.valueOf(((Customer)obj).getId());
}
return null;
}
}
Customer : <h:selectOneMenu id="customer" value="#{dealBean.deal.customer}">
<f:converter converterId="customerConverter" />
<f:selectItems value="#{dealBean.customerList}" var="cus"
itemLabel="#{cus.name}" itemValue="#{cus}" />
</h:selectOneMenu>
当托管bean处于请求或会话范围内时,Customer pojo被正确设置为Deal pojo。问题是当托管bean在View范围内时,Customer pojo被设置为Deal pojo为NULL。
我正在使用JSF 2.2.0
非常感谢您的帮助。
答案 0 :(得分:1)
它不是转换器,视图范围是破坏的:
由于您使用的是JSF标记,因此无法使用@ViewScoped
注释,因为它已从规范中删除并仅为CDI使用而恢复。您可以使用omnifaces view scoped或apache myFaces的组件(我个人推荐omnifaces)。
您可以确认这创建一个
System.out.print("Creating");
在构造函数中并检查如何调用每个Ajax请求,因此bean没有被恢复,因为被标记为视图并且是部分请求,所以不再设置值(除非您发送所有表单,这不是一个很好的解决方案),其他解决方法可能是发出bean请求并恢复每个请求的所有数据,使其成为Session(但会为会话活动),或者@ConvesationScoped,你必须在其中销毁和手动启动对话。 同样,我的第一个建议可能是更改为符合Java ee服务器并使用CDI注释,因为JSF正在折旧且不再更新