从多部分请求中获取表单参数,而无需获取文件 [英] Get form parameters from multipart request without getting the files

查看:68
本文介绍了从多部分请求中获取表单参数,而无需获取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种无需上传文件即可在Servlet过滤器中获取HTTP多部分请求的表单参数的方法.

I'm looking for a way to get the form parameters of a HTTP multi-part request in a Servlet-filter without uploading files (yet).

request.getParameterMap()返回空.我了解这是因为请求包含多个部分.

request.getParameterMap() returns empty. I understand this is because of the request being multi-part.

我已经看过commons.HttpFileUpload,但是对于我的情况来说似乎太过分了.在此过滤器中,我只对普通参数感兴趣,并且还不想处理文件上传.

I've looked at commons.HttpFileUpload but this seems to be overkill for my situation. In this filter I'm only interested in the normal parameters, and don't want to handle the file-upload yet.

主要问题是我需要在过滤器堆栈的下方有一个完整的HttpRequestObject. HttpFileUpload似乎消耗了部分请求数据(可能是通过使用数据流对象并再次将其关闭).

the main problem is that I need to have an intact HttpRequestObject further down the filter stack. The HttpFileUpload seems to consume part of the request data (probably by using the data stream object and closing it again.)

推荐答案

这肯定不是矫kill过正,这是正确的方法,并且总是比自己编写解析器更好. Apache Commons FileUpload 已开发和维护多年,并已证明其在处理多部分/表单数据请求中的强大功能.您不想重新发明轮子.如果您确实要这样做(我不建议这样做),请阅读 multipart/form -data规范,并从读取HttpServletRequest#getInputStream()开始(警告:这是二进制和字符数据的混合!).

It's certainly not overkill, it's the right way and always better than writing the parser yourself. The Apache Commons FileUpload is developed and maintained for years and has proven its robustness in handling multipart/form-data requests. You don't want to reinvent the wheel. If you really want to do it (I don't recommend it), then read on the multipart/form-data specification and start with reading the HttpServletRequest#getInputStream() (warning: this is a mix of binary and character data!).

如果需要,您还可以编写一个过滤器,该过滤器在后台使用Apache Commons FileUpload并检查每个请求是否为multipart/form-data,如果是,则在以下帮助下将参数放回请求参数图中: Commons FileUpload并将上载的文件(或异常)作为请求属性,以便最终在您的Servlet代码中更加透明.您可以在此处找到了解此想法的基本示例.

You can if necessary also write a Filter which makes use of Apache Commons FileUpload under the hood and checks every request if it is multipart/form-data and if so, then put the parameters back in the request parameter map with help of Commons FileUpload and put the uploaded files (or exceptions) as request attributes, so that it's finally a bit more transparently in your servlet code. You can find here a basic example to get the idea.

希望这会有所帮助.

这篇关于从多部分请求中获取表单参数,而无需获取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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