Servlet link relative to application base

2020-02-29 06:51发布

问题:

I am writing a servlet (specifically with Scalatra). In the servlet I have many links on a table of contents which is included with every page. I want these links to be relative to the application base. If I use links such as "/foo", everything works fine when the servlet is served from the root (localhost:8080/) but if I serve it from Jetty/Tomcat along with other servlets (localhost:8080/servlet) the link points outside of the servlet.

What is a good fix for this problem?

回答1:

You need to prepend the link URL with a domain-relative path including the context path as obtained by HttpServletRequest#getContextPath(). I don't do Scala, so I can't give a Scala-targeted answer, but here's how you'd do it in JSP so that the picture is sound:

<a href="${pageContext.request.contextPath}/servlet">link</a>

When the current context path is /foo, then the above will end up in HTML as

<a href="/foo/servlet">link</a>

Or if you're generating HTML programmatically using Java inside a servlet class (which is actually a poor practice, but that aside):

out.println("<a href=\"" + request.getContextPath() + "/servlet\">link</a>");

An alternative is to set the <base> tag in HTML so that all relative links are relative to it, see also this answer for more detail: Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP