获取服务器的路径(即Java后台代码)html
String path = request.getSession().getServletContext().getRealPath("/upload");web
结果显示为:D:\\apache-tomcat-7.0.42\\webapps\\OA\\uploadapache
2.在jsp上获取路径浏览器
String path = request.getContextPath();tomcat
request.getContextPath()应该是获得项目的名字,若是项目为根目录,则获得一个"",即空的字条串。若是项目为abc,服务器
<%=request.getContextPath()% > 将获得abc,服务器端的路径则会自动加上,<a href="XXXX.jsp"> 是指当前路径下的这个app
xxx.jsp页面,有时候也能够在head里设置html:base来解决路径的问题,不过用的最多的仍是request.getContextPathwebapp
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";jsp
request.getScheme();
返回的协议名称,默认是httpspa
request.getServerName()
返回的是你浏览器中显示的主机名,你本身试一下就知道了
getServerPort()
获取服务器端口号
假定你的web application 名称为news,你在浏览器中输入请求路径:
http://localhost:8080/news/main/list.jsp
则执行下面向行代码后打印出以下结果:
一、 System.out.println(request.getContextPath());
打印结果:/news
二、System.out.println(request.getServletPath());
打印结果:/main/list.jsp
三、 System.out.println(request.getRequestURI());
打印结果:/news/main/list.jsp
四、 System.out.println(request.getRealPath("/"));
打印结果:F:\Tomcat 6.0\webapps\news\test
例如: http://localhost:80/myblog/authen/login.do
request.getSchema()能够返回当前页面使用的协议,就是上面例子中的“http”
request.getServerName()能够返回当前页面所在的服务器的名字,就是上面例子中的“localhost"
request.getServerPort()能够返回当前页面所在的服务器使用的端口,就是80,
request.getContextPath()能够返回当前页面所在的应用(工程或者项目)的名字,就是上面例子中的myblog
这四个拼装起来,就是当前应用的根路径了
String path = request.getContextPath(); //获得的是我要访问的项目名:MAOA
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.getScheme()//获得的是:http
request.getServerName()//获得的是主机名。也就是我要访问的项目的ip,若是是在个人电脑上那么,获得的就是localhost
request.getServerPort();//获得的是我要访问问项目的服务器端口号,
path;就是上面的获得的项目名MAOA