獲取專案的根路徑(後臺,前段兩種手段)
阿新 • • 發佈:2019-02-09
1.通過能過濾器新增
public class ContextPathFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException,ServletException {
String path = ((HttpServletRequest)servletRequest).getContextPath(); String basepath = path; servletRequest.setAttribute("CP", basepath); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }當然了還得新增到web.xml
<filter>剩下的前臺引用就可以了<filter-name>ContextPathFilter</filter-name> <filter-class>com.person.core.web.ContextPathFilter</filter-class> </filter> <filter-mapping> <filter-name>ContextPathFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<link rel="stylesheet" type="text/css" href="${CP}/css/style.css"/>
<script type="text/javascript"> var basePath = '${CP}';
</script>
2.就是前端頁面直接獲取(摘自 點選開啟連結)
- 一.js
- a.'${pageContext.request.contextPath}'//結果:/projectName
- b.'<%=request.getContextPath()%>'//結果:/projectName
- 用法:
- <script>
- function searchData(dom){
- $(dom).attr('disabled', true);
- var url = '${pageContext.request.contextPath}/OrderController/getOrders.mmx?'+$('#orderForm').serialize();
- var url = '<%=request.getContextPath()%>'+'/OrderController/getOrders.mmx?'+$('#orderForm').serialize();
- $('#dataDiv').html('資料載入中...').load(url, function(){
- $(dom).attr('disabled', false);
- });
- }
- <script>
- 二.jsp
- a.<%=request.getContextPath()%>//結果:/projectName
- b.${pageContext.request.contextPath}//結果:/projectName
- 用法:
- <linkrel="stylesheet"type="text/css"href="${pageContext.request.contextPath}/order/css/OrderCss.css"/>
- <linkrel="stylesheet"type="text/css"href=<%=request.getContextPath()%>+"/order/css/OrderCss.css" />