Absolute and relative paths in Java JSP Servlet

Source: Internet
Author: User

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 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 ". ",". /",".. /.. /"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, 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.

**************************************** **************************************** *********************************

Here are some methods for obtaining the Java path on the Internet:

Note: If you start the program from ant, this. getclass (). getresource ("") is more strange, you can directly use the Java command line for debugging.

Obtain the absolute path of classpath and the current class.

To obtain a path other than classpath:

URL base = This. getclass (). getresource (""); // first obtain the location of the class, such as/home/Popeye/testjava/build/classes/NET/string Path = new file (base. getFile (),"...... /...... /...... /"+ Name). GetCanonicalPath (); // You Can Get/home/Popeye/testjava/name.

The following are some methods to obtain the absolute path of classpath and the current class. You may need to use some of these methods to obtain the absolute path of the resources you need.

1. filetest. Class. getresource ("")

The URI Directory of the current filetest. Class file is obtained. Not yourself!

For example, file:/D:/Java/eclipse32/workspace/jbpmtest3/bin/COM/test/

2. filetest. Class. getresource ("/")

Obtain the absolute URI path of the current classpath.

For example, file:/D:/Java/eclipse32/workspace/jbpmtest3/bin/

3. thread. currentthread (). getcontextclassloader (). getresource ("")

The obtained absolute URI path of the current classpath.

For example, file:/D:/Java/eclipse32/workspace/jbpmtest3/bin/

4. filetest. Class. getclassloader (). getresource ("")

The obtained absolute URI path of the current classpath.

For example, file:/D:/Java/eclipse32/workspace/jbpmtest3/bin/

5. classloader. getsystemresource ("")

The obtained absolute URI path of the current classpath.

For example, file:/D:/Java/eclipse32/workspace/jbpmtest3/bin/

We recommend that you use thread. currentthread (). getcontextclassloader (). getresource ("") to obtain the URI representation of the absolute path of the current classpath.

In Web applications, we generally use the servletcontext. getrealpath ("/") method to obtain the absolute path of the root directory of the Web application. In this way, we only need to provide the path relative to the root directory of the Web application program to build an absolute path to locate the resource.

Note:

1. Try not to use the relative path relative to the current user directory of system. getproperty ("user. dir. This is a time bomb, and you may be killed at any time.

2. Try to use absolute path resources in Uri format. It can easily be converted to Uri, URL, and file objects.

3. Try to use the relative path of the classpath. Do not use absolute paths. You can use the public static URL getextendresource (string relativepath) method of the classloaderutil class above to locate resources in all locations using the relative path relative to classpath.

4. Do not use hard-coded absolute paths. Because we can use the getresource ("") method of the classloader class to obtain the absolute path of the current classpath.

Using a hard-coded absolute path is completely unnecessary! It will make your death ugly! The program cannot be transplanted!

If you must specify an absolute path, it is much better to use the configuration file than hard encoding!

Of course, I recommend that you use the program to obtain the absolute path of classpath to spell the absolute path of resources. (T002)

 

Java uses relative paths to read files
1. In the Java project environment, use Java. Io to read files using relative paths. Example:
* Directory structure:
Decisiontree
| ___ SRC
| ___ Com. decisiontree. samplesreader. Java
| ___ Resource
| ___ Train.txt,test.txt
* Samplesreader. Java:
String filepath = "resource/train.txt"; // pay attention to the content of filepath;
File file = new file (filepath );
......
* Pay attention to the content of filepath. By default, java. Io is located under the current user directory ("user. dir"), that is, the project Root
Directory under "D: \ decisiontree". Therefore, the relative path (based on user. DIR) is "resource/train.txt"
. In this way, the JVM can obtain the complete path (absolute path) based on "user. dir" and "resource/train.txt ".
Path) "D: \ decisiontree \ resource \ train.txt", find the train.txt file.
* Note: the starting position of the relative path does not have a diagonal bar "/". For example:
Filepath = "resource/train.txt ";
Instead of filepath = "/resource/train.txt"; // error!


2. In the javaee environment, use classloader to read XML using relative paths:
* See the previous article "read an XML file through a virtual path or relative path to avoid hard encoding ".
* The content is as follows:
Java uses relative paths to read XML files:
I. xml files are generally stored in three locations:
1. Put it under the WEB-INF;
2. Put the XML file in the/WEB-INF/classes directory or the jar package of classpath;
3. Put it in the same package as the Java class to parse it, not necessarily classpath;
2. Two corresponding reading methods using relative paths:
Method 1: (not verified)
Put the XML file under the WEB-INF directory, and then
Program code:
Inputstream is = getservletcontext (). getresourceasstream ("/WEB-INF/xmlfile. xml ");
Method 2: Put the XML file in the/WEB-INF/classes directory or the jar package of classpath, you can use the static
Getsystemresourceasstream (string S;
Program code:
String s_xmlpath = "com/SPF/web/EXT/hotspot/hotspotxml/hotspot. xml ";
Inputstream in = classloader. getsystemresourceasstream (s_xmlpath );
Method 3: XML is stored in a random package path:
String s_xmlpath = "com/SPF/web/EXT/hotspot/hotspotxml/hotspot. xml ";
Classloader = hotspotxmlparser. Class. getclassloader ();
Inputstream in = classloader. getresourceasstream (s_xmlpath );

For Java programs, whether they are unpackaged or packaged jar or war files, sometimes they need to obtain the information of the directory where the program runs. How can this be done?
In the file system processed by Java, there are two directory Representation Methods:
(1) Absolute Directory, which starts with "/" and represents the given directory starting from the root directory, such as/C:/Java
(2) relative path. It is represented by a directory name without "/", indicating that the directory given by the current Java program is used as the starting directory. For example, Java/classes. In the relative path, some specific characters can represent special directories. For example, "." indicates the current directory, and "." indicates the upper-level directory of the current directory. In many examples provided on the Internet, "." is used as the directory name to construct an instance of the file object, and then the file object method is used to obtain the directory of the current program running.
This method is simple, but sometimes the running directory of the current program cannot be obtained correctly. The reason is that running a Java program does not have to enter the directory where the class file or jar file of the program is located, as long as the correct class path information is specified during runtime, you can run the Java program in any directory. In this case, you can only obtain the directory information of the command.
From the above analysis, we can see that many Java programs, especially web programs, cannot meet the requirements by using the "." notation of the current path. So how can we get the correct running directory information?
In web programs, Servlet APIs can be used to obtain some path information, such as the getrealpath method defined in the httpservletrequest interface. However, similar methods depend on the servlet environment and are not convenient for unit testing.
This article provides a path detection method that only uses Java standard APIs, that is, using the classloader abstract class.
Using java. lang. the getclassloader method of the class can obtain the classloader instance of the given class. Its getresource method can obtain the resource location in the current class loader, we can use the name of the class file as the resource to be searched. After processing, we can obtain the running location information of the current Java program. Its pseudocode is as follows:
Obtains the Class Name of the class parameter.
Obtain the package name of the class.
Convert package name to path
Use getresource to get the URL of the current class file
Use the URL to parse the path of the current Java program
The Code is as follows:

Java code
/**-----------------------------------------------------------------------
* Getapppath requires a class attribute parameter of the Java class used by the current program. It can return the packaged
* The Name Of The system directory where the Java executable file (jar, war) is located or the directory where the non-packaged Java program is located
* @ Param CLS: class type
* @ Return the returned value is the Java program running directory where the class is located.
-------------------------------------------------------------------------*/
Public static string getapppath (class CLs ){
// Check whether user-passed parameters are null
If (CLS = NULL)
Throw new java. Lang. illegalargumentexception ("the parameter cannot be blank! ");
Classloader loader = Cls. getclassloader ();
// Obtain the full name of the class, including the package name
String clsname = Cls. getname () + ". Class ";
// Obtain the package of the input parameter
Package pack = Cls. getpackage ();
String Path = "";
// If it is not an anonymous package, convert the package name to the path
If (pack! = NULL ){
String packname = pack. getname ();
// Check whether the SDK is a Java base class library to prevent users from passing in the built-in JDK class library.
If (packname. startswith ("Java.") | packname. startswith ("javax ."))
Throw new java. Lang. illegalargumentexception ("do not transmit the system class! ");
// Remove the package name from the class name to obtain the class file name
Clsname = clsname. substring (packname. Length () + 1 );
// Determine whether the package name is a simple package name. If yes, directly convert the package name to the path,
If (packname. indexof (".") <0) Path = packname + "/";
Else {// otherwise, the package name is converted to the path according to the package name components
Int start = 0, end = 0;
End = packname. indexof (".");
While (end! =-1 ){
Path = path + packname. substring (START, end) + "/";
Start = end + 1;
End = packname. indexof (".", start );
}
Path = path + packname. substring (start) + "/";
}
}
// Call the getresource method of classloader to pass in the class file name containing path information
Java.net. url = loader. getresource (path + clsname );
// Obtain the path information from the URL object
String realpath = URL. getpath ();
// Remove the protocol name "file:" From the path information :"
Int Pos = realpath. indexof ("file :");
If (Pos>-1) realpath = realpath. substring (Pos + 5 );
// Remove the last part of the path information that contains the class file information to obtain the path of the class.
Pos = realpath. indexof (path + clsname );
Realpath = realpath. substring (0, pos-1 );
// If the class file is packaged into a jar file, remove the corresponding jar and other packaging file names.
If (realpath. endswith ("! "))
Realpath = realpath. substring (0, realpath. lastindexof ("/"));
/*------------------------------------------------------------
The getresource method of classloader uses UTF-8 to encode the path information.
If there are Chinese characters and spaces in it, they are converted.
Here, the urldecoder's decode method is called for decoding to obtain the original
Chinese and space Path
-------------------------------------------------------------*/
Try {
Realpath = java.net. urldecoder. Decode (realpath, "UTF-8 ");
} Catch (exception e) {Throw new runtimeexception (E );}
Return realpath;
} // Getapppath definition ends
/-----------------------------------------------------------------

This method can be used for both jar or war files and non-jar files. Note the following two points:

Do not pass the system class as a parameter of getapppath, such as Java. lang. string. class, of course, do not pass those classes that are already in JDK, such as some classes related to XML.
To pass should be the main running class in the program, do not pass the class files in the program supporting class libraries, that is, the class files in the third-party class libraries, otherwise, the location of the class libraries will be obtained.

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.