Posted on 2009-08-20 22:35
Gavin.lee 阅读(3464)
评论(0) 编辑 收藏 所属分类:
web 积累(前端 + 后台)
今天出了很大的纰漏,我们站上工行充值渠道疯狂掉单,原因是开发包陈旧,但是没法查到日志,写的日志全是空文件,原因就是我将request.getQueryString()写到文件中当日志,怪我对这个方法理解不透,回来好好反省一下,查了api,写了这个方法:
api第一句:Returns the query string that is contained in the request URL after the path,这就说明它只对get方法抛的数据有效。post方法传的参数getQueryString将什么都得不到。
我的总结:
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;


public class QueryString
{
private StringBuffer query = new StringBuffer();


public QueryString(String name, String value)
{
encode(name, value);
}


public synchronized void add(String name, String value)
{
query.append('&');
encode(name, value);
}


private synchronized void encode(String name, String value)
{

try
{
query.append(URLEncoder.encode(name, "UTF-8"));
query.append('=');
value = value.replaceAll(" ", "%20");
query.append(value);

} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}


public String getQuery()
{
return query.toString();
}


public String toString()
{
return getQuery();
}


/** *//**
* 直接接受request
* 注:request中提供的getQueryString方法只对Get方法才能生效,
* 在我们不知道方法的情况下最好重写getQueryString
* @param request
* @return
*/

public static String getQueryString(HttpServletRequest request)
{
boolean first = true;
StringBuffer strbuf = new StringBuffer("");
Enumeration emParams = request.getParameterNames();
//do-while

do
{

if (!emParams.hasMoreElements())
{
break;
}
String sParam = (String) emParams.nextElement();
String[] sValues = request.getParameterValues(sParam);
String sValue = "";

for (int i = 0; i < sValues.length; i++)
{
sValue = sValues[i];

if (sValue != null && sValue.trim().length() != 0 && first == true)
{
//第一个参数
first = false;
strbuf.append(sParam).append("=").append(sValue);

} else if (sValue != null && sValue.trim().length() != 0 && first == false)
{
strbuf.append("&").append(sParam).append("=").append(sValue);
}
}
} while (true);

return strbuf.toString();
}

public static void main(String args[])
{
QueryString qs = new QueryString("parms1", "1");
qs.add("parms", "2");
qs.add("parms", "3");
System.out.println(qs.toString()); //parms1=1&parms=2&parms=3
}
}
