tags:

views:

78

answers:

3
+1  A: 

Relying on the filesystem like that for a webapp (i.e., using absolute paths) is not good practice will make your code less portable.

You should keep your files in a resources directory and use the ClassLoader to load your files relative to the classpath. See ClassLoader.getResource() and ClassLoader.getResourceAsStream(). Another option is to use ServletContext.getResource() or ServletContext.getResourceAsStream(). You can get the ServletContext in servlets by using the inherited getServletContext() method.

Vivin Paliath
I don't think portability is per se a problem here since the desired files are already in the webcontent and he just want to display only them.
BalusC
A: 

Since /usr/local/tomcat/sites/web_tech/images/scores is the directory being listed, having /usr/local/tomcat/sites/web_tech as root for the output seems a bit... arbitrary.

The best thing I can think of is to have a File root = <your intended root>; and then do something similar to

String path = f.getName();
while (!f.equals(root)) {
    f = f.getParent();
    path = f + "/" + path;
}
aioobe
+1  A: 

You'll need to substring the root path away.

File root = new File(getServletContext().getRealPath("/"));
for (File file : root.listFiles()) {
    // ...
    String path = file.getAbsolutePath().substring(root.getAbsolutePath().length());

By the way, those System.out.println() lines actually won't print to the response. They prints to the stdout which may be the IDE console or the server's logfile. Further, this kind of logic doesn't belong in a JSP file. Do it in a real Java class and forward to JSP for display.

BalusC