如何使用 java servlet 读取 json 或 xml 文件?
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 Apache Commons FileUpload 库来处理多部分请求。多部分请求是当将带有文件元素的表单发布到 servlet 时收到的请求。
例如:
这会上传文件并将其作为临时文件保存在服务器的硬盘上。然后您可以对该文件执行所需的操作。
特别是对于非常大的文件,更好的方法可能是跳过保存并直接处理 InputStream。为此,您需要一个合适的 XML 库(例如 Stax),它可以直接处理流。
编辑:表单的操作属性应与 servlet 映射的 url 模式匹配。
HTML 示例:
web.xml 片段示例:
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:
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:
Example web.xml snippet:
您可以使用 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.