哪里有几种方法。
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
可以设置为contex 部署描述符中的 WAR 文件dev
或在外部设置,如果未设置,则回退到缩小版本。min
4)使用脚本:
<a href="<%=request.getContextPath()%>/index.html">Home</a>