Question

I'm using JSP to make some pages and I'm having trouble with anchor locations.

When I'm at page /somepage/something and on that page I want to link to page /somepage/something/code. Now, if I use this code:

<a href="<c:out value="${code}" />">Link</a>

it results in the link <a href="http://my-server:port/somepage/code">Link</a>.

If I use this code:

<a href="./<c:out value="${code}" />">Link</a>

it results in the link <a href="http://my-server:port/somepage/code">Link</a>.

And if I use this code:

<a href="<c:out value="/${code}" />">Link</a>

it results in the link <a href="http://my-server:port/code">Link</a>.

How can I make the link <a href="http://my-server:port/somepage/something/code">Link</a>?

Was it helpful?

Solution

When the browser loads a page at /somepage/something (without a trailing slash), it interprets the path as "the file something in the directory /somepage". So when it sees links like

<a href="code">Link</a>

or

<a href="./code">Link</a>

it interprets them as being relative to the current directory, i.e. /somepage, which is why they resolve to /somepage/code.

If you want a (relative) link to /somepage/something/code, you will need a link like

<a href="something/code">Link</a>

(Note that if your page is at /somepage/something/ (with a trailing slash), then the browser interprets /somepage/something as the directory. In this case, your first two attempts would work as expected.)

OTHER TIPS

That's the big problem with urls. I had the same issue using nodejs. finally I used the module URIjs to build an url. You can find a suited lib for JSP, of just remove the things after lastest slash and add your ${code}. See also How to get just the parent directory name of a specific file and http://arstechnica.com/civis/viewtopic.php?f=20&t=459188

For example :

<%@ page import="java.io.File" %>

<%

  File f = new File(currentUrl);

%>
<a href="<%= f.getParent() + code %>">Link</a>

Depending on the web framework you are using you can try one of the following:

<%
    String var = (String)pageContext.getRequest().getAttribute("javax.servlet.forward.request_uri");
    request.setAttribute("forwardURI", var);
%>
<a href="${forwardURI}/${code}">Link</a>

or simply

<a href="${pageContext.request.requestURI}/${code}">Link</a>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top