如何在不包含上下文根名称的情况下使用相对路径? [英] How to use relative paths without including the context root name?
问题描述
要使用我的静态文件(CSS,JS),我必须编写像/AppName/templates/style/main.css
这样的绝对路径.有什么解决办法,我可以像style/main.css
那样写相对路径?
To working my static file (CSS, JS) I have to write absolute path like /AppName/templates/style/main.css
. Is there any solution, that I could write relative path like style/main.css
?
推荐答案
如果您真正关心的是webapp上下文("AppName"部分)的动态性,则只需通过 HttpServletRequest#getContextPath()
.
If your actual concern is the dynamicness of the webapp context (the "AppName" part), then just retrieve it dynamically by HttpServletRequest#getContextPath()
.
<head>
<link rel="stylesheet" href="${pageContext.request.contextPath}/templates/style/main.css" />
<script src="${pageContext.request.contextPath}/templates/js/main.js"></script>
<script>var base = "${pageContext.request.contextPath}";</script>
</head>
<body>
<a href="${pageContext.request.contextPath}/pages/foo.jsp">link</a>
</body>
如果您想为所有相对链接设置基本路径,从而不必在每个相对链接中重复${pageContext.request.contextPath}
,请使用<base>
标记.这是在 JSTL函数.
If you want to set a base path for all relative links so that you don't need to repeat ${pageContext.request.contextPath}
in every relative link, use the <base>
tag. Here's an example with help of JSTL functions.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<head>
<c:set var="url">${pageContext.request.requestURL}</c:set>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(pageContext.request.requestURI))}${pageContext.request.contextPath}/" />
<link rel="stylesheet" href="templates/style/main.css" />
<script src="templates/js/main.js"></script>
<script>var base = document.getElementsByTagName("base")[0].href;</script>
</head>
<body>
<a href="pages/foo.jsp">link</a>
</body>
这样,每个相对链接(即以/
或方案开头的 not )将相对于<base>
.
This way every relative link (i.e. not starting with /
or a scheme) will become relative to the <base>
.
这与Tomcat毫无关系.它只是与HTTP/HTML基础相关.您将在每台其他Web服务器上遇到相同的问题.
This is by the way not specifically related to Tomcat in any way. It's just related to HTTP/HTML basics. You would have the same problem in every other webserver.
- Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
- Is it recommended to use the <base> html tag?
这篇关于如何在不包含上下文根名称的情况下使用相对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!