JSF 2 - generating images from binary data
I'm u开发者_JAVA百科sing on my JSF 2 project Primefaces 3.0.M2
as primary compenent library. It works so far very well but the graphicImage component seems to be broken. It only renders images one time - I load the given page, image is shown, when I reload the same page the image (streamedcontent) is gone and in my log I only recieve a
29.08.2011 08:39:03 org.primefaces.application.PrimeResourceHandler handleResourceRequest
SCHWERWIEGEND: Error in streaming dynamic resource.
Is there a other proper/good/best way to display images from a binary data stream? Or do I have to create a servlet which handles this for me?
I'm using
- Mojarra 2.1.2
- Primefaces 3.0.M2
- Spring 3.0.5
This sounds to me like the StreamedContent property of the Managed Bean is being reset back to null because the the bean is being destroyed and recreated on postback.
This may be because your bean is @RequestScoped
.
Try setting your bean to @ViewScoped
or @SessionScoped
so that it persists beyond post backs.
You may find this stackoverflow thread useful - How to use p:graphicImage with StreamedContent within p:dataTable?
But basically, it seems there are at least two things about p:graphicimage that you must know (I don't know why primefaces oficial documentation and demo doesn't say a word about this but anyway)
- your image is not available during the RENDER_RESPONSE phase
- @ViewScoped won't work
So here's the code that worked for me
[1] Managed bean is session scoped and the bean attribute is not DefaultStreamedContent (which is not serializable) but byte[].
@ManagedBean
@SessionScoped
public class ImageController implements Serializable{
private byte[] img;
[2] the dynamic image getter method is
public DefaultStreamedContent getContent(){
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
}else{
if (img == null){
return new DefaultStreamedContent();
}else{
return new DefaultStreamedContent(new ByteArrayInputStream(img), "image/png");
}
}
}
精彩评论