Improve efficiency of UrlPathHelper#getSanitizedPath

See gh-27623
This commit is contained in:
happyWilliam0 2021-10-29 14:14:05 +08:00 committed by Rossen Stoyanchev
parent c5de5c9939
commit b5743966d6
2 changed files with 17 additions and 10 deletions

View File

@ -405,17 +405,18 @@ public class UrlPathHelper {
* </ul> * </ul>
*/ */
private static String getSanitizedPath(final String path) { private static String getSanitizedPath(final String path) {
int index = path.indexOf("//"); if (path.length() == 0) {
if (index >= 0) {
StringBuilder sanitized = new StringBuilder(path);
while (index != -1) {
sanitized.deleteCharAt(index);
index = sanitized.indexOf("//", index);
}
return sanitized.toString();
}
return path; return path;
} }
char[] arr = path.toCharArray();
int slowIndex = 0;
for (int fastIndex = 1; fastIndex < arr.length; fastIndex++) {
if (arr[fastIndex] != '/' || arr[slowIndex] != '/') {
arr[++slowIndex] = arr[fastIndex];
}
}
return new String(arr, 0, slowIndex + 1);
}
/** /**
* Return the request URI for the given request, detecting an include request * Return the request URI for the given request, detecting an include request

View File

@ -246,6 +246,12 @@ class UrlPathHelperTests {
request.setRequestURI("/SPR-12372/foo/bar//"); request.setRequestURI("/SPR-12372/foo/bar//");
assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/bar//"); assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/bar//");
// "enhance" case
request.setServletPath("/foo/bar//");
request.setRequestURI("/SPR-12372////////////////////////foo//////////////////bar////////////////////");
assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/bar//");
} }
@Test @Test