Search code examples
javamysqlspringimagejsf-2

Spring + JSF - Retrieve Image from Database and Show in Brower


I am developing a web site with Spring 4 + JSF 2.0 framework + MySQL Database. I'm trying to retrieve a image from database and display it on browser. So basically I have a table called product_t with a LongBlob column called image, which is responsible to store png files.

I need to retrieve each image from each product in a page, so:

<ui:repeat value="#{productControllerImpl.list3NotNewRandomProducts()} var="product" varStatus="status">
<h2>#{product.name}</h2>
<strong>#{product.subDescription}</strong><br></br> <span>#{product.description}
</ui:repeat>

So far so good.

I search on google the following solution:

For each product in UI I need to call a Servlet in order to retrieve the image. As I'm using JSF + Spring, I wrote the following block code in UI:

<h:graphicImage   value="/images/#{productControllerImpl.findProductImageById(product.id)}"/>

And in my productControllerImpl I have this:

@Override
public byte[] findProductImageById(Long productId) {
    byte[] productImage = null;
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();      
    ServletOutputStream outputStream = null; 
    try {
        productImage = productService.findProductImageById(productId);
        response.reset();           
        outputStream = response.getOutputStream();
        response.setContentType("image/png");
        outputStream.write(productImage);
        outputStream.flush();       
        outputStream.close();
    } catch(Throwable e){
        throw new RuntimeException("Error processing product image: " + e.getMessage(), e);
    }

    return null;
}

So basically I am receiving the producIt from iteration, and search on database for the respective product image (I don't know if this is the best choice).

The problem here is, when this page is accessed I receive the full image in browser:

Product Image

And I'm pretty lost in this part.

Does anybody knows what I am missing here?

Thanks in advance.


Solution

  • I assume you're referring to Show image as byte[] from database as graphic image in JSF page

    I believe your main issue is you're ending your response stream: outputStream.flush();
    outputStream.close(); remove them, and try it again on your doGet for the image servlet.

    Personally I prefer StreamedContent with PrimeFaces as mentioned here Display dynamic image from database with p:graphicImage and StreamedContent

    or OmniFaces graphicImage http://showcase.omnifaces.org/components/graphicImage rather than creating servlet to output the content.

    This post by BalusC will solve all your issues: Servlet for serving static content