Issue
I have set up the following patterns:
Pattern regExAllPattern = Pattern.compile("/customers");
Pattern regExIdPattern = Pattern.compile("/customers/([0-9A-Za-z]{32})");
Pattern regExCategoryPattern = Pattern.compile("/customers/category/([0-9A-Za-z]+)");
Here I collect the incoming path:
String pathInfo = req.getPathInfo();
Which I try to match with the resular expressions
Matcher matchRecord = regExIdPattern.matcher(pathInfo);
Matcher matchCollection = regExAllPattern.matcher(pathInfo);
Matcher matchCollectionCategory = regExCategoryPattern.matcher(pathInfo);
Then I act upon the matchers above:
if (matchRecord.find()) {
System.out.println("FIND CUSTOMER RECORD");
System.out.println("====================");
//do something
} else if (matchCollection.find()) {
System.out.println("FIND ALL CUSTOMERS");
System.out.println("====================");
//do domething
} else if (matchCollectionCategory.find()) {
String category = matchCollectionCategory.group(1); // .group(1);
System.out.println("FIND CUSTOMERS BY CATEGORY: " + category);
System.out.println("====================");
//do something
} else {
System.out.println("can not find match");
}
Now when I open an URL view to find customers by category the pathinfo is as followed:
HTTP JVM: PATHINFO received = /xsp/customers/category/edd
However matchCollection.find() returns true so I get as output:
HTTP JVM: FIND ALL CUSTOMERS
What am I doing wrong here? What must I do to make sure that matchCollection.find() returns false for incoming path /xsp/customers/category/edd ?
Solution
Because it matches. The string /customers is found in the url.
You can build a more complex regex, or the easy way is starting the if sequences by the most explicit first ending with the shortest pattern:
if (matchCollectionCategory.find()) {
String category = matchCollectionCategory.group(1); // .group(1);
System.out.println("FIND CUSTOMERS BY CATEGORY: " + category);
System.out.println("====================");
//do something
} else if (matchRecord.find()) {
System.out.println("FIND CUSTOMER RECORD");
System.out.println("====================");
//do something
} else if (matchCollection.find()) {
System.out.println("FIND ALL CUSTOMERS");
System.out.println("====================");
//do domething
} else {
System.out.println("can not find match");
}
There are two (among many others of course) special chars:
^means start of the sequence$means end of sequence
So, if you want a String to match exactly /customers and nothing else, you would use ^/customers$. That pattern will not match against whatever/customers/whatever. But without those, the matcher will try to find the sequence in whatever part of the String. Please refer to java Pattern class for more info about pattern matching; you can find there all the available options.
Answered By - gmanjon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.