I want to get {testId : 111} from /v1/testId/111 example URL.
I know that it is very simple to get path variable if using the request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE) method.
But, filters are executed before Servlets.
Therefore, request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE) method is not available.
(ref. How to get Path Variables in Spring Filter?)
Is there any way to retrieve Path Variable within the filter?
Or, Is there any way to retrieve Path Variable without request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE) method?
The String of /v1/testId/111 is actually available and I intend to extract 111 from it.
You are looking for lastIndexOf, a method of String.
String foo = "/v1/testId/111";
String theValue = foo.substring(foo.lastIndexOf("/") + 1);
lastIndexOf returns the numerical position of the last slash in this case and getting the substring from the next numerical position will effectively return everything you have after the last slash.
EDIT
If you have more instances, like /v1/testId/111/userId/222, then you could split your String, like
String string = "/v1/testId/111/userId/222";
String[] parts = string.split("/");
for (int index = 0; index < parts.length; index++) {
if (isNumeric(parts(index))) {
//Do something with these values as you please
String entityName = parts[index - 1];
String entityValue = parts[index];
}
}
isNumeric is implemented as such:
public static boolean isNumeric(String strNum) {
if ((strNum == null) || (strNum.equals(""))) {
return false;
}
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
Courtesy to https://www.baeldung.com/java-check-string-number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With