Servlet 相对于应用程序库的链接

发布于 2024-12-04 03:30:49 字数 244 浏览 5 评论 0原文

我正在编写一个servlet(特别是使用Scalatra)。在 servlet 中,我在每个页面都包含的目录上有许多链接。我希望这些链接与应用程序库相关。如果我使用诸如“/foo”之类的链接,则当从根(localhost:8080 /)提供servlet时一切正常,但如果我从Jetty / Tomcat与其他servlet(localhost:8080 / servlet)一起提供它,则链接指向 servlet 外部。

对于这个问题有什么好的解决办法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

左秋 2024-12-11 03:30:49

您需要在链接 URL 前面添加域相对路径,包括通过 HttpServletRequest#getContextPath()。我不使用 Scala,所以我无法给出针对 Scala 的答案,但您可以在 JSP 中执行以下操作,以便图片清晰:

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

当当前上下文路径为 /foo,那么上面的内容将以 HTML 形式结束,

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

或者如果您在 servlet 类中使用 Java 以编程方式生成 HTML(这实际上是一种不好的做法,但除此之外):

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

另一种方法是设置 ; 标签在 HTML 中,以便所有相对链接都与其相关,另请参阅此答案以获取更多详细信息: 调用转发的 Servlet 时,浏览器无法访问/查找 CSS、图像和链接等相关资源到 JSP

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文