JS获取Request请求参数实现
Javascript版
方法:
String.prototype.getParameter = function (key) {
var re = new RegExp(key + '=([^&]*)(?:&)?');
return this.match(re) && this.match(re)[1];
};
测试代码:
<script type="text/javascript">
<!--
String.prototype.getParameter = function (key) {
var re = new RegExp(key + '=([^&]*)(?:&)?');
return this.match(re) && this.match(re)[1];
};
var s = "http://www.baidu.com/index.html?x0=0&x1=1&x2=2&x3=3&x4=http://www.google.com";
document.write(s.getParameter('x0') + "<br/>");
document.write(s.getParameter('x1') + "<br/>");
document.write(s.getParameter('x2') + "<br/>");
document.write(s.getParameter('x3') + "<br/>");
document.write(s.getParameter('x4') + "<br/>");
document.write(s.getParameter('undefined') + "<br/>");
//-->
</script>
输出:
0
1
2
3
http://www.google.com
null
java版
方法:
public static String getParameter(String url, String key) {
Pattern pat = Pattern.compile("[&?]+" + key + "=([^&]*)&?");
Matcher mat = pat.matcher(url);
if(mat.find()){
return mat.group(1);
}
return null;
}
测试用例:
@Test
public void testGetParameter() {
String url = "http://192.168.11.117/ganglia/graph.php?z=xlarge&c=test&h=192.168.11.139&m=cpu_idle&cs=03%2F22%2F2014+00%3A00&ce=03%2F23%2F2014+12%3A00";
System.out.println(GetParameterTest.getParameter(url, "c"));
System.out.println(GetParameterTest.getParameter(url, "h"));
System.out.println(GetParameterTest.getParameter(url, "zxxx"));
System.out.println(GetParameterTest.getParameter(url, "ce"));
}
作者:不敲代码的攻城狮
出处:https://www.cnblogs.com/leigq/
任何傻瓜都能写出计算机可以理解的代码。好的程序员能写出人能读懂的代码。