Copy codeThe Code is as follows:
Package RequestPackage;
Import java. util. HashMap;
Import java. util. Map;
Public class CRequest {
/**
* Parse the url request path, including the page
* @ Param strURL url
* @ Return url path
*/
Public static String UrlPage (String strURL)
{
String strPage = null;
String [] arrSplit = null;
StrURL = strURL. trim (). toLowerCase ();
ArrSplit = strURL. split ("[?] ");
If (strURL. length ()> 0)
{
If (arrSplit. length> 1)
{
If (arrSplit [0]! = Null)
{
StrPage = arrSplit [0];
}
}
}
Return strPage;
}
/**
* Remove the path from the url and leave the Request Parameters
* @ Param strURL url
* @ Return url request parameters
*/
Private static String TruncateUrlPage (String strURL)
{
String strAllParam = null;
String [] arrSplit = null;
StrURL = strURL. trim (). toLowerCase ();
ArrSplit = strURL. split ("[?] ");
If (strURL. length ()> 1)
{
If (arrSplit. length> 1)
{
If (arrSplit [1]! = Null)
{
StrAllParam = arrSplit [1];
}
}
}
Return strAllParam;
}
/**
* Parse the key-value pairs in the url parameter
* For example, "index. jsp? Action = del & id = 123 ", parses Action: del, id: 123 and saves it to map.
* @ Param URL url
* @ Return url request parameters
*/
Public static Map <String, String> URLRequest (String URL)
{
Map <String, String> mapRequest = new HashMap <String, String> ();
String [] arrSplit = null;
String strUrlParam = TruncateUrlPage (URL );
If (strUrlParam = null)
{
Return mapRequest;
}
// Each key value is a group
ArrSplit = strUrlParam. split ("[&]");
For (String strSplit: arrSplit)
{
String [] arrSplitEqual = null;
ArrSplitEqual = strSplit. split ("[=]");
// Parse the key value
If (arrSplitEqual. length> 1)
{
// Correct Parsing
MapRequest. put (arrSplitEqual [0], arrSplitEqual [1]);
}
Else
{
If (arrSplitEqual [0]! = "")
{
// Only the parameter has no value and is not added
MapRequest. put (arrSplitEqual [0], "");
}
}
}
Return mapRequest;
}
}
Test class
Copy codeThe Code is as follows:
Package RequestPackage;
Import java. util. Map;
Public class TestCRequest {
/** Used to test the CRequest class
* @ Param args
*/
Public static void main (String [] args ){
// Request url
String str = "index. jsp? Action = del & id = 123 & sort = ";
// Url page path
System. out. println (CRequest. UrlPage (str ));
// Url parameter key-Value Pair
String strRequestKeyAndValues = "";
Map <String, String> mapRequest = CRequest. URLRequest (str );
For (String strRequestKey: mapRequest. keySet ()){
String strRequestValue = mapRequest. get (strRequestKey );
StrRequestKeyAndValues + = "key:" + strRequestKey + ", Value:" + strRequestValue + ";";
}
System. out. println (strRequestKeyAndValues );
// When an invalid key is obtained, null is output.
System. out. println (mapRequest. get ("page "));
}
}
Test code running effect
Index. jsp
Key: id, Value: 123; key: sort, Value:; key: action, Value: del;
Null