0

I want to get the current URL of my website. Not the context, not the ports, not the scheme or the protocol. Only the relative url. For example:

https://www.myurl.com/context/relative/url/site.mvc

I want to have:

/relative/url/site.mvc

${pageContext.request.contextPath} gives me: /context/ ${pageContext.request.requestURL} gives me https://www.myurl.com/context/WEB-INF/tiles/relative/url/site/center.jsp Thats where the site is located in my directory.

But I want the relative path of the website... without Javascript!

DonMarco
  • 405
  • 2
  • 14
  • 34

2 Answers2

3

So, you want the base URL? You can get it in a servlet as follows:

String url = request.getRequestURL().toString();
String baseURL = url.substring(0, url.length() - request.getRequestURI().length()) + request.getContextPath() + "/";
// ...

Or in a JSP, as , with little help of JSTL:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />
...
<head>
    <base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/" />
</head>

Note that this does not include the port number when it's already the default port number, such as 80. The java.net.URL doesn't take this into account.

See also:

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

jsp file:

request.getAttribute("javax.servlet.forward.request_uri")
Community
  • 1
  • 1
jmail
  • 5,944
  • 3
  • 21
  • 35
  • I wanted to have the relative path, not the base url. But your idea helped a lot, see my post below! Thanks! – DonMarco Mar 18 '14 at 14:19
3

Thank you @jmail.

Your statement brought me on the right track. But I did not want the base url, but the solution would be this:

<c:set var="currentUrl" value="${pageContext.request.request.getAttribute('javax.servlet.forward.request_uri')}"/>

<c:set var="contextPath" value="${pageContext.request.contextPath}"/>

<c:forEach items="${paramValues}" var="paramItem">
  <c:set var="urlParams" value="${urlParams}&${paramItem.key}=${paramItem.value[0]}"/>
</c:forEach>

<c:set var="urlParams" value="${fn:substring(urlParams,  1, fn:length(urlParams))}" />

<c:set var="relativeUrl" value="${fn:substring(currentUrl,  fn:length(contextPath), fn:length(currentUrl))}?${urlParams}" />

You forgot the parameters, and your version extracted the base, instead of the relative path!

DonMarco
  • 405
  • 2
  • 14
  • 34