You could use JSTL as follows to obtain the site's base URL:
<%@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="base" value="${fn:substring(url, 0, fn:length(url) - fn:length(req.requestURI))}${req.contextPath}/" />
...
(the req
is in the above example just a shorthand to the current instance of HttpServletRequest, the <c:set var="url">
line basically converts the StringBuffer
returned by HttpServletRequest#getRequestURL()
to String
so that it can be used in the string functions)
Then you can create the link as follows:
<a href="${base}example.jsp">${base}example.jsp</a>
Or maybe, when using the HTML <base>
tag which makes all relative links in the document relative to it:
<head>
<base href="${base}" />
</head>
<body>
<a href="example.jsp">${base}example.jsp</a>
</body>