%@ page import="java.io.*,java.util.*;" %>
<%--
#FILE: random_image2.jsp - Version 2.0
#
#INSTALLATION INSTRUCTIONS:
# 1) Save this jsp code within the web page you want random images displayed.
# It is recommended that you put this code at the top of your JSP page.
# 2) You will need to import the java.io and java.util packages into
# your JSP page. Example:
# <%@ page import="java.io.*,java.util.*;" %>
# 3) Make sure the script has execute permissions.
# 4) Make sure your IMAGE_DIRECTORY has read permissions, as well
# as the files within that directory.
# 5) Change:
# IMAGE_DIRECTORY = "./images/";
# as described in the jsp code below.
# 6) To display a random image, insert the following HTML JSP method call
# within your HTML code:
# <% out.println(DisplayRandomImage());%>
# See the HTML code below for an example.
#
#ABOUT THIS SCRIPT:
# This is a very simple jsp script. All it does is grab a
#random image from a directory and print the name within the associated
#HTML IMG tag.
#
#HISTORY:
# 5/15/2004 2.0 Original release
#
#AUTHOR:
# http://www.davelozinski.com/scripts
#
#BEGIN CONFIGURATION ITEMS:
# The URL the directory which contains the images
#to be randomly chosen and displayed. Value should end with
#a trailing slash "/" character!
#
--%>
<%!
public String IMAGE_DIRECTORY = "./gfx/";
//#The path RELATIVE to this script to the dir containing the images.
//#The value should end with a "/" character!
//#This directory should contain ONLY images.
//######## NOTHING BELOW THIS LINE SHOULD NEED TO BE CONFIGURED!!! ########
String DisplayRandomImage() {
ServletContext application = getServletConfig().getServletContext();
String msg = "";//#Either the IMG tag or message to be returned.
File dir = new File(application.getRealPath(IMAGE_DIRECTORY));
if (dir.isDirectory()) {
FilenameFilter imageFiles = new FilenameFilter() {
public boolean accept(File path, String name) {
return (name.endsWith("gif") || name.endsWith("jpg") || name.endsWith("jpeg"));
}
};
File[] files = dir.listFiles(imageFiles);
if (files.length > 0) {
int randomNum = new Random().nextInt(files.length);
msg = "";
} else {
msg = "No random images located in \"" + dir.toString() + "\"";
}
} else {
msg = "\"" + dir.toString() + "\" does not appear to be a valid directory!";
}
return msg;
} //#DisplayRandomImage
//########
%>
<%= DisplayRandomImage() %>