开发者

Servlet link relative to application base

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 开发者_如何学Pythona good fix for this problem?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜