Servlet中的request.getParameter() 研究,api解读,以及解码申明

Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.
You should only use this method when you are sure the parameter has only one value. If the parameter might have more than one value, use getParameterValues.
If you use this method with a multivalued parameter, the value returned is equal to the first value in the array returned by getParameterValues.
If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via getInputStream or getReader can interfere with the execution of this method.

在英文api文档里面,对这个办法进行了很具体的论说,我翻译一下:

返回一个字符串格局的恳求参数值,若是这个恳求参数不存在,那么返回null,请求参数 是 一个请求的扩大信息就http servlets,请求参数包含在querystring 或者post提交的数据里面当你断定这个请求参数只有独一值,那么你应用这个办法。
若是有多个值的话,你要应用getParameterValues.了,若是你应用这个办法解析多值参数,那么将会返回getParameterValues成果的第一个值若是参数数据经过request body 传来的,比如 http post 恳求,直接经过getInputStream or getReader 读取body,会影响这个办法的履行。


网站上,经常有人说这个办法会先对参数进行解码,学的时后不求甚解,如今我们来看看到底是怎么回事:
就tomcat来说,具体实现 源码 是org.apache.catalina.core.ApplicationHttpRequest.getParameter( String),
它调用了 专门的 org.apache.catalina.core.ApplicationHttpRequest.parseParameters()办法来转换参数,
该办法又调用了 org.apache.catalina.core.ApplicationHttpRequest.mergeParameters()来merge 参数。

我们来读下它的源码:
/**
* Merge the parameters  the saved query parameter string (if any), <br>
* and the parameters already present on this request (if any), <br>
* such that the parameter values  the query string show up first if there are duplicate parameter names.
*/
private void mergeParameters(){
if ((queryParamString == null) || (queryParamString.length() < 1))
return;
HashMap queryParameters = new HashMap();
String encoding = getCharacterEncoding();
if (encoding == null)
encoding = "ISO-8859-1";
try{
RequestUtil.parseParameters(queryParameters, queryParamString, encoding);
}catch (Exception e){
;
}
Iterator keys = parameters.keySet().iterator();
while (keys.hasNext()){
String key = (String) keys.next();
Object value = queryParameters.get(key);
if (value == null){
queryParameters.put(key, parameters.get(key));
continue;
}
queryParameters.put(key, mergeValues(value, parameters.get(key)));
}
parameters = queryParameters;
}

可以看到 ,先会应用 encoding 对参数进行解码,这里调用了 getCharacterEncoding(),这就是 为什么过滤器 ,过滤中文,会应用request.setCharacterEncoding(CharsetType.UTF8); 的原因。

若是不设置值,默认 应用ISO-8859-1,上方就是所说的 request.getParameter()会内部对参数解码 的实现过程。


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值