Como exibir uma imagem fora do contexto com JSF?

7 respostas
N

bom dia, como posso exibir uma imagem com o JSF, sendo que a imagem esté em um diretório fora do projeto?
por exemplo:
c:imagens

obrigado

7 Respostas

R

Tá usando RichFaces?

N

bom dia raf4ever
estou usando PrimeFaces

N

achei esse link, mostrando como fazer com servlet

http://balusc.blogspot.com/2007/04/imageservlet.html#ImageServletServingFromAbsolutePath

N
Não consegui... o que estou fazendo de errado? mew servlet está assim
@WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet
{
	// Constants ----------------------------------------------------------------------------------

    private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.

    // Properties ---------------------------------------------------------------------------------

    private String imagePath;

    // Actions ------------------------------------------------------------------------------------

    public void init() throws ServletException {

        // Define base path somehow. You can define it as init-param of the servlet.
        this.imagePath = "C:/HRE-Commerce/imagens";

        // In a Windows environment with the Applicationserver running on the
        // c: volume, the above path is exactly the same as "c:\images".
        // In UNIX, it is just straightforward "/images".
        // If you have stored files in the WebContent of a WAR, for example in the
        // "/WEB-INF/images" folder, then you can retrieve the absolute path by:
        // this.imagePath = getServletContext().getRealPath("/WEB-INF/images");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        // Get requested image by path info.
        String requestedImage = request.getPathInfo();

        // Check if file name is actually supplied to the request URI.
        if (requestedImage == null) {
            // Do your thing if the image is not supplied to the request URI.
            // Throw an exception, or send 404, or show default/warning image, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        // Decode the file name (might contain spaces and on) and prepare file object.
        File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));

        // Check if file actually exists in filesystem.
        if (!image.exists()) {
            // Do your thing if the file appears to be non-existing.
            // Throw an exception, or send 404, or show default/warning image, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        // Get content type by filename.
        String contentType = getServletContext().getMimeType(image.getName());

        // Check if file is actually an image (avoid download of other files by hackers!).
        // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
        if (contentType == null || !contentType.startsWith("image")) {
            // Do your thing if the file appears not being a real image.
            // Throw an exception, or send 404, or show default/warning image, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        // Init servlet response.
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setContentType(contentType);
        response.setHeader("Content-Length", String.valueOf(image.length()));
        response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");

        // Prepare streams.
        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            // Open streams.
            input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
            output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

            // Write file contents to response.
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } finally {
            // Gently close streams.
            close(output);
            close(input);
        }
    }

    // Helpers (can be refactored to public utility class) ----------------------------------------

    private static void close(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                // Do your thing with the exception. Print it, log it or mail it.
                e.printStackTrace();
            }
        }
    }
}
no web.xml adicionei;
<servlet>
	    <servlet-name>imageServlet</servlet-name>
	    <servlet-class>mypackage.ImageServlet</servlet-class>
	</servlet>
	<servlet-mapping>
	    <servlet-name>imageServlet</servlet-name>
	    <url-pattern>/image/*</url-pattern>
	</servlet-mapping>

e estou chamando assim:

<h:graphicImage value="image/000086.jpg" />

o que está errado?

obrigado

L

Cara, utilizando servlet então é a saída para a renderização de imagens fora do contexto da aplicação no jsf?

Andei pesquisando e encontrei muita gambiarra.
E normalmente gambiarra cedo ou tarde buga seu codigo fonte.

C

E ai conseguiu resolver? Estou usando primefaces, mas busco direto do banco a imagem, sei que não é a melhor maneira, mas foi requisito.

L

Então brother, ainda não resolvi mas estou olhando na api do rich
http://livedemo.exadel.com/richfaces-demo/richfaces/mediaOutput.jsf?c=mediaOutput&tab=usage

se vc está utilizando prime, com ctz tem algo parecido na api do prime

Criado 28 de novembro de 2011
Ultima resposta 10 de jul. de 2012
Respostas 7
Participantes 4