RequestUtils { public static String buildBaseUrl(final HttpServletRequest request) { final String requestUri = Optional.ofNullable((String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI)) .orElseGet(request::getRequestURI); final String path = requestUri.replaceFirst(request.getContextPath(), ""); final int depth = StringUtils.countMatches(path, "/") - 1; return depth <= 0 ? "." : StringUtils.repeat("../", depth); }  static String buildBaseUrl(final HttpServletRequest request);  }
@Test public void buildsBaseUrlForRootPath() { final HttpServletRequest request = mockRequest("/", null); assertThat(RequestUtils.buildBaseUrl(request), is(".")); }
@Test public void buildsBaseUrlForDeepPath() { final HttpServletRequest request = mockRequest("/foo/bar/baz", null); assertThat(RequestUtils.buildBaseUrl(request), is("../../")); }
@Test public void buildsBaseUrlForForward() { final HttpServletRequest request = mockRequest("/forward/error", "/foo/bar/baz"); assertThat(RequestUtils.buildBaseUrl(request), is("../../")); }
@Test public void endsInAForwardSlash() { final HttpServletRequest request = mockRequest("/foo/bar", null); assertThat(RequestUtils.buildBaseUrl(request), is("../")); }