获取项目的根路径(后台,前段两种手段)

本文介绍两种获取Web项目路径的方法:一是通过自定义过滤器在Java后台设置并传递项目路径;二是直接在前端页面使用JSP内置对象获取项目路径。文中提供了具体的实现代码及示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>  
[html]  view plain  copy
  1. 二.jsp  
  2. a.<%=request.getContextPath()%>//结果:/projectName  
  3. b.${pageContext.request.contextPath}//结果:/projectName  
  4. 用法:  
  5. <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/order/css/OrderCss.css" />   
  6. <link rel="stylesheet" type="text/css" href=<%=request.getContextPath()%>+"/order/css/OrderCss.css" />   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值