servlet中获得tomcat项目根目录的绝对路径 public class CreateXmlAction extends HttpServlet { private ServletConfig config; public void init(ServletConfig config) throws ServletException { this.config = config; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath = config.getServletContext().getRealPath("/"); } } 或者直接在继承了HttpServlet的Servlet中写: Java代码 String filePath=this.getServletConfig().getServletContext().getRealPath("/");
springmvc
String path=request.getSession().getServletContext().getRealPath("upload/img/product"); //二进制上传 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; //获取文件 CommonsMultipartFile fpic=(CommonsMultipartFile) multipartRequest.getFile("fpic"); //判断是否有文件提交 if(fpic!=null){ if(!fpic.isEmpty()){ String time=DataUtil.getCurrentTimeMillis(); String path=request.getSession().getServletContext().getRealPath("upload/img/product"); File file = new File(path+"/"+time+ ".jpg"); fpicurl = "upload/img/product/p"+time+".jpg"; try { fpic.getFileItem().write(file); } catch (Exception e) { e.printStackTrace(); return; } } }
ssh
使用Struts2的ServletActionContext可以得到项目的真实路径 假如,项目名称为BookSystem,部署到Tomcat的webapps目录下,则 String path=ServletActionContext.getServletContext().getRealPath("/"); path取出的路径为:D:\apache-tomcat-7.0.16\webapps\BookSystem 即:BookSystem项目部署到服务器的完整路径 取出上传路径,并保证路径存在的代码如下: Action类中部分代码: //取出当前项目部署在服务器上的路径 String path=ServletActionContext.getServletContext().getRealPath("/"); //构建当前项目下的存放目录 String filePath=path+"images"; //构建文件对象 File folder=new File(filePath); //检测文件夹是否存在,如果不存在,则新建images目录 if(!folder.exists()){ folder.mkdir(); }