The request. getRealPath ("/xx/yy") method in JSP prompts an outdated alternative method.
When uploading files, our JSP project usually needs to obtain the absolute path of the directory on the server. The request. getRealPath () method is outdated, but there are alternative methods.
HttpSession session = request. getSession (true); // get session // String path = request. getRealPath ("/data/userfile/image"); // This method is obsolete String path = session. getServletContext (). getRealPath ("/data/userfile/image"); // file storage path
In servlet or struts, you can also write as follows:
this.getServletContext().getRealPath("/data/userfile/image");this.getServlet().getServletContext().getRealPath("/data/userfile/image");
Related Introduction: In the latest Java Servlet API 2.1 version, we do not agree to use the request. getRealPath () method, instead of ServletContext. getRealPath (java. lang. String. In the Servlet 2.4 document, set ServletContext. getRealPath (java. lang. string) is described as follows: return a String that contains the real path of a given virtual path. If the conversion is incorrect, return null. For example, the virtual path "/index.html" can always be found using "/index.html" regardless of the actual path on the server file system. The actual returned PATH uses a format similar to that of the computer or operating system where the servlet container is located, and contains the appropriate path separator. If the servlet container cannot be converted, null is returned. However, the returned values of ServletContext. getRealPath () often return different paths. For example, there are two files: exper1.txt, which are located at C: \ Tomcat 6.0 \ webapps \ ROOT and exper2.txt, at C: \ Tomcat 6.0 \ webapps, and at C: \ Tomcat 6.0 \ webapps \ ROOT write one. jsp file: ServletContext context = getServletContext (); context.getrealpath(+exper1.txt ") the result is C: \ Tomcat 6.0 \ webapps \ ROOT \ exper1.txt; context.getrealpath(+exper2.txt") and the result is C: \ Tomcat 6.0 \ webapps \ ROOT \ exper2.txt; context.getrealpath(+exper3.txt ") the result is still C: \ Tomcat 6.0 \ webapps \ ROOT \ exper3.txt but e Xper3 does not exist. This shows that the getRealPath () method has some problems. Application. getRealPath () usage and ServletContext. getRealPath () is basically the same. When you change the context in the previous example to application, the results are the same. It also has the same problem. 2. The request object is located in javax. servlet. http. httpServletRequest package, but the online information cannot be found in java API is displayed in J2EE API or Tomcat API. No verification is available yet, if you are interested, you can try it. 3. The above method returns the complete path of the project, including the drive letter and project name.