ServletRequest的一个小知识点_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > ServletRequest的一个小知识点

ServletRequest的一个小知识点

 2012/9/8 11:52:13  personbeta  程序员俱乐部  我要评论(0)
  • 摘要:看到有人直接通过ServletRequest.getInputStream()中读取Post中的body,代码大概如下:Stringcharset=request.getCharacterEncoding();if(charset==null){charset=DEFAULT_ENCODE;}BufferedReaderin=newBufferedReader(newInputStreamReader(request.getInputStream(),charset))
  • 标签:Servlet 一个

看到有人直接通过ServletRequest.getInputStream()中读取Post中的body,代码大概如下:

        String charset = request.getCharacterEncoding(); 
         if (charset == null) { 
             charset = DEFAULT_ENCODE; 
         } 
         BufferedReader in = new BufferedReader(new  InputStreamReader(request 
                 .getInputStream(), charset)); 
  
         // Read the request 
         CharArrayWriter data = new CharArrayWriter(); 
         char[] buf = new char[8192]; 
         int ret; 
         while ((ret = in.read(buf, 0, 8192)) != -1) { 
             data.write(buf, 0, ret); 
         } 
         return data.toString(); 

?

当时心里有个疑问:为什么不直接通过调用request.getParameter()来获取相应的值呢?虽然至今也没想到答案,但是通过查看servlet规范了解到了ServletRequest的一个小知识,规范原文如下:

SRV.3.1.1 When Parameters Are Available
The following are the conditions that must be 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 getParameter family 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.

?

英文比较简单,就不翻译了。

发表评论
用户名: 匿名