JAVAWEB项目获取服务器、项目相关路径方法
做项目的时候,jsp、js、java形式中可能会需要获取一些变化的路径,避免输入过多的硬代码
在java(servlet)中
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/项目名称/ //获取的是服务的访问地址
上面这个可以在jsp中这样写,或在jsp的<script>中
var basePath="<%=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath() %>";
(java获取服务器一些信息的方法(服务器地址/相对路径/端口/项目名字)
request.getServletContext().getRealPath("/") 获取项目所在服务器的全路径,如:D:\Program Files\apache-tomcat-7.0.25\webapps\TestSytem\
request.getServletPath() 获取客户端请求的路径名,如:/object/delObject
request.getServerName() 获取服务器地址,如:localhost
request.getServerPort() 获取服务器端口,如8080
request.getContextPath() 获取项目名称,如:TestSytem
request.getLocalAddr() 获取本地地址,如:127.0.0.1
request.getLocalName() 获取本地IP映射名,如:localhost
request.getLocalPort() 获取本地端口,如:8090
request.getRealPath("/") 获取项目所在服务器的全路径,如:D:\Program Files\apache-tomcat-7.0.25\webapps\TestSytem\
request.getRemoteAddr() 获取远程主机地址,如:127.0.0.1
request.getRemoteHost() 获取远程主机,如:127.0.0.1
request.getRemotePort() 获取远程客户端端口,如:3623
request.getRequestedSessionId() 获取会话session的ID,如:823A6BACAC64FB114235CBFE85A46CAA
request.getRequestURI() 获取包含项目名称的请求路径,如:/TestSytem/object/delObject
request.getRequestURL().toString() 获取请求的全路径,如:http://localhost:8090/TestSytem/object/delObject