如何使用 JSP 列出服务器目录的内容?
问题描述:
在编写 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)?
是否会因为某些安全问题而限制某些文件 I/O 操作?
Would some file I/O operations be restricted because of some security issues?
我更喜欢不访问某些特定于实现的解决方案服务器变量/属性.
我不会问它是否像 new File(".")
一样简单,因为这只会给出服务器可执行文件的目录.
I wouldn't ask if it were as simple as new File(".")
, because this would just give the directory of server's executables.
答
你应该知道你的 web 应用程序中 jsp 的路径,以便你可以将它传递给 getRealPath()
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();