1、在 JSF 环境中获取到 ServletContext:
- ServletContext sc = (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext();
2、servlet 中获得项目绝对路径
- String filePath=this.getServletConfig().getServletContext().getRealPath("/");
根目录所对应的绝对路径
- request.getServletPath();
文件的绝对路径
- request.getSession().getServletContext().getRealPath(request.getRequestURI())
当前 web 应用的绝对路径
- servletConfig.getServletContext().getRealPath("/");
3、jsp 中获取服务器路径
- String contextPath = request.getContextPath();
- String realPath = request.getSession().getServletContext().getRealPath("/");
- String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + contextPath + "/";
说明:
contextPath ="/ 项目名称"; // 获取的是项目的相对路径
realPath = F:\tomcat_home\webapps \ 项目名称 \ // 获取的是项目的绝对路径
basePath = http://localhost:8080 / 项目名称 / // 获取的是服务的访问地址
4、ServletContext 对象获得几种方式
- Javax.servlet.http.HttpSession.getServletContext()Javax.servlet.jsp.PageContext.getServletContext()Javax.servlet.ServletConfig.getServletContext()
文件的绝对路径
- request.getSession().getServletContext().getRealPath(request.getRequestURI())
当前 web 应用的绝对路径
- servletConfig.getServletContext().getRealPath("/");
就爱阅读 www.92to.com 网友整理上传, 为您提供最全的知识大全, 期待您的分享,转载请注明出处。
来源: http://www.92to.com/bangong/2017/04-18/20613017.html