Java-relative path/absolute path

Source: Internet
Author: User
Tags rfc

1. understanding of basic concepts
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 test.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.2 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, CSS and JavaScript referenced on JSP/html pages. it is best to add <% = request. getcontextpath () %> to ensure that all 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 file location, so that when the file is moved, it is easy to cause problems.

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, new file ("/") represents the directory system. getproperty ("user. dir ").
The following program obtains the current path of the execution class

 

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
(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: beaweblogic700...... your file root path is C :.
Therefore, you can access files on your server in two ways:
A. Use absolute path:
For example, place your parameter file in C: yourconfigyourconf. properties and directly use new fileinputstream ("yourconfig/yourconf. properties ");
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. It is the root path for the JSP Engine to compile the JSP into a servlet. for example, use the new file method to test file F = new file ("a.htm" zookeeper. 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.
Example: getclass (). getresourceasstream (filepath); // filepath can be "/FILENAME", here/Represents the WEB-INF/classes under the web publishing 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.
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 perform operations on the Web application server, such as moving files, searching for files, copying and deleting files, and the relative address of the server. The concept of absolute address is clearer.
We recommend that you refer to the standard RFC document in Uri. At the same time, you can have a thorough understanding of Java. Io. file. java.net. Uri. and other content.

Add a little bit
A. Request. getservletpath () Looks like different middleware providers have different implementations. We have encountered inconsistent cases in Weblogic and tomcat before.
B. Operating System
Java code
Classloader. getsystemresource ("")
Classloader. getsystemresource ("")
This method has different performance in different operating systems.
Therefore, note the following about path operations: test the target deployment environment and operating system environment.

Pheh 2007-08-30
This is the method that I often use to go to the root directory of the current project in Java.
Java code

 

/***//**
* Todo obtains the root directory of the current project.
* @ Author <a href = "mailto: pheh.lin@gmail.com"> pheh </a> <br>
* Created on 2006-12-30 17:15:41
*/
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;
}
}
Related Article

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.