我希望能够在PrimeFaces数据表中从数据库动态加载图像。 代码如下,基于此PF论坛主题:
```html
```
请注意,在value属性中使用了EL表达式来获取图像的ID并将其传递给后台bean的getImage方法。
然而,我无法使其工作。我的参数将“null”传递给我的后端bean。这是如何引起的,我该如何解决?
我正在使用Netbeans 6.9.1,JSF 2.0和Primefaces 2.2.RC2。
我首先尝试了BalusC的解决方案,它可以正常工作,但UI中未呈现图像。 Glassfish抛出以下异常:
<p:dataTable id="tablaInventario" var="inv" value="#{registrarPedidoController.inventarioList}" paginator="true" rows="10"
selection="#{registrarPedidoController.inventarioSelected}" selectionMode="single"
update="tablaInventario tablaDetalle total totalDesc" dblClickSelect="false" paginatorPosition="bottom">
<p:column sortBy="producto.codigo" filterBy="producto.codigo">
<f:facet name="header">#{msg.codigo}</f:facet>
#{inv.producto.codProducto}
</p:column>
<p:column>
<f:facet name="header">Foto</f:facet>
<p:graphicImage id="photo" value="#{registrarPedidoController.streamedImageById}" cache="FALSE">
<f:param name="inv" value="#{inv.id}" />
</p:graphicImage>
</p:column>
</p:dataTable>
使用
public StreamedContent getStreamedImageById() {
DefaultStreamedContent image = null;
String get = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("inv");
System.out.println("[Param]: " + get); // This prints null.
Long id = new Long(get);
List<Inventario> listInventarios = controladorRegistrarPedido.listInventarios();
for (Inventario i : listInventarios) {
if (i.getId().compareTo(id) == 0) {
byte[] foto = i.getProducto().getFoto();
image = new DefaultStreamedContent(new ByteArrayInputStream(foto), "image/png");
}
}
return image;
}
然而,我无法使其工作。我的参数将“null”传递给我的后端bean。这是如何引起的,我该如何解决?
我正在使用Netbeans 6.9.1,JSF 2.0和Primefaces 2.2.RC2。
我首先尝试了BalusC的解决方案,它可以正常工作,但UI中未呈现图像。 Glassfish抛出以下异常:
WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NullPointerException
at com.sun.faces.mgbean.BeanManager$ScopeManager$ViewScopeHandler.isInScope(BeanManager.java:552)
感谢BalusC的帮助,我终于能够工作了。为了管理getStreamedImageId,我必须使用RequestScoped、SessionScoped或ApplicationScoped。然而,在UI中总是设置默认图像(对于空值情况),而不是与每一行相对应的预期图像。新代码如下:
public StreamedContent streamedById(Long id) {
DefaultStreamedContent image = null;
System.out.println("[ID inventario]: " + id);
List<Inventario> listInventarios = controladorRegistrarPedido.listInventarios();
for (Inventario i : listInventarios) {
if (i.getId().equals(id)) {
byte[] foto = i.getProducto().getFoto();
if (foto != null) {
System.out.println(" [Foto]: " + foto);
image = new DefaultStreamedContent(new ByteArrayInputStream(foto), "image/png");
break;
}
}
}
if (image == null) {
System.out.println(" [Image null]");
byte[] foto = listInventarios.get(0).getProducto().getFoto();
image = new DefaultStreamedContent(new ByteArrayInputStream(foto), "image/png");
}
System.out.println(" [Foto Streamed]: " + image);
return image;
}
p:graphicImage
内容的 bean 需要是请求作用域、会话作用域(如果本身是无状态的,甚至可以是应用程序作用域)。视图作用域不被支持。您需要将视图作用域 bean 中的方法分离到适当作用域的单独 bean 中。这也有额外的好处,即更好地可重用于其他地方。 - BalusC