我想编写一个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();
}
}
答案 0 :(得分:1)
您正在寻找的是:
File root = new File(getServletContext().getRealPath("."));