我为jsf创建了一个自定义转换器。 getAsObject()工作正常,但getAsString()返回异常。我不确定问题出在哪里,我已经尝试以不同的方式将对象转换为字符串,但它一直在返回异常。
这是我的转换器代码:
@Named
public class ProductConverter implements Converter{
@EJB
private ProductEJB productEjb;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(value== null )
{
throw new ConverterException("There was an error at getAsObject()");
}
int id = Integer.parseInt(value);
return productEjb.findProductById(id);
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null || value.equals(""))
{
return "";
}
else
{
Integer id = ((Product)value).getProduct_id();
return String.valueOf(id);
}
}
}
这是Product类(为简单起见,排除了Getters / Setters / equals()/ hash()):
@Entity
@NamedQueries({
@NamedQuery(name="findAllProducts", query = "SELECT p from Product p")
})
public class Product implements Serializable
{
private static final long serialVersionUID = 1L;
@Id @GeneratedValue(strategy= GenerationType.AUTO)
private int product_id;
private String name;
private String description;
protected byte[] imageFile;
private Float price;
@Temporal(TemporalType.TIMESTAMP)
private Date dateAdded;
@ManyToOne
private Category category_fk;
@ManyToOne
private SaleDetails saleDetails_fk;
这是我得到的堆栈:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at com.lv.Controllers.Converters.ProductConverter.getAsObject(ProductConverter.java:30)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:171)
at javax.faces.component.UIViewParameter.getConvertedValue(UIViewParameter.java:394)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at javax.faces.component.UIViewParameter.processValidators(UIViewParameter.java:273)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1172)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
这是我使用转换器的jsf:
<f:metadata>
<f:viewParam name="product" value="#{productDelete.product}" converter="#{productConverter}"/>
</f:metadata>
答案 0 :(得分:5)
当收到null
或空值时,不要抛出异常。这毫无意义。它们可能代表合法有效的值,只代表“无价值”。然后返回null
。如果您想强制要求,那么您应该使用required="true"
或任何自定义Validator
,但不要在Converter
中执行此操作。
只有当值真正不可转换时,才应抛出ConverterException
。我已经改进了你的转换器来做到这一点。您不是检查提交的值是否为有效数字,也不是检查获得的模型值是Product
的实例。否则会导致NumberFormatException
或ClassCastException
进一步降低代码,您应该通过抛出适当的ConverterException
来预防。
@Named
public class ProductConverter implements Converter {
@EJB
private ProductEJB productEjb;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.isEmpty()) {
return null;
}
if (!value.matches("\\d+")) {
throw new ConverterException("The value is not a valid ID number: " + value);
}
int id = Integer.parseInt(value);
return productEjb.findProductById(id);
// You may want to perform an additional check if it didn't return null
// and otherwise throw ConverterException with "unknown Product ID".
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return null; // Or an empty string, can also.
}
if (!(value instanceof Product)) {
throw new ConverterException("The value is not a valid Product: " + value);
}
Integer id = ((Product)value).getProduct_id();
return (id != null) ? String.valueOf(id) : null;
}
}
答案 1 :(得分:2)
当值为null时,看起来您的方法无法处理。在这种情况下尝试返回一个空字符串
public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
if (value == null || value.equals("")) {
return "";
} else {
Integer id = ((Product)value).getProduct_id();
return String.valueOf(id);
}
}
答案 2 :(得分:1)
值表达式#{productDelete.product}
正在解析为null。
注意:转换器的contract表明getAsString
为空值返回空字符串。