使用servlet显示网页中的文件列表 [英] Display list of files in webpage using servlet

查看:453
本文介绍了使用servlet显示网页中的文件列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java EE的新手,我希望在网页中显示PDF缩略图列表。这些PDF存储在 src / main / webapp / pdf 的文件夹中,我想读取此文件夹以获取所有文件名。这是我的代码:

I'm new to Java EE, and I want to display in a webpage a list of PDF thumbnails. These PDF are stored in a folder in src/main/webapp/pdf, and I want to read this folder to get all the filenames. Here is my code :

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) {
    try {
        res.setContentType("application/json");
        res.setCharacterEncoding("UTF-8");

        PrintWriter out = res.getWriter();
        File pdfFolder = new File("/pdf");

        for (File pdf : pdfFolder.listFiles()) { // Line 27
            out.println(pdf.getName());
        }
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage());
    }
}

当我运行此代码时,我得到 NullPointerException

When I run this code, I get a NullPointerException :

java.lang.NullPointerException
    com.multi.services.ListFiles.doGet(ListFiles.java:27)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

这是我的结构:

我想拥有的是一个读取PDF文件夹并返回包含PDF文件名的JSON的Web服务,我将使用Ajax在JavaScript中调用此服务。

What I want to have is a web service that reads the PDF folder and returns a JSON containing the PDF filenames, and I will call this service in a JavaScript using Ajax.

任何人都可以帮我制作我的脚本运行良好?或者有没有更好的解决方案?

Can anyone help me to make my script running well ? Or has anyone a better solution ?

谢谢:)

推荐答案

来自Javadoc的引用 File.listFiles()

A quote from the Javadoc of File.listFiles()


返回null如果这个抽象路径名不表示目录,或者是否发生I / O错误。

returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

所以你的路径不正确(因为当前您的servlet容器的目录是未定义的)。你有这些可能性:

So your path is not correct (as the current directory of your servlet container is undefined). You have these possibilities here:


  • 使用绝对路径(如果你将PDF存储在webapp之外,这是合适的)

  • Use the absolute path (this is appropriate, if you store the PDF outside of your webapp)

使用 getRealPath() (这应该适合您的用例; PDF是webapp的一部分) :

Use getRealPath() (this should be suitable for your use case; PDFs are part of webapp):

File pdfFolder =
  new File(req.getSession().getServletContext().getRealPath("/pdf"));

这篇关于使用servlet显示网页中的文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆