Hi everyone!
I am making a JSP page with Eclipse and Apache Tomcat 6. I want to create a drop-down list that will be populated with the list of all folders in the directory of that JSP page. Can someone show me how to do that?

Thanks in advance!

Dani AI

Generated

opened a common requirement: render a select element from server-side folders. The snippet posted by shows a working JSP scriptlet approach, but it mixes view and filesystem logic and assumes the webapp is exploded on disk. A cleaner, safer pattern is to let a servlet (or controller) read a configured filesystem directory and pass a simple list of folder names to the JSP (or provide a JSON endpoint for client-side population). This keeps presentation free of scriptlets and avoids leaking absolute server paths.

A compact, modern flow (Java 7+) is shown below: the servlet reads a configured base directory, collects directory names, sets them as a request attribute, and forwards to a JSTL-enabled JSP for rendering.

// FolderListServlet (init reads a context-param "folders.path")
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Path base = Paths.get(getServletContext().getInitParameter("folders.path"));
    List<String> folders;
    try (Stream<Path> s = Files.list(base)) {
        folders = s.filter(Files::isDirectory)
                   .map(p -> p.getFileName().toString())
                   .sorted()
                   .collect(Collectors.toList());
    }
    req.setAttribute("folders", folders);
    req.getRequestDispatcher("/WEB-INF/views/folders.jsp").forward(req, resp);
}
<select name="folder">
  <c:forEach var="f" items="${folders}">
    <option value="${f}">${f}</option>
  </c:forEach>
</select>

Practical notes and cautions: do not expose absolute filesystem paths in option values; restrict listing to a single configured base directory; validate/sanitize any folder selection on submit to prevent path traversal; ensure the container user has read permission; avoid relying on the webapp being exploded (use an external directory or a context-configured path). For debugging, confirm the init parameter, check server logs for IO exceptions, and log the resolved base path (without printing sensitive full paths in production). This approach keeps the view simple, improves portability, and addresses the maintainability and security gaps in the original scriptlet solution.

You could try this code:

<%-- 
    Document   : index
    Created on : Jul 27, 2010, 2:09:50 PM
    Author     : jaka
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.io.File" %>
<%@page import="java.io.FileFilter" %>
<%@page import="java.io.IOException" %>
<%
String currDirStr = getServletContext().getRealPath("");
File[] folders = null;
try {
    File currDir = new File(currDirStr);
    if(currDir.exists()) {
        folders = currDir.listFiles(new FileFilter() {

            public boolean accept(File pathname) {
                String name = pathname.getName();
                if(pathname.isDirectory()) {
                    if("WEB-INF".equals(name) || "META-INF".equals(name)) {
                        return false;
                    }
                    return true;
                }
                return false;
            }
        });
        if(folders == null) {
            folders = new File[0];
        }
    }
} catch(Exception ex) {}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">



<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="GET">
            <table border="1">
                <tbody>
                    <tr>
                        <td>Select Folder:</td>
                        <td>
                            <select name="folder">
                                <%
                                for(File folder : folders) { %>
                                <option value="<%= folder.getAbsolutePath() %>"><%= folder.getName() %></option>
                                <% } %>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>
                            <input type="submit" value="Submit" />
                        </td>
                    </tr>
                </tbody>
            </table>

        </form>
    </body>
</html>

Thanks I also have same Problem. I try it code and share then.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.