1. 程式人生 > >獲取專案的根路徑(後臺,前段兩種手段)

獲取專案的根路徑(後臺,前段兩種手段)

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.就是前端頁面直接獲取(摘自 點選開啟連結
  1. 一.js  
  2. a.'${pageContext.request.contextPath}'//結果:/projectName
  3. b.'<%=request.getContextPath()%>'//結果:/projectName
  4. 用法:  
  5. <script>  
  6. function searchData(dom){  
  7.    $(dom).attr('disabled'true);  
  8.    var url = '${pageContext.request.contextPath}/OrderController/getOrders.mmx?'+$('#orderForm').serialize();  
  9.    var url = '<%=request.getContextPath()%>'+'/OrderController/getOrders.mmx?'+$('#orderForm').serialize();  
  10.    $('#dataDiv').html('資料載入中...').load(url, function(){  
  11.       $(dom).attr('disabled'false);  
  12.    });  
  13. }  
  14. <script>  
  1. 二.jsp  
  2. a.<%=request.getContextPath()%>//結果:/projectName  
  3. b.${pageContext.request.contextPath}//結果:/projectName  
  4. 用法:  
  5. <linkrel="stylesheet"type="text/css"href="${pageContext.request.contextPath}/order/css/OrderCss.css"/>
  6. <linkrel="stylesheet"type="text/css"href=<%=request.getContextPath()%>+"/order/css/OrderCss.css" />