HttpServletRequest的getParameter方法
来源:互联网 发布:linux驱动开发pdf 编辑:程序博客网 时间:2024/05/17 02:22
HttpServletRequest的getParameter方法:
tomcat或者其他的Servlet容器在调用程序员的Servlet之前已经帮我们做了很多事情了,比如解析HttpRequestLine(HTTP请求行)和解析HttpHeader(HTTP请求头)等等,但事实上在Servlet之前,服务器只解析到Header就停了,剩下的请求体留在request.getInputStream的流里,所以,如果你想在Servlet里面获得请求体里的内容,直接去读request.getInputStream()就好了。 但事情可能还没那么简单,我们知道,当我们在前端提交一个表单的时候,假设表单的内容为:name=baolin&password=mima
,我们是可以直接在Servlet里调用request.getParameter("name");
来获取到name的值的,大家有没有想过,如果form表单用的是POST方法提交,那么毫无疑问参数是在请求体里的,前面说过,如果想获取请求体里的内容,是可以在request流里直接读的,那么问题来了:
- 因为流是不能往回读的,如果我在之前先用
request.getInputStream()
读取完了请求体,这时候我再来用request.getParameter("name");
获取name的值,得到的是真实值还是个空呢?或者我先调用了request.getParameter();再来request.getInputStream();尝试获取请求体内容,可以得到吗? - 第二个问题,如果我在请求行里的URI部分这么写:
/testServlet?name=baolin
,接着又在请求体里附加name=baobao
,然后post提交,这时候在后台Servlet调用request.getParameter("name");
获取的是baolin还是baobao呢? - 第三个问题,如果我写了两个一样的参数,我应该怎样获取这两个参数呢?
答案:
- (该问题的前提是参数在请求体里,并且Content-Type是
application/x-www-form-urlencoded
)因为流是不能往回读的,所以如果程序员自己通过request获取的InputStream读完了请求体,那么再来调用request.getParameter试图获取参数得到的是null,反之亦然。 request.getParameter()方法的解析顺序为:URI -> 请求体,所以如果在URI获取到了需要的参数,那就不会再去请求体解析了
【很明显这句是有问题的,Tomcat解析Parameter的逻辑应该是:parameter的name和value是一对多的关系,tomcat会先解析URI里的queryString,然后判断如果是post请求&&content-type=”aplication/x-www-form-urlencoded”不管之前有没有获取到需要的参数都会去解析body,也就是说如果不是post请求而是delete或者其它请求或者content-type不是”aplication/x-www-form-urlencoded”则不会去读取body,这种情况getInputSteam读取body会得到数据】
2017-10-24勘误
可以用request.getParameterValues(“name”)方法来获取所有name
- HttpServletRequest的getParameter方法
- HttpServletRequest的getInputStream方法和getParameter方法
- HttpServletRequest 的 getAttribute() getParameter()
- HttpServletRequest类的getAttribute()方法与getParameter()方法的区别
- HttpServletRequest中的getAttribute方法和getParameter方法的区别
- HttpServletRequest 的 getAttribute()和getParameter()
- 区分HttpServletRequest 中getAttribute() 与 getParameter() 方法
- HttpServletRequest.getParameter(String)和getAttribute()的区别
- HttpServletRequest中getAttribute()和 getParameter()的区别
- HttpServletRequest对象的getAttribute()与getParameter()
- HttpServletRequest.getParameter(String)和getAttribute()的区别
- HttpServletRequest中getAttribute()和getParameter()的区别
- HttpServletRequest中getAttribute()和getParameter()的区别
- HttpServletRequest类,方法getAttribute()和getParameter()有何区别
- HttpServletRequest之getParameter
- HttpServletRequest getParameter返回null
- HttpServletRequest.getParameter(String)和getAttribute(String)的区别
- HttpServletRequest的常用方法
- 基础练习 BASIC-3 字母图形
- Linux
- iOS开发
- 基础练习 BASIC-4 数列特征
- 帧中继
- HttpServletRequest的getParameter方法
- BigDecimal 使用方法详解
- axios
- windows安装程序无法将windows配置为在此计算机的硬件上运行
- 基础练习 BASIC-5 查找整数
- PPP的配置
- log4cplus的使用(转载)
- MySQL存储过程:实现更新UUID
- 35:字符串的展开