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,16 +405,17 @@ 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) { return path;
StringBuilder sanitized = new StringBuilder(path);
while (index != -1) {
sanitized.deleteCharAt(index);
index = sanitized.indexOf("//", index);
}
return sanitized.toString();
} }
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);
} }
/** /**
@ -532,7 +533,7 @@ public class UrlPathHelper {
*/ */
public String getOriginatingQueryString(HttpServletRequest request) { public String getOriginatingQueryString(HttpServletRequest request) {
if ((request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE) != null) || if ((request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE) != null) ||
(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE) != null)) { (request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE) != null)) {
return (String) request.getAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE); return (String) request.getAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE);
} }
else { else {

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