Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list contents of a server directory using JSP?

Tags:

java

file

jsp

When writing a JSP file, how can I get the current directory of this file at runtime
(to be able to iterate the directory and list its contents)?

Would some file I/O operations be restricted because of some security issues?

I would prefer a solution without accessing some implementation-specific server variables / properties.

EDIT:
I wouldn't ask if it were as simple as new File("."), because this would just give the directory of server's executables.

like image 831
ivan_ivanovich_ivanoff Avatar asked Jun 03 '09 22:06

ivan_ivanovich_ivanoff


2 Answers

As of Version 2.1 of the Java Servlet API use:

File jsp = new File(request.getSession().getServletContext().getRealPath(request.getServletPath()));
File dir = jsp.getParentFile();
File[] list = dir.listFiles();
like image 74
Max GIesbert Avatar answered Oct 14 '22 09:10

Max GIesbert


you should know the path of the jsp within your web application so you can pass that to getRealPath()

File jsp = request.getRealPath(pathToJspInWebapp);  //eg. /WEB-INF/jsp/my.jsp
File directory = jsp.getParentFile();
File[] list = directory.listFiles();
like image 43
objects Avatar answered Oct 14 '22 11:10

objects