Servlet 相对于应用程序库的链接
我正在编写一个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在链接 URL 前面添加域相对路径,包括通过
HttpServletRequest#getContextPath()
。我不使用 Scala,所以我无法给出针对 Scala 的答案,但您可以在 JSP 中执行以下操作,以便图片清晰:当当前上下文路径为
/foo
,那么上面的内容将以 HTML 形式结束,或者如果您在 servlet 类中使用 Java 以编程方式生成 HTML(这实际上是一种不好的做法,但除此之外):
另一种方法是设置
;
标签在 HTML 中,以便所有相对链接都与其相关,另请参阅此答案以获取更多详细信息: 调用转发的 Servlet 时,浏览器无法访问/查找 CSS、图像和链接等相关资源到 JSPYou 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:When the current context path is
/foo
, then the above will end up in HTML asOr if you're generating HTML programmatically using Java inside a servlet class (which is actually a poor practice, but that aside):
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