Skip to content

Commit b574396

Browse files
happyWilliam0rstoyanchev
authored andcommitted
Improve efficiency of UrlPathHelper#getSanitizedPath
See gh-27623
1 parent c5de5c9 commit b574396

File tree

2 files changed

+16
-9
lines changed

2 files changed

+16
-9
lines changed

spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -405,16 +405,17 @@ else if (index1 == requestUri.length()) {
405405
* </ul>
406406
*/
407407
private static String getSanitizedPath(final String path) {
408-
int index = path.indexOf("//");
409-
if (index >= 0) {
410-
StringBuilder sanitized = new StringBuilder(path);
411-
while (index != -1) {
412-
sanitized.deleteCharAt(index);
413-
index = sanitized.indexOf("//", index);
408+
if (path.length() == 0) {
409+
return path;
410+
}
411+
char[] arr = path.toCharArray();
412+
int slowIndex = 0;
413+
for (int fastIndex = 1; fastIndex < arr.length; fastIndex++) {
414+
if (arr[fastIndex] != '/' || arr[slowIndex] != '/') {
415+
arr[++slowIndex] = arr[fastIndex];
414416
}
415-
return sanitized.toString();
416417
}
417-
return path;
418+
return new String(arr, 0, slowIndex + 1);
418419
}
419420

420421
/**
@@ -532,7 +533,7 @@ public String getOriginatingServletPath(HttpServletRequest request) {
532533
*/
533534
public String getOriginatingQueryString(HttpServletRequest request) {
534535
if ((request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE) != null) ||
535-
(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE) != null)) {
536+
(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE) != null)) {
536537
return (String) request.getAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE);
537538
}
538539
else {

spring-web/src/test/java/org/springframework/web/util/UrlPathHelperTests.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,12 @@ void removeDuplicateSlashesInPath() {
246246
request.setRequestURI("/SPR-12372/foo/bar//");
247247

248248
assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/bar//");
249+
250+
// "enhance" case
251+
request.setServletPath("/foo/bar//");
252+
request.setRequestURI("/SPR-12372////////////////////////foo//////////////////bar////////////////////");
253+
254+
assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/bar//");
249255
}
250256

251257
@Test

0 commit comments

Comments
 (0)