faisal has posted 2 posts at DZone. View Full User Profile

Display Images From a Non-Project Directory in JSF

  • submit to reddit

When using image related tags in JSF we come across a situation where we need to display an image from the system which is not in the project directory. The images which are in the project directory are easily displayed using the relative path in the "src" or "value" attribute in these tags but displaying images using absolute path is not possible directly in JSF using these tags.

A technique to do this is explained in this article which uses a servlet to respond to the image url which we send.

1)Provide the following entry in web.xml:


2)In your xhtml/jsp file call the servlet as shown below:

<h:graphicImage value="/images/dynamic/?file=test.jpg"/>

3)Create the following servlet class

public class DynamicImageServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException


try {

// Get image file.

String file = request.getParameter("file");

BufferedInputStream in = new BufferedInputStream(new FileInputStream("Image directory:/" + file));

// Get image contents.
byte[] bytes = new byte[in.available()];


// Write image contents to response.

} catch (IOException e) {





Explanation of servlet code:
The url (/images/dynamic/?file=test.jpg) specified with the parameter "file" in the xhtml file calls the servlet based on the entry in the web.xml file.

The servlet's doGet() method receives the request and processes it to write the response in the form of the image from the system.

The "Image directory" specified in the servlet class is the system directory from where you want to read the image.

Published at DZone with permission of its author, faisal khan.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Lance Semmens replied on Thu, 2010/05/20 - 12:23pm

You should always be careful with functions like this that allow arbitrary access to the filesystem. You may have opened up a security hole for a hacker.

Consider a hacker trying the following url




Alex Fernando replied on Thu, 2012/02/23 - 12:10pm

Soy de Ecuador. Te agradesco un monton. Me sirvio de mucha ayuda.

Voy a recomendar este post

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.