3

I'm trying to make a link within my my webproject that shows the link's url in the link text.

For example, if I'm working on my localhost's Example project, I want a link to the example.jsp page to look like http://localhost:8081/Example/example.jsp

Where that will link to the /example.jsp page.

I need to be able to do this dynamically.

skaffman
  • 398,947
  • 96
  • 818
  • 769
user906153
  • 1,218
  • 8
  • 30
  • 43
  • Then just do that? What exactly is your question? How to dynamically obtain the hostname, port and/or context name or something? – BalusC Dec 28 '11 at 16:25
  • Yeah, I need to be able to do this dynamically. I've edited my question – user906153 Dec 28 '11 at 16:25
  • For when the project is loaded to a server, so it will be able to get the correct full URL for /example.jsp. – user906153 Dec 28 '11 at 16:30

1 Answers1

8

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>
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Is there a way to do this without installing JSTL? – user906153 Dec 28 '11 at 16:53
  • Yes, just prepare the information in a preprocessing controller servlet (if you have any one... I have the impression that you haven't any one given the fact that you aren't using JSTL), or use *scriptlets* instead (raw Java code embedded in JSPs). *Scriptlets* are however strongly discouraged since over a decade. See also http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files. – BalusC Dec 28 '11 at 16:55
  • Thanks BalusC, I haven't seen that kind of rare code for a while. Your base URL is indeed WORKING. Thanks again! – Mark Joseph Del Rosario Oct 26 '12 at 07:11