Search code examples
javajspurlservlets

How to get the base URL from JSP request object?


How to get the base URL from the JSP request object?

Here is an example of the full URL:

http://localhost:8080/SOMETHING/index.jsp

What I want is the part till index.jsp, how is it possible in JSP?


Solution

  • 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 <base>, 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: