Accessing the full url, including hostname with jstl
30,676
Solution 1
You need to prepare it yourself based on HttpServletRequest#getRequestURL()
and a little help of JSTL functions:
<c:set var="req" value="${pageContext.request}" />
<c:set var="baseURL" value="${fn:replace(req.requestURL, fn:substring(req.requestURI, 1, fn:length(req.requestURI)), req.contextPath)}" />
...
<c:url var="myUrl" value="${baseURL}/${MyID}"/>
Solution 2
HttpServletRequest object has all the details:
getProtocol
getServerName
getContextPath
so I think you can use:
${request.protocol} :// ${request.serverName} ${request.contextPath} /etc
to build what you want.
Author by
NimChimpsky
side hustle : metriculous.network Spring is too bloated, I created my own web app framework Infrequent tweets What if programming languages were methods to eat an orange?
Updated on February 18, 2020Comments
-
NimChimpsky about 4 years
<c:url var="myUrl" value="/MyPath/${MyID}"/>
which I then use later (to enable users to copy links) :
<input size="35" disabled value="${myUrl}" />
and it shows
/my-app-name/MyPath/23
however I want it to be
http://myHost/my-app-name/MyPath/23
I can prepend the string sure, but wanted a way to actively get the correct hostname ... ?
-
NimChimpsky over 12 yearsthat was quick, thnx, will give it a shot.
-
BalusC over 12 yearsYou would only end up in a clumsy if-else logic flow in order to hide the port whenever it's already the default port for the given protocol. It's easier to build based on
getRequestURL()
. Also, thegetServerName()
is manipulatable by the client through theHost
request header, I wouldn't rely on this. -
helios over 12 yearsOk. I didn't think about hiding the port. I didn't go the getRequestURL way because the OP wanted to change the URL. One question. I didn't understood the servername manipulation. Is it that if the client send a Host:www.other.com that will get into our built URL?
-
cthiebaud about 10 yearson tomcat 7.0.52, I had to change the start of the substring from 1 to 0 :
fn:substring(req.requestURI, 0, fn:length(req.requestURI)), etc.
-
cthiebaud about 10 yearseven better, on tomcat 7.0.52, simplified baseURL works for me:
<c:set var="baseURL" value="${fn:replace(req.requestURL, req.requestURI, req.contextPath)}" />
-
BalusC about 10 years@cthiebaud: this fails if webapp is deployed to context root and the request URI is "/". This also fails if the request URL contains -by coincidence- repeated parts of request URI. You'd really better substring off the exact part by index.
-
Julien D over 7 yearsgot it working with ${pageContext.request.serverName}
-
Francisco Souza over 7 yearsWhat if I whant to get only the "page name", example: if i have localhost:8080/ticket/pages/cadastro.jsf then I need to check is "this" page is equal to "cadastro.jsf" (JSF/Primefaces) ?