要使用静态文件(CSS、JS),我必须写绝对路径,例如
/AppName/templates/style/main.css
。是否有解决方案,使我可以写相对路径,例如style/main.css
?/AppName/templates/style/main.css
。是否有解决方案,使我可以写相对路径,例如style/main.css
?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 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>
/
或方案开头的链接)都将变成相对于<base>
。顺便提一下,这与Tomcat无关,只涉及HTTP/HTML基础知识。在任何其他Web服务器中,您都会遇到同样的问题。<c:out>
。完全不了解并拥有非常古老的软件并不是一个合理的负评原因。 - BalusC使用应用程序上下文相对路径,只需使用 <c:url>
标签即可。
当value
参数以 /
开头时,标签将把它视为应用程序相关的URL,并将应用程序名称添加到URL中。
例如:
JSP:
<c:url value="/templates/style/main.css" var="mainCssUrl" />`
<link rel="stylesheet" href="${mainCssUrl}" />
...
<c:url value="/home" var="homeUrl" />`
<a href="${homeUrl}">home link</a>
将成为此HTML,带有相对于域名的URL:
<link rel="stylesheet" href="/AppName/templates/style/main.css" />
...
<a href="/AppName/home">home link</a>
<base href="${pageContext.request.contextPath}/"/>
domain:port
部分,但会包含应用程序上下文。您可以从某个目录启动Tomcat,该目录是Tomcat的$cwd。您可以指定相对于此$cwd的任何路径。
假设您有
home
- tomcat
|_bin
- cssStore
|_file.css
我们可以将整个链接修改为以下方式(解决方案涉及jsp文件):
使用JSTL,我们可以这样做: 要链接资源,如css、js:
<link rel="stylesheet" href="${pageContext.request.contextPath}/style/sample.css" />
<script src="${pageContext.request.contextPath}/js/sample.js"></script>
制作链接的方法:
<a id=".." class=".." href="${pageContext.request.contextPath}/jsp/sample.jsp">....</a>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<link rel="stylesheet" href="<%=request.getContextPath()%>/style/sample.css" />
<script type="text/javascript" src="<%=request.getContextPath()%>/js/sample.js"></script>
制作超链接的方法:
<a id=".." class=".." href="<%=request.getContextPath()%>/jsp/sample.jsp">....</a>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:url value="/" var="root" />
<link rel="stylesheet" href="${root}templates/style/main.css">
style/main.css
都应该可以工作。可能有一些地方不行,但是如果你不告诉别人你实际上想做什么,那么帮助你的人会非常随意,很难成功。 - T.J. Crowder