Method of obtaining path based on Java file and web application
1. Understanding of basic concepts
`Absolute path `: the real path of the file or directory on your application on the hard disk, such as URL and physical path
For example:
c:/xyz/test. Txt stands for test Txt file absolute path;
http://www.sun.com/index.htm It also represents an absolute URL path;
`Relative path `: the path relative to a benchmark directory, including the relative path of the web (the relative directory in HTML).
For example:
In the servlet, "/" represents the root directory of the web application and the relative representation of the physical path.
For example:
". /" represents the current directory and ".. /" represents the parent directory. This similar representation also belongs to relative path.
2. About relative path and absolute path in JSP / servlet.
2.1 server address
`Server side relative address `: refers to the address relative to your web application. This address is resolved on the server side (different from the relative address in HTML and JavaScript, which is resolved by the client browser). That is, at this time, the corresponding address in JSP and servlet should be relative to your web application, that is, relative to http://192.168.0.1/webapp/ of
It is used in:
`Forward: request in servlet getRequestDispatcher(address);` This address is resolved on the server side, so if you want to forward to a.jsp, it should be written as follows:
`request. Getrequestdispatcher ("/ user / a.jsp") ` relative to the current web application webapp, its absolute address is: http://192.168.0.1/webapp/user/a.jsp 。
2.2 client address
`The relative addresses in all HTML pages are relative to the server root directory( http://192.168.0.1/ )Instead of (the directory of the web application under the root directory) http://192.168.0.1/webapp/ of
`The address of the action attribute of the form in HTML should be relative to the server root directory( http://192.168.0.1/ )Therefore, if the submitted to a.jsp is: action = "/ webapp / user / a.jsp" or action = "/ user / a.jsp", the submitted to servlet is action = "/ webapp / handleservlet".
JavaScript is also parsed on the client side, so its relative path is the same as that of the form.
Therefore, in general, it is better to add webapp application name in front of CSS, JavaScript, action and other attributes referenced by JSP / HTML pages to ensure that the referenced files belong to the directory in the web application.
In addition, try to avoid using similar ".", ". /", ".. /.. /" and other similar relative paths relative to the location of the file, which is easy to cause problems when the file is moved.
3. Obtain the relative path and absolute path of the current application in JSP / servlet
3.1 obtain the relative path and absolute path of the current application in JSP
Absolute path corresponding to root directory: ` request getRequestURI();`
Absolute path to file: ` application getRealPath(request.getRequestURI());`
Absolute path of current web application: ` application getRealPath("/");`
Get the upper directory of the request file: ` newfile (application. Getrealpath (request. Getrequesturi())) getParent();`
3.2 obtain the relative path and absolute path of the current application in the servlet
Absolute path corresponding to root directory: ` request getServletPath();`
Absolute path to file: ` request getSession(). getServletContext(). getRealPath();`
Absolute path of current web application: ` ServletConfig getServletContext(). getRealPath("/");`
ServletContext object can be obtained in several ways:
4. Method to obtain relative path and absolute path in Java class
4.1 obtaining absolute paths in separate Java classes
According to Java io. From the doc file of file, we can see that ` by default, the directory represented by newfile ("/") is system getProperty("user.dir");`。
The following program obtains the current path of the execution class:
4.2 the Java class in the server obtains the current path (from the network)
(1). Weblogic
The root directory of webapplication system files is the root directory where your Weblogic installation is located.
For example: if your Weblogic is installed in C: eaweblogic 700
Then, your file root path is C:
Therefore, there are two ways for you to access your server-side files:
a. Use absolute path:
For example, put your parameter file in C: yourconfig / yourconf properties,
Directly use newfileinputstream ("yourconfig / yourconf. Properties");
b. Use relative path:
The root directory of the relative path is the root path of your webapplication, that is, the upper directory of web-inf. put your parameter file in yourwebapp / yourconfig / yourconf properties,
Use this:
newFileInputStream("./yourconfig/yourconf.properties");
Either way, choose by yourself.
(2). Tomcat
Output system. In class getProperty("user.dir"); Showing% Tomcat_ Home%/bin
(4). How to read relative paths?
Either getresource or getresourceasstream can be in the java file
Example: ` getclass() getResourceAsStream(filePath);` // Filepath can be "/ filename", where / represents WEB-INF / classes under the web publishing root path
The default path to use this method is: WEB-INF / classes. Has been tested in Tomcat.
5. The relative path when reading the file to avoid the use of hard coding and absolute path.
5.1 use spring's Di mechanism to obtain files and avoid hard coding.
There are two kinds of paths used in Java: absolute path and relative path. Specifically, it can be divided into four types:
(1) Absolute resource path in URI form
For example: File: / D: / Java / eclipse 32 / workspace / jbpmtest3 / bin / AAA b
URLs are special cases of URIs. The prefix / protocol of the URL must be recognized by Java. A URL can open a resource, but a URI cannot.
URL and URI objects can be converted to each other. You can use their respective touri (), tourl () methods!
(2) Absolute path of the local system
D:/java/eclipse32/workspace/jbpmtest3/bin/aaa. b
Java. This form of parameter is required for classes in the IO package. However, they generally provide URI type parameters, and URI type parameters accept URI style strings. Therefore, through URI conversion, you can still use the URI style absolute path in Java Class in io package.
(3) Relative path relative to classpath
For example, the relative path to file: / D: / Java / eclipse 32 / workspace / jbpmtest3 / bin /. Where bin is the classpath of the project. All Java source files are compiled Copy the class file to this directory.
(4) Relative path relative to the current user directory
Is relative to system The path returned by getproperty ("user. Dir").
For general projects, this is the root path of the project. For a Java EE server, this may be a path to the server. There is no uniform standard for this!
Therefore, never use "relative path to current user directory".
However: by default, Java Classes in io packages always analyze relative pathnames based on the current user directory. This directory is controlled by the system property user Dir specifies, usually the calling directory of the Java virtual machine.
That is, when using Java It is best not to use relative paths when using classes in io packages. Otherwise, although it may be normal in J2SE applications, there will be problems in J2EE applications! And this path is different in different servers!
`Relative path best practice `: it is recommended to use a relative path relative to the current classpath. Therefore, when using a relative path, we should use a relative path relative to the current classpath.
`Getresource (string name), getresourceasstream (string name) and other methods of classloader class use the relative path relative to the classpath of the current project to find resources.
The same is true for getbundle (string path) of 'resourcebundle class' commonly used to read property files.
By looking at the source code of the classloader class and its related classes, it actually uses an absolute path in the form of URI. By obtaining the absolute path in the URI form of the current classpath, the absolute path in the URI form of the relative path is constructed. (this is actually a guess, because the JDK internally calls the source code of sun, which does not belong to the JDK and is not open source.)
`Relative paths are absolute paths in nature, so in the final analysis, Java can only use absolute paths to find resources. All the relative paths to find resources are just convenient methods. However, it is the API that helps us build the absolute path at the bottom to find the resources!
Here are some methods to get the classpath and the absolute path of the current class. You may need to use some of these methods to get the absolute path of the resources you need.
1. `FileTest. class. Getresource ("") ` 1: get the current class filetest The URI directory of the class file. Not myself!
For example: File: / D: / Java / eclipse 32 / workspace / jbpmtest3 / bin / COM / test/
2. `FileTest. class. Getresource ("/") `: get the absolute URI path of the current classpath.
For example: File: / D: / Java / eclipse 32 / workspace / jbpmtest3 / bin/
3. `Thread. currentThread(). getContextClassLoader(). Getresource (""): the obtained is also the absolute URI path of the current classpath.
For example: File: / D: / Java / eclipse 32 / workspace / jbpmtest3 / bin/
4. `FileTest. class. getClassLoader(). Getresource (""): the obtained is also the absolute URI path of the current classpath.
For example: File: / D: / Java / eclipse 32 / workspace / jbpmtest3 / bin/
5. `ClassLoader. Getsystemresource (""): the obtained is also the absolute URI path of the current classpath.
For example: File: / D: / Java / eclipse 32 / workspace / jbpmtest3 / bin/
`It is recommended to use `: thread currentThread(). getContextClassLoader(). Getresource ("") to get the URI representation of the absolute path of the current classpath.
Addressing resources in Web Applications
As mentioned above, the current user directory is relative to system The path returned by getproperty ("user. Dir"). For Java EE servers, this may be a path to the server. There is no unified specification for this! Not the root directory of our published web application! In this way, in a web application, we must not use a relative path relative to the current user directory.
In web applications, we usually use ` ServletContext The getrealpath ("/") ` method obtains the absolute path of the root directory of the web application. In this way, we only need to provide the path relative to the web application root directory to build the absolute path to locate the resource.
This is the general strategy we take when developing web applications.
General relative path solution
There are many relative paths in Java, which are not easy to use and are very error prone. Therefore, a convenient method is written to help solve the relative path problem more easily.
Resource addressing problems in web applications running with Java se
In Java se programs, we usually use classpath as the destination for storing resources. However, in web applications, we generally use WEB-INF and its subdirectories outside the classpath as the storage place of resource files.
In web applications, we usually use ServletContext The getrealpath ("/") method obtains the absolute path of the root directory of the web application. In this way, we only need to provide the path relative to the web application root directory to build the absolute path to locate the resource.
Web application, which can be published and run as a web application. However, we often run the main method of a class of a web application in the way of Java se. Alternatively, use JUnit to test. This needs to be run in the way of Java se.
In this way, we cannot use ServletContext The getrealpath ("/") method obtains the absolute path of the root directory of the web application.
For the classloader class provided by JDK, its getresource (string name), getresourceasstream (string name) and other methods use the relative path relative to the classpath of the current project to find resources.
The same is true for getbundle (string path) of resourcebundle class commonly used to read property files.
They can only use relative paths to read resources under the classpath, and cannot locate resources outside the classpath.
Problem reading configuration file outside classpath
For example, if we use the test driven development method to develop web applications using configuration files such as spring, hibernate and ibatis, we will encounter problems.
Although spring itself provides a file system (that is, relative to the user.dir directory) to read the web configuration file, it is not very convenient after all, and it is inconsistent with the code usage in the web program!
As for hibernate, ibatis is even more troublesome! Only move the configuration file to classpath, otherwise it is impossible to use test driven development!
What about this?
General relative path solution
To solve this problem, write a helper class' classloaderutil 'and provide a convenient method [public static URL getextendresource (string relativepath)]. In all Java programs such as web applications, when you need to locate resources outside the classpath, you use the convenient method of this helper class instead of the ServletContext unique to web applications Getrealpath ("/") method to locate the resource.
Use the absolute path of classpath to locate all resources
The implementation principle of this convenient method is to "use the absolute path of classpath to locate all resources".
The getresource ("") method of classloader class can get the absolute path of the current classpath, which is the ability of all Java programs and has the greatest adaptability!
The getresource (string relative path) method of the classloader class provided by the current JDK can only accept general relative paths. In this way, using the getresource (string relative path) method of the classloader class can only locate the resources under the classpath.
If it can accept parameters such as ".. /" and allows us to locate resources outside the classpath with relative paths, then we can locate resources in the location!
Of course, I can't modify this method of classloader class, so I wrote a helper class classloaderutil class and provided the method [public static URL getextendresource (string relativepath)]. It can accept the relative path with ".. /" symbol, and realize the function of freely looking for resources.
The above method to obtain the path based on java files and web applications is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.