HttpServletRequest的getInputStream方法和getParameter方法

百里马 2014-07-13 11:05:32
比如我一个POST请求,传的是表单数据,为什么这个时候getInputStream得到的为空串?而getParameter方法却可以获得数据?
...全文
3687 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
百里马 2014-07-14
  • 打赏
  • 举报
回复
引用 2 楼 fangmingshijie 的回复:
有没有设置form的enctype属性? 默认的是application/x- www-form-urlencoded,如果你使用了request.getParameter() ,再用request.getInputStream()就获取不到了。流只能获取一次。
我不用getParameter,直接调用getInputStream也是获取不到的
shine333 2014-07-14
  • 打赏
  • 举报
回复
根据Servlet规范,如果同时满足下列条件,则请求体(Entity)中的表单数据,将被填充到request的parameter集合中(request.getParameter系列方法可以读取相关数据): 1 这是一个HTTP/HTTPS请求 2 请求方法是POST(querystring无论是否POST都将被设置到parameter中) 3 请求的类型(Content-Type头)是application/x-www-form-urlencoded 4 Servlet调用了getParameter系列方法 如果上述条件没有同时满足,则相关的表单数据不会被设置进request的parameter集合中,相关的数据可以通过request.getInputStream()来访问。反之,如果上述条件均满足,相关的表单数据将不能再通过request.getInputStream()来读取。 Servlet Specifiaction 3.0:
引用
3.1.1 When Parameters Are Available The following are the conditions that mustbe met before post form data will be populated to the parameter set: 1. The request is an HTTP or HTTPS request. 2. The HTTP method is POST. 3. The content type is application/x-www-form-urlencoded. 4. The servlet has made an initial call of any of the getParameterfamily of methods on the request object. If the conditions are not met and the post form data is not included in the parameter set, the post data must still be available to the servlet via the request object’s input stream. If the conditions are met, post form data will no longer be available for reading directly from the request object’s input stream.
类似的例子,还有response.getOutputStream和getWriter,它们往往也是一对矛盾体
  • 打赏
  • 举报
回复
有没有设置form的enctype属性? 默认的是application/x- www-form-urlencoded,如果你使用了request.getParameter() ,再用request.getInputStream()就获取不到了。流只能获取一次。
Defonds 2014-07-14
  • 打赏
  • 举报
回复
getParameter() 和 getInputStream() 有冲突的,因为流只能被读一次

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧