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

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


    ContextPathFilter
    com.person.core.web.ContextPathFilter


    ContextPathFilter
    /*
剩下的前台引用就可以了

rel="stylesheet" type="text/css" href="${CP}/css/style.css"/>


2.就是前端页面直接获取(摘自 点击打开链接)

  1. 一.js  
  2. a.'${pageContext.request.contextPath}'//结果:/projectName  
  3. b.'<%=request.getContextPath()%>'//结果:/projectName  
  4. 用法:  

你可能感兴趣的:(spring,mvc,JavaWeb基础知识)