пятница, 13 апреля 2012 г.

JSF - Displaying images from database in JSF

In the past it took me some time to get an idea of how to store images in database and how to display them in jsf. So I would like to show everyone how come around this problem how it is done.

What do you need: 
1. Image entity class
2. Servlet which retrieves images by name and renders them.

Image entity class is not a big deal. In the database you would usually store images as a BLOB value in bytes. In your entity you just have to add an annotation @LOB to your image binary field.

Here is the servlet:


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.inject.Inject;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import org.gicm.cms.CMSDao;
import org.gicm.model.UploadedImage;
@WebServlet("/images/*")
public class TestServlet extends HttpServlet {

    @Inject
    private CMSDao cms;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String imageId = String.valueOf(request.getPathInfo().substring(1)); // Gets string that goes after "/images/".
        UploadedImage image = cms.findImage(imageId); // Get Image from DB.

        response.setHeader("Content-Type", getServletContext().getMimeType(image.getName()));
        response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");

        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            input = new BufferedInputStream(image.getData()); // Creates buffered input stream.
            output = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[8192];
            for (int length = 0; (length = input.read(buffer)) > 0;) {
                output.write(buffer, 0, length);
            }
        } finally {
            if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
            if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
        }
    }
}

Now the images can be accessed through yoursite.com/images/imagename
So what you can do is basically create a reference table in your database which will be connected to your images table to reference the name of the image, and in your managed bean retrieve the List of images in reference table.
In your JSF you will do something like this:
<img src="/images/{image.name} />
Best regards,
NETLink community member

Комментариев нет:

Отправить комментарий