我有一个简单的复合组件,它必须渲染一个inputText。当一个put值并按下commandButton后跟随异常就是throw:
java.lang.IllegalArgumentException: Cannot convert 1 of type class java.lang.String to class sample.entity.Product
当我使用h:inputText代替d:myInputText时,它可以正常工作。
是否可以为复合组件使用FacesConverter和属性forClass?我不喜欢使用标签f:converter的converter属性或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 + '}';
}
}
我使用Mojarra 2.1.14,Glassfish 3.1和CDI。 最好的问候。
答案 0 :(得分:2)
我能够在Mojarra 2.1.14中重现它。这是Mojarra的一个错误。它在MyFaces 2.1.9中运行良好。我已经向Mojarra家伙报告了issue 2568。与此同时,除了明确指定客户端中的<f:converter for>
或移动到MyFaces(其中也有自己的一组特定怪癖/问题)之外,没有其他选择。