users@glassfish.java.net

Re: JSF - referencing images outside of deployed .ear

From: <glassfish_at_javadesktop.org>
Date: Thu, 03 May 2007 06:23:28 PDT

It's a pretty big pain in JSF too. You need a servlet that serves up the images. Register the servlet in the usual way and include links such as GetImage?id=myfile.png.

Here is the code from a recent project where I needed to do that.

<pre>
package com.horstmann.qq.web;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetImageServlet extends HttpServlet {
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        HttpSession session = request.getSession();
        String id = request.getParameter("id");
        String extension = id.substring(id.lastIndexOf('.') + 1);
        response.setContentType("image/" + extension);
        String imageDirectory = getServletContext().getInitParameter("com.horstmann.qq.imagePath");
        FileInputStream in = new FileInputStream(new File(new File(imageDirectory), id));
        OutputStream out = response.getOutputStream();
        final int BUFFER_SIZE = 1024;
        byte[] buffer = new byte[BUFFER_SIZE];
        int n = 0;
        while (-1 != (n = in.read(buffer))) {
            out.write(buffer, 0, n);
        }
        in.close();
        out.close();
    }
        
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
}
</pre>

I know the <pre> tags don't work--what does one do in this system to format code???
[Message sent by forum member 'cayhorstmann' (cayhorstmann)]

http://forums.java.net/jive/thread.jspa?messageID=215339