JAVA,JSP,Servlet,Js 获取当前工程路径-绝对路径

时间:2022-08-26 15:32:56

在jsp和class文件中调用的相对路径不同。 在jsp里,根目录是WebRoot 在class文件中,根目录是WebRoot/WEB-INF/classes 当然你也可以用System.getProperty("user.dir")获取你工程的绝对路径。

另:在Jsp,Servlet,Java中详细获得路径的方法!

1.jsp中取得路径:

以工程名为TEST为例:

(1)得到包含工程名的当前页面全路径:request.getRequestURI()
结果:/TEST/test.jsp
(2)得到工程名:request.getContextPath()
结果:/TEST
(3)得到当前页面所在目录下全名称:request.getServletPath()
结果:如果页面在jsp目录下 /TEST/jsp/test.jsp
(4)得到页面所在服务器的全路径:application.getRealPath("页面.jsp")
结果:D:\resin\webapps\TEST\test.jsp
(5)得到页面所在服务器的绝对路径:absPath=new java.io.File(application.getRealPath(request.getRequestURI())).getParent();
结果:D:\resin\webapps\TEST

2.在类中取得路径:

(1)类的绝对路径:Class.class.getClass().getResource("/").getPath()
结果:/D:/TEST/WebRoot/WEB-INF/classes/pack/
(2)得到工程的路径:System.getProperty("user.dir")
结果:D:\TEST

3.在Servlet中取得路径:

(1)得到工程目录:request.getSession().getServletContext().getRealPath("") 参数可具体到包名。
结果:E:\Tomcat\webapps\TEST
(2)得到IE地址栏地址:request.getRequestURL()
结果:http://localhost:8080/TEST/test
(3)得到相对地址:request.getRequestURI()

结果:/TEST/test

4.在js中获取项目绝对地址

var curWwwPath = window.document.location.href;
  var pathName =  window.document.location.pathname;
  var pos = curWwwPath.indexOf(pathName);
  var localhostPaht = curWwwPath.substring(0,pos);
  var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
var Path=localhostPaht + projectName;

Path即是绝对路径地址,包括ip端口和项目名


附加:

在JSP中我们表示绝对路径可以使用EL表达式:${pageContext.request.contextPath}

这种方式是调用隐式的pageContext对象,然后在得到HttpServletRequest对象,最后再拿到contextPath。

该方式是以属性的形式出现。

同样可以采用JSP的形式来表示:<%=request.getContextPath()%>

该方式调用的jsp的内置的HttpServletRequest对象,此时用点是点不出来的,需要使用get方式的形式。

网上还有关于使用jstl中的set设置变量的方式也列出来:

<c:set var="ctx" value="${pageContext.request.contextPath}" />

想获得带ip和端口的地址:

String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";