String ContextPath = request.getContextPath();这个获取的是上下文路径,一般就是项目名字,如果上下文路径为空,则这个输出也为空。
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + ContextPath + "/";
System.out.println("basePath:"+basePath);
输出的效果是:basePath:http://localhost:8084/calls/
request.getScheme() 获取到 http
request.getServerName() 获取到localhost,就是IP地址
request.getServerPort() 获取到 8084端口号
String path = request.getSession().getServletContext().getRealPath("/");
System.out.println("path:"+path);
path:C:\Users\Administrator\Documents\NetBeansProjects\WebApplication11\build\web\
这个web文件夹下面就是/WEB-INF/之类的文件夹了
request.getSession().getServletContext() 获取的是Servlet容器对象,相当于tomcat容器了。getRealPath("/") 获取实际路径,“/”指代项目根目录,所以代码返回的是项目在容器中的实际发布运行的根路径如:I:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\UMPWeb_20131230\
得到的就是你tomcat下webapps下的项目根路径
那么请问一下如果我往这个路径存文件是把文件存到了服务器上了吗?
是的。
request.getSession().getServletContext() 获取的是Servlet容器对象,相当于tomcat容器了。getRealPath("/") 获取实际路径,“/”指代项目根目录,所以代码返回的是项目在容器中的实际发布运行的根路径
在工程的WebContent下新建一个upload的目录
// 文件保存路径
String filePath = realPath + "upload/"+ file.getOriginalFilename();
本文详细解析了Java Web应用程序中如何获取项目的上下文路径、实际路径及如何在服务器上存储文件。介绍了使用request对象获取http方案、服务器名称、端口号等信息的方法,以及通过getSession()和getServletContext()获取Servlet容器对象并获取项目根目录实际路径的过程。
10万+

被折叠的 条评论
为什么被折叠?



