Servlet 文件并发

发布于 2025-01-05 01:56:15 字数 4240 浏览 1 评论 0原文

我真的有一个很简单的问题。 我为供应商编写了一个 servlet,用于上传 XML 文件。 这些文件被写入服务器上的某个位置。 所有文件都使用时间戳进行重命名。

下面的代码是否存在并发问题的风险? 我问是因为我们从供应商那里收到文件,看起来像 他们有来自 2 个不同 XML 文件

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    processRequest(request, response);
}

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    processRequest(request, response);
}        

public String getServletInfo() {
    return "Short description";
}// </editor-fold>

protected void processRequest(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    File dirToUse;
    boolean mountExists = this.getDirmount().exists();
    if (!mountExists) {
        this.log("MOUNT " + this.getDirmount() + " does not exist!");
        dirToUse = this.getDiras400();

    } else {
        dirToUse = this.getDirmount();
    }

    boolean useSimpleRead = true;
    if (request.getMethod().equalsIgnoreCase("POST")) {
        useSimpleRead = !ServletFileUpload.isMultipartContent(request);
    }

    if (useSimpleRead) {
        this.log("Handle simple request.");
        handleSimpleRequest(request, response, dirToUse);

    } else {
        this.log("Handle Multpart Post request.");
        handleMultipart(request, response, dirToUse);
    }
}   

protected void handleMultipart(HttpServletRequest request,
        HttpServletResponse response, File dir) throws IOException,
        ServletException {
    try {
        FileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        List<FileItem> items = upload.parseRequest(request);

        if (items.isEmpty()) {
            this.log("No content to read in request.");
            throw new IOException("No content to read in request.");
        }

        boolean savedToDisk = true;
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            getFilename(request);
            File diskFile = new File(dir, this.getFilename(request));
            item.write(diskFile);

            if (!diskFile.exists()) {
                savedToDisk = false;
            }
        }

        if (!savedToDisk) {
            throw new IOException("Data not saved to disk.");
        }

    } catch (FileUploadException fue) {
        throw new ServletException(fue);

    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}   

protected void handleSimpleRequest(HttpServletRequest request,
        HttpServletResponse response, File dir) throws IOException {
    // READINPUT DATA TO STRINGBUFFER
    InputStream in = request.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

    StringBuffer sb = new StringBuffer();
    String line = reader.readLine();
    while (line != null) {
        sb.append(line + "\r\n");
        line = reader.readLine();
    }

    if (sb.length() == 0) {
        this.log("No content to read in request.");
        throw new IOException("No content to read in request.");
    }       

    //Get new Filename
    String newFilename = getFilename(request);
    File diskFile = new File(dir, newFilename);
    saveDataToFile(sb, diskFile);

    if (!diskFile.exists()) {
        throw new IOException("Data not saved to disk.");
    }
}

protected abstract String getFilename(HttpServletRequest request);

protected void saveDataToFile(StringBuffer sb, File diskFile) throws IOException {
    BufferedWriter out = new BufferedWriter(new FileWriter(diskFile));

    out.write(sb.toString());
    out.flush();
    out.close();
}

getFileName 实现的内容:

@Override
protected String getFilename(HttpServletRequest request) {
    Calendar current = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
    long currentTimeMillis = current.getTimeInMillis();

            System.out.println(currentTimeMillis);
    return "disp_" + request.getRemoteHost() + "_" + currentTimeMillis + ".xml";
}

无论如何,提前感谢!

I have quite a simple question really.
I wrote a servlet for suppliers to upload XML-files to.
These files get written to a location on the server.
All the files get renamed with a timestamp.

Is there a risk of concurrency problems with the code below?
I ask because we receive files from a supplier, that look like
they have content from 2 different XML-files

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    processRequest(request, response);
}

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    processRequest(request, response);
}        

public String getServletInfo() {
    return "Short description";
}// </editor-fold>

protected void processRequest(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    File dirToUse;
    boolean mountExists = this.getDirmount().exists();
    if (!mountExists) {
        this.log("MOUNT " + this.getDirmount() + " does not exist!");
        dirToUse = this.getDiras400();

    } else {
        dirToUse = this.getDirmount();
    }

    boolean useSimpleRead = true;
    if (request.getMethod().equalsIgnoreCase("POST")) {
        useSimpleRead = !ServletFileUpload.isMultipartContent(request);
    }

    if (useSimpleRead) {
        this.log("Handle simple request.");
        handleSimpleRequest(request, response, dirToUse);

    } else {
        this.log("Handle Multpart Post request.");
        handleMultipart(request, response, dirToUse);
    }
}   

protected void handleMultipart(HttpServletRequest request,
        HttpServletResponse response, File dir) throws IOException,
        ServletException {
    try {
        FileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        List<FileItem> items = upload.parseRequest(request);

        if (items.isEmpty()) {
            this.log("No content to read in request.");
            throw new IOException("No content to read in request.");
        }

        boolean savedToDisk = true;
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            getFilename(request);
            File diskFile = new File(dir, this.getFilename(request));
            item.write(diskFile);

            if (!diskFile.exists()) {
                savedToDisk = false;
            }
        }

        if (!savedToDisk) {
            throw new IOException("Data not saved to disk.");
        }

    } catch (FileUploadException fue) {
        throw new ServletException(fue);

    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}   

protected void handleSimpleRequest(HttpServletRequest request,
        HttpServletResponse response, File dir) throws IOException {
    // READINPUT DATA TO STRINGBUFFER
    InputStream in = request.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

    StringBuffer sb = new StringBuffer();
    String line = reader.readLine();
    while (line != null) {
        sb.append(line + "\r\n");
        line = reader.readLine();
    }

    if (sb.length() == 0) {
        this.log("No content to read in request.");
        throw new IOException("No content to read in request.");
    }       

    //Get new Filename
    String newFilename = getFilename(request);
    File diskFile = new File(dir, newFilename);
    saveDataToFile(sb, diskFile);

    if (!diskFile.exists()) {
        throw new IOException("Data not saved to disk.");
    }
}

protected abstract String getFilename(HttpServletRequest request);

protected void saveDataToFile(StringBuffer sb, File diskFile) throws IOException {
    BufferedWriter out = new BufferedWriter(new FileWriter(diskFile));

    out.write(sb.toString());
    out.flush();
    out.close();
}

getFileName implementation:

@Override
protected String getFilename(HttpServletRequest request) {
    Calendar current = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
    long currentTimeMillis = current.getTimeInMillis();

            System.out.println(currentTimeMillis);
    return "disp_" + request.getRemoteHost() + "_" + currentTimeMillis + ".xml";
}

Anyway, thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怎樣才叫好 2025-01-12 01:56:15

不会出现同步问题,但可能会出现竞争条件,例如,两个线程可能使用 getFileName() 方法返回相同的文件名

There would not be synchronization problems but there can be race conditions, for example, two threads might return the same file name using the method getFileName()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文