get absolute URL with EL
Asked Answered
I

3

11

How can I build up an absolute URL using no scriptlets (only EL) to the current server, using the current protocol, port, application etc?

Informative answered 18/4, 2011 at 14:51 Comment(5)
Absolute URL to where? From what information? We need a lot more information to help you, I'm afaid..Banner
like this: String s = "http://www.example.com" :) Well, jokes apart, what do you mean exactly? Building from what? And, pardon my ignorance, what is "EL"?Lovellalovelock
Sorry All, I mean to the current server. Using the current protocol and port etcInformative
@MarcoS: hover the [el] tag below the question and read the popbox and click if necessary the info link therein.Algonkian
@BalusC: ah, stupid me! thank you for suggesting this.Lovellalovelock
A
25

You can get the base URL up to with the context root with help of JSTL as follows:

<%@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="baseURL" value="${fn:replace(pageContext.request.requestURL, pageContext.request.requestURI, pageContext.request.contextPath)}" />
...
<link rel="stylesheet" href="${baseURL}/foo.css" />
<script src="${baseURL}/foo.js"></script>
<a href="${baseURL}/foo.jsp">link</a>
Algonkian answered 18/4, 2011 at 15:5 Comment(1)
In my setup, this results in a URL with http instead of https.Pungy
I
4

Another way is:

http://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/thePage.jsp
Informative answered 12/5, 2011 at 16:22 Comment(2)
localPort is however incorrect. Use serverPort. The only disadvantage of this way is that you still ends with an ugly port number in URL when the site runs on default HTTP ports 80 or 443.Algonkian
Thanks. Of course. Well spotted. For my use the ports are not default, otherwise i'd simply leave it off.Informative
A
-1

Yet another way is:

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

I'm quite surprised when the GitHub Copilot just suggested the code snippet. ~~ :)

Ayn answered 9/11, 2022 at 0:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.