1. Get the path in the java file
Thread.currentThread().getContextClassLoader().getResource("") //Get the path where the resource file (.class file) is located
ClassLoader.getSystemResource("")
Class_Name.class.getClassLoader().getResource("")
Class_Name.class .getResource("/")
Class_Name.class .getResource("") // Get the path where the current class is located
System.getProperty("user.dir") // Get the absolute path to the root directory of the project
System.getProperty("java.class.path") //Get the classpath and package path
The printouts are as follows:
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/com/xml/imp/
F:work_litaouri_test
F: work_litaouri_testWebContentWEB-INFclasses; F: work_litaouri_testWebContentWEB-INFlibdom4j.jar
2. Obtain the relative and absolute paths of the current application in JSP
The absolute path corresponding to the root directory: request.getRequestURI()
Absolute path to the file: application.getRealPath(request.getRequestURI());
The absolute path of the current web application: application.getRealPath("/");
Get the upper directory of the requested file: new File(application.getRealPath(request.getRequestURI())).getParent()
3. Obtain the relative and absolute paths of the current application in the servlet
The absolute path corresponding to the root directory: request.getServletPath();
Absolute path to the file: request.getSession().getServletContext().getRealPath(request.getRequestURI())
The absolute path of the current web application: servletConfig.getServletContext().getRealPath("/");
(ServletContext object is obtained in several ways:
javax.servlet.http.HttpSession.getServletContext()
javax.servlet.jsp.PageContext.getServletContext()
javax.servlet.ServletConfig.getServletContext()
)
The above is the entire content of this article, I hope you like it.
Please take some time to share the article with your friends or leave a comment. We will sincerely thank you for your support!