我正在尝试编写一个简单的 java servlet 来列出目录中的文件。路径存储在 web.xml 的 init-param 中。当我调用 getInitParameters() 时,它返回目录路径。但是当我尝试将它传递给处理程序时,它返回 null。不知道我做错了什么。有什么帮助吗?
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
interface Handler {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException;
}
class DispatchChoice {
public final String param;
public final GetHandler getHandler;
public DispatchChoice (String param, Handler getHandler)
{
this.param = param;
this.getHandler = getHandler;
}
}
public class MyServlet extends HttpServlet
{
String value;
public void init() throws ServletException {
value = getInitParameter("addressfile"); // correct value is saved here
System.out.println("Init value : "+value);
}
DispatchChoice myChoice = new DispatchChoice("/test1", new FileHandler(value));
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException
{
myChoice.getHandler.doGet(request, response);
}
}
class FileHandler implements Handler {
private String place;
public FileHandler (String value){
this.place = value; // this is NULL, not the value from above
System.out.println("Param value : " + value);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
File directory = new File(place); //is NULL
File[] files = directory.listFiles();
PrintWriter pw = response.getWriter();
for (int index = 0; index < files.length; index++) {
pw.println(files[index].getName());
}
}
}
web.xml
<servlet>
<servlet-name>ListManagerServlet</servlet-name>
<servlet-class>savva.listmanagerservlet.ListManagerServlet</servlet-class>
<init-param>
<param-name>addressfile</param-name>
<param-value>d:\\temp\\</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ListManagerServlet</servlet-name>
<url-pattern>/ListManagerServlet</url-pattern>
</servlet-mapping>