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
}
}
posted on 2010-01-31 14:08
fly 阅读(2070)
评论(0) 编辑 收藏 所属分类:
jsp学习