4
我有一個簡單的複合組件,它必須呈現一個inputText。當把值並按的commandButton後續的例外是拋出:FacesConverter forClass不能與Composite Componet一起工作
java.lang.IllegalArgumentException: Cannot convert 1 of type class java.lang.String to class sample.entity.Product
當我使用H:inputText的,而不是d:myInputText它的做工精細。
是否可以使用FacesConverter和屬性forClass作爲複合組件?我不喜歡使用標籤f:轉換器的轉換器屬性或converterId。 有人幫我嗎?
頁代碼:
<h:form>
<h:messages />
Product Id: <h:myInputText value="#{productController.product}"/>
<h:commandButton value="Submit" action="#{productController.someAction()}" />
Product Description: <h:outputText value="#{productController.product.description}"/>
</h:form>
複合碼:
<composite:interface>
<composite:attribute name="value"/>
<composite:editableValueHolder name="value" targets="#{cc.clientId}:value"/>
</composite:interface>
<composite:implementation>
<div id="#{cc.clientId}">
<h:inputText id="value" value="#{cc.attrs.value}"/>
<h:message for="#{cc.clientId}:value" />
</div>
</composite:implementation>
ManagedBean代碼:
@Named("productController")
@RequestScoped
public class ProductController {
private Product product;
public Product getProduct() {
if (product == null) {
product = new Product();
}
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public void someAction() {
System.out.println("Product " + product);
}
}
轉換器代碼:
@FacesConverter(forClass = Product.class)
public class ProductConverter implements Converter {
@Override
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
System.out.println("[DEBUG] getAsObject: " + value);
if (value == null || "".equals(value)) {
return null;
}
//TODO: some logic to get entity from database.
return new Product(new Long(value));
}
@Override
public String getAsString(FacesContext fc, UIComponent uic, Object o) {
System.out.println("[DEBUG] getAsString: " + o);
if (o == null) {
return null;
}
return String.valueOf(((Product) o).getId());
}
}
實體代碼:
public class Product {
private Long id;
private String description;
public Product() {
}
public Product(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Product other = (Product) obj;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Product{" + "id=" + id + '}';
}
}
我用鑽嘴魚科2.1.14,Glassfish的3.1和CDI。 此致敬禮。
我試過你的解決方案,但還沒有工作。 順便說一句,如果我指定類型我的複合不能用於其他實體像客戶端。 –
你說得對。查看更新後的答案。我會檢查原因,然後報告給Mojarra傢伙。 – BalusC