如何使用 java servlet 读取 json 或 xml 文件?

发布于 2024-12-22 23:32:33 字数 259 浏览 0 评论 0原文

我正在使用 NetBeans,我将创建一个基于 Web 的应用程序,该应用程序根据一些工具处理任何 xml 和 json 文件。到目前为止,我已经使用 html 创建了一个基本站点,并且还有一些用 javabean 编写的 java 代码。 我想问您,您认为通过java servlet读取和处理xml或json文件的最佳方法是什么?我如何传递文件(用户选择的文件,到可以进行进一步处理的一侧)。我读过 HTTPClient 类是一个好方法,但是我不确定这是否是最好的。

感谢您抽出时间

I am using NetBeans and I am going to create a web based app which processes any xml and json file according to some tools. Until now, I ve created a basic site using html and I also have some java code written in javabeans.
I would like to ask you what do you think is the best way to read and process an xml or json file through java servlets? How can I pass the file(which the user chooses, to the side where further process can be done). I ve read that HTTPClient class is a good way, however i am not sure if this is the best.

Thanks for your time

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

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

发布评论

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

评论(2

携君以终年 2024-12-29 23:32:33

您可以使用 Apache Commons FileUpload 库来处理多部分请求。多部分请求是当将带有文件元素的表单发布到 servlet 时收到的请求。

例如:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

(...)

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        if (ServletFileUpload.isMultipartContent(request)) {
            handleMultiPartContent(request);
        }
    }

    private void handleMultiPartContent(HttpServletRequest request) {

        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileSizeMax(2097152); // 2 Mb
        try {
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    File tempFile = saveFile(item);
                    // process the file
                }
            }
        }
        catch (FileUploadException e) {
            LOG.debug("Error uploading file", e);
        }
        catch (IOException e) {
            LOG.debug("Error uploading file", e);
        }
    }

    private File saveFile(FileItemStream item) {

        InputStream in = null;
        OutputStream out = null;
        try {
            in = item.openStream();
            File tmpFile = File.createTempFile("tmp_upload", null);
            tmpFile.deleteOnExit();
            out = new FileOutputStream(tmpFile);
            long bytes = 0;
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
                bytes += len;
            }
            LOG.debug(String.format("Saved %s bytes to %s ", bytes, tmpFile.getCanonicalPath()));
            return tmpFile;
        }
        catch (IOException e) {

            LOG.debug("Could not save file", e);
            Throwable cause = e.getCause();
            if (cause instanceof FileSizeLimitExceededException) {
                LOG.debug("File too large", e);
            }
            else {
                LOG.debug("Technical error", e);
            }
            return null;
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            }
            catch (IOException e) {
                LOG.debug("Could not close stream", e);
            }
        }
    }

这会上传文件并将其作为临时文件保存在服务器的硬盘上。然后您可以对该文件执行所需的操作。

特别是对于非常大的文件,更好的方法可能是跳过保存并直接处理 InputStream。为此,您需要一个合适的 XML 库(例如 Stax),它可以直接处理流。

编辑:表单的操作属性应与 servlet 映射的 url 模式匹配。

HTML 示例:

<form action="upload" ENCTYPE='multipart/form-data' method="POST">
    <input type="file" name="user_file" accept="text/xml">
    <input type="submit" value="Validate" />
</form>

web.xml 片段示例:

<servlet>
    <servlet-name>FileReaderServlet</servlet-name>
    <servlet-class>my.application.FileReaderServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>FileReaderServlet</servlet-name>
    <url-pattern>/upload</url-pattern>
</servlet-mapping>

You could use the Apache Commons FileUpload library to handle the multipart request. A multipart request is what you receive when a form with a file element is posted to a servlet.

For example:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

(...)

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        if (ServletFileUpload.isMultipartContent(request)) {
            handleMultiPartContent(request);
        }
    }

    private void handleMultiPartContent(HttpServletRequest request) {

        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileSizeMax(2097152); // 2 Mb
        try {
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    File tempFile = saveFile(item);
                    // process the file
                }
            }
        }
        catch (FileUploadException e) {
            LOG.debug("Error uploading file", e);
        }
        catch (IOException e) {
            LOG.debug("Error uploading file", e);
        }
    }

    private File saveFile(FileItemStream item) {

        InputStream in = null;
        OutputStream out = null;
        try {
            in = item.openStream();
            File tmpFile = File.createTempFile("tmp_upload", null);
            tmpFile.deleteOnExit();
            out = new FileOutputStream(tmpFile);
            long bytes = 0;
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
                bytes += len;
            }
            LOG.debug(String.format("Saved %s bytes to %s ", bytes, tmpFile.getCanonicalPath()));
            return tmpFile;
        }
        catch (IOException e) {

            LOG.debug("Could not save file", e);
            Throwable cause = e.getCause();
            if (cause instanceof FileSizeLimitExceededException) {
                LOG.debug("File too large", e);
            }
            else {
                LOG.debug("Technical error", e);
            }
            return null;
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            }
            catch (IOException e) {
                LOG.debug("Could not close stream", e);
            }
        }
    }

This uploads the file and saves it as a temporary file on the server's harddisk. You can then do with the file what is needed.

Especially for very large files a better approach might be to skip the saving and process the InputStream directly. You need a suitable XML library for this (for example Stax) which can handle streams directly.

EDIT: the action attribute of your form should match the url-pattern of your servlet-mapping.

Example HTML:

<form action="upload" ENCTYPE='multipart/form-data' method="POST">
    <input type="file" name="user_file" accept="text/xml">
    <input type="submit" value="Validate" />
</form>

Example web.xml snippet:

<servlet>
    <servlet-name>FileReaderServlet</servlet-name>
    <servlet-class>my.application.FileReaderServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>FileReaderServlet</servlet-name>
    <url-pattern>/upload</url-pattern>
</servlet-mapping>
烟酒忠诚 2024-12-29 23:32:33

您可以使用 apache 提供的 HttpClient (或者)Sun 提供的 HttpURLClient,两者都是很好的 API。如果您选择 apache,则需要安装额外的 Jars。

与 Sun 提供的方法相比,Apache HttpClient 有几个额外的方法。

You can use either HttpClient provided by apache (or) Sun provided HttpURLClient, both are good APIs. If you opt for apache you need to install extra Jars.

Apache HttpClient has couple of extra methods comparing with Sun provided one.

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