Servlet link relative to application base

早过忘川 提交于 2019-11-29 23:13:14

问题


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



来源:https://stackoverflow.com/questions/7367515/servlet-link-relative-to-application-base

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!