Deep understanding of relative and absolute paths

Source: Internet
Author: User

Absolute path: the absolute path is the real path of the file or directory on your home page on the hard disk (URL and physical path), for example:
C: XYZ est.txt represents the absolute path of the test.txt file. Http://www.sun.com/index.htmalso represents a urlabsolute volume.

Relative Path: the path relative to a base directory. Contains the relative path of the Web (relative directory in HTML), for example
In servlet, "/" indicates the directory of the Web application. The relative representation of the physical path. For example, "./" indicates the current directory, and "../" indicates the upper-level directory. This similar representation is also a relative path.
For more information about Uri, URL, and urn, see RFC standards.

RFC 2396: Uniform resource identifiers (URI): Generic syntax,
Http://www.ietf.org/rfc/rfc2396.txt)

2. About the relative paths and absolute paths in JSP/servlet.

2.1 server address

The relative address on the server is relative to the address of your web application. This address is parsed on the server (different from the relative address in HTML and JavaScript, they are parsed by the client browser) That means the relative address in JSP and Servlet should be relative to your web application, that is, relative to http: // 192.168.0.1/webapp.

Where it is used:
Forward: request in servlet. getrequestdispatcher (Address); this address is resolved on the server side. Therefore, you must forward it to. JSP should write this: request. getrequestdispatcher ("/user/. JSP ") the absolute address of this/relative to the current web application webapp is: http: // 192.168.0.1/webapp/user/. JSP. Sendredirect: <% response. sendredirect ("/rtccp/user/a. jsp") in JSP; %>

2.22 client address

The relative addresses of all HTML pages are relative to the server root directory (http: // 192.168.0.1/), rather than (the directory of the Web application under the same directory) http: // 192.168.0.1/webapp. The address of the Form Action attribute in HTML should be relative to the server root directory (http: // 192.168.0.1. JSP: Action = "/webapp/user/. JSP "or action =" <% = request. getcontextpath () %> "/user/. JSP;
Submitting to servlet is actiom = "/webapp/handleservlet" javascript is also parsed on the client, so its relative path is the same as the form.

Therefore, in general, it is best to add CSS, JavaScript, action, and other attributes referenced in JSP/html pages.
<% = Request. getcontextpath () %> to make sure all referenced files belong to the directory in the Web application. In addition, try to avoid using similar ". ",". /"," http://www.cnblogs.com/"and other similar relative paths relative to the file location, so that when the file moves, it is easy to problem.

3. Obtain the relative and absolute paths of the current application in JSP/servlet.

3.1 obtain the relative and absolute paths of the current application in JSP
Absolute path corresponding to the root directory: request. getrequesturi ()
Absolute path of the file: application. getrealpath (request. getrequesturi ());
Absolute path of the current web application: application. getrealpath ("/");
Obtain the upper-level directory of the request file: New file (application. getrealpath (request. getrequesturi (). getparent ()

3.2 obtain the relative and absolute paths of the current application in Servlet
Absolute path corresponding to the root directory: request. getservletpath ();
Absolute path of the file: request. getsession (). getservletcontext (). getrealpath
(Request. getrequesturi ())
Absolute path of the current web application: servletconfig. getservletcontext (). getrealpath ("/");
(The servletcontext object can be obtained in the following ways:
Javax. servlet. http. httpsession. getservletcontext ()
Javax. servlet. jsp. pagecontext. getservletcontext ()
Javax. servlet. servletconfig. getservletcontext ()
)

4. Methods for obtaining relative paths and absolute paths in Java class

4.1 obtain the absolute path in a separate Java class
According to the java. Io. File doc, we can see that:
By default, the directory represented by new file ("/") is system. getproperty ("user. dir ").
The program obtains the current path of the execution class.

Package org. Cheng. file;

Import java. Io. file;

Public class filetest {
Public static void main (string [] ARGs) throws exception {
System. Out. println (thread. currentthread (). getcontextclassloader (). getresource (""));

System. Out. println (filetest. Class. getclassloader (). getresource (""));

System. Out. println (classloader. getsystemresource (""));
System. Out. println (filetest. Class. getresource (""));
System. Out. println (filetest. Class. getresource ("/"));
// Path of the class file
System. Out. println (new file ("/"). getabsolutepath ());
System. Out. println (system. getproperty ("user. dir "));
}
}

4.2 The Java class on the server obtains the current path (from the Network)

(1). WebLogic

The webapplication System File root directory is the root directory where your WebLogic installation is located.
For example, if your WebLogic is installed in C: eaweblogic700 .....
The root path of your file is C :.
Therefore, you can access files on your server in two ways:
A. Use absolute path:
For example, put your parameter file in C: yourconfigyourconf. properties,
Use new fileinputstream ("yourconfig/yourconf. properties") directly ");
B. Use the relative path:
The root directory of the relative path is the root path of your webapplication, that is, the upper-level directory of the WEB-INF, put your parameter file

In yourwebappyourconfigyourconf. properties,
This method is used as follows:
New fileinputstream ("./yourconfig/yourconf. properties ");
You can select either of the two methods.

(2). Tomcat

Output System. getproperty ("user. dir") in the class; % atat_home %/bin

(3). Resin

It is not the relative path of your JSP, but the JSP Engine executes this JSP to compile it into a Servlet
For example, use the new file method to test file F = new file ("a.htm ");
This a.htm is in the resin installation directory.

(4). How to read relative paths?

In a Java file, either getresource or getresourceasstream can be used.

For example, getclass (). getresourceasstream (filepath); // filepath can be "/FILENAME", where/Represents the Web

Publish WEB-INF/classes under root path

By default, the path to this method is: WEB-INF/classes. It has been tested in Tomcat.

5. Read the relative path of the file to avoid hard encoding and absolute path usage. (From Network)
5.1 use the di mechanism of spring to obtain files and avoid hard coding.
Refer to the following connection content:
Http://www.javajia.net/viewtopic.php? P = 90213 &
5.2 read configuration files
Refer to the following connection content:
Http://dev.csdn.net/develop/article/39/39681.shtm

5.3 read an XML file through a virtual path or relative path to avoid hard Encoding

Refer to the following connection content:
Http://club.gamvan.com/club/clubPage.jsp? Ipage = 1 & tid = 10708 & CCID = 8

6. Common Operations on files in Java (copying, moving, deleting, creating, etc.) (from the Network)
Common Java File Operations
Http://www.easydone.cn/014/200604022353065155.htm

Java file operations (in JSP)
Http://www.pconline.com.cn/pcedu/empolder/gj/java/0502/559401.html

Java File Operations)
Http://www.51cto.com/html/2005/1108/10947.htm

Java: how to create, delete, modify, and copy directories and files
Http://www.gamvan.com/developer/java/2005/2/264.html

Summary:
By using the above content, you can find and copy files on the web application server, move files, search for files
Delete files and other operations, while the relative address of the server, the absolute address concept is clearer.
We recommend that you refer to the standard RFC document in Uri. At the same time, I have a thorough understanding of Java. Io. file. java.net. Uri. and other content
Other aspects of understanding can be more in-depth and thorough.

Process the obtained path

Java code

Public class application {

/**
* Todo: Get the root directory.
* @ Return
* @ Author <a href = "mailto: pheh.lin@gmail.com"> pheh </a> <br>
* Created on 15:16:21
*/
Public static string getrootpath (){
// Because the class name is "application", "application. Class" can be found
String result = application. Class. getresource ("application. Class"). tostring ();
Int Index = result. indexof ("WEB-INF ");
If (Index =-1 ){
Index = result. indexof ("bin ");
}
Result = result. substring (0, index );
If (result. startswith ("jar ")){
// When the class file is in the jar file, the returned path is "jar: file:/F :/...".
Result = result. substring (10 );
} Else if (result. startswith ("file ")){
// When the class file is in the class file, the returned path is "file:/F :/...".
Result = result. substring (6 );
}
If (result. endswith ("/") Result = result. substring (0, result. Length ()-1); // does not contain the final "/"
Return result;
}
}
Detailed analysis

First:
File F = new file (this. getclass (). getresource ("/"). getpath ());
System. Out. println (f );
Result:
C: \ Documents ents % 20and % 20settings \ Administrator \ workspace \ projectname \ bin
Obtain the project path of the current class;
If "/" is not added,
File F = new file (this. getclass (). getresource (""). getpath ());
System. Out. println (f );
Result:
C: \ Documents ents % 20and % 20settings \ Administrator \ workspace \ projectname \ bin \ com \ test
Obtain the absolute path of the current class;

Second:
File directory = new file (""); // The parameter is null.
String coursefile = directory. GetCanonicalPath ();
System. Out. println (coursefile );
Result:
C: \ Documents ents and Settings \ Administrator \ workspace \ projectname
Obtain the project path of the current class;

Third:
URL xmlpath = This. getclass (). getclassloader (). getresource ("selected.txt ");
System. Out. println (xmlpath );
Result:
File:/C:/Documents ents % 20and % 20 settings/Administrator/workspace/projectname/bin/selected.txt
Obtain the path of selected.txt in the srcdirectory of the current project

Fourth:
System. Out. println (system. getproperty ("user. dir "));
Result:
C: \ Documents ents and Settings \ Administrator \ workspace \ projectname
Get current project path

Category 5:
System. Out. println (system. getproperty ("Java. Class. Path "));
Result:
C: \ Documents ents and Settings \ Administrator \ workspace \ projectname \ bin
Get current project path

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.