JAVA获取服务器路径的方法

xiaoxiao2021-02-28  133

JAVA获取服务器路径的方法

1、在JSF环境中获取到ServletContext:

1 2 ServletContext sc = (ServletContext)FacesContext.          getCurrentInstance().getExternalContext().getContext();

2、servlet中获得项目绝对路径

1 2 String filePath= this .getServletConfig().          getServletContext().getRealPath( "/" );

根目录所对应的绝对路径 request.getServletPath(); 文件的绝对路径 request.getSession().getServletContext().getRealPath(request.getRequestURI()) 当前web应用的绝对路径 servletConfig.getServletContext().getRealPath(“/”);

ps: 一般情况下,以下的路径获取可以满足一般的需求了

1 2 3 4 5 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/项目名称/ //获取的是服务的访问地址 3、ServletContext对象获得几种方式

1 2 3 Javax.servlet.http.HttpSession.getServletContext() Javax.servlet.jsp.PageContext.getServletContext() Javax.servlet.ServletConfig.getServletContext()
转载请注明原文地址: https://www.6miu.com/read-29207.html

最新回复(0)