哪裏有幾種方法。
1)綁定基地變量在共同片段:
common.jspf
:
<%@tag language="java" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:url value="/" var="base"/>
或類似:
<c:set var="base" value="${pageContext.request.contextPath}"/>
和包括在每個頁面片段:
<%@include file="base.jspf"%>
<script src="${base}/js/jquery.js"></script>
<link href="${base}/css/bootstrap.css" rel="stylesheet" type="text/css">
<a href="${base}/index.html">Home</a>
2)使用${pageContext.request.contextPath}
無處不在:
<script src="${pageContext.request.contextPath}/js/jquery.js"></script>
<link href="${pageContext.request.contextPath}/css/bootstrap.css" rel="stylesheet" type="text/css">
<a href="${pageContext.request.contextPath}/index.html">Home</a>
3)是我最喜歡的:添加過濾器,包括屬性基地:
/src/java/company/project/web/filter/BaseFilter.java
import java.io.IOException;
import javax.servlet.*;
/**
* Make sane JSP, instead of:
* <pre><a href="<c:url value='/my/path/${id}.html'/>">Title</a></pre>
* allow to use:
* <pre><a href="${ctx}/my/path/${id}.html">Title</a></pre>
*/
public class BaseFilter implements Filter {
@Override
public void init(FilterConfig fc) {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setAttribute("base", request.getServletContext().getContextPath());
chain.doFilter(request, response);
}
@Override
public void destroy() { }
}
和寄存器,濾波器在web.xml
:
<filter>
<filter-name>BaseFilter</filter-name>
<filter-class>company.project.web.filter.BaseFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>BaseFilter</filter-name>
<url-pattern>*.htm</url-pattern>
<url-pattern>*.json</url-pattern>
</filter-mapping>
,並使用乾淨的語法(如上面但沒有必要包括樣板片段):
<script src="${base}/js/jquery.js"></script>
<link href="${base}/css/bootstrap.css" rel="stylesheet" type="text/css">
<a href="${base}/index.html">Home</a>
注我在該過濾器設置額外的屬性,爲在CSS/JS的開發和精簡版之間切換的示例:
private String min;
@Override
public void init(FilterConfig fc) {
min = fc.getServletContext().getInitParameter("min");
if (min == null)
min = fc.getInitParameter("min");
if (min == null)
min = "min";
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setAttribute("ctx", request.getServletContext().getContextPath());
request.setAttribute("min", min);
chain.doFilter(request, response);
}
和相應的JSP代碼:
<script src="${base}/js/jquery.${min}.js"></script>
<link href="${base}/css/bootstrap.${min}.css" rel="stylesheet" type="text/css">
初始參數min
可以不設置在當從外部設定到dev
或min
於與回退,以縮小的版本CONTEX部署描述符WAR文件。
4)使用scriplets:
<a href="<%=request.getContextPath()%>/index.html">Home</a>
'$ {} pageContext.request.contextPath/nextPage.jsp'?不適用於出站,但它使應用程序內的鏈接非常乾淨。 –
雖然沒有解決目標。重點是通過Tomcat提供的整個出站鏈接格式化邏輯以及您已安裝的任何過濾器(如urlrewrite)來運行url。在這種情況下,我們正在做一些比絕對路徑更復雜的事情,我們正在重寫js文件以包含用於緩存清除的構建版本。 – JBCP