我想编写一个 servlet 来搜索 Tomcat 服务器上的文件,该服务器给出文件的相对位置。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String gettext = request.getParameter("name");
String set = gettext;
String s = null;
RequestDispatcher dispatcher = request.getRequestDispatcher("search.jsp");
request.setAttribute("text", gettext);
File root = new File("here i want to give localhost:8080/webappfoldername");
String fileName = set + ".png";
System.out.println(fileName);
try {
boolean recursive = true;
Collection files = FileUtils.listFiles(root, null, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
if (file.getName().equals(fileName)) {
System.out.println(file.getAbsolutePath());
s = file.getAbsolutePath();
// System.out.println(s);
getServletContext().setAttribute("return", s);
// request.setAttribute("return" ,file.getAbsolutePath());
String testing = (String) getServletContext().getAttribute("return");
// System.out.println(testing);
request.getRequestDispatcher("/page.jsp").forward(request, response);
}
}
if (s == null) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("no file found");
}
} catch (Exception e) {
e.printStackTrace();
}
}
最佳答案
您正在寻找的是:
File root = new File(getServletContext().getRealPath("."));
关于java - 用于搜索服务器的 servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7203928/