JavascriptはRequest要求パラメータを取得して実現します.

1931 ワード

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 3http://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"));

	}