JAVA file paths and WEB application paths

Source: Internet
Author: User

JAVA file paths and WEB application paths

 

1. understanding of basic concepts

'Absolute path': the true path of the file or directory on your application on the hard disk, such as URL and physical path.

For example:

C:/xyz/test.txtrepresents 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, including the relative path of the Web (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:

./Indicates the current directory, and ../indicates the upper-level directory. This similar representation is also a relative path.

 

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

 

2.1 server address

'Relative address on the server ': refers to the address relative to your web application. This address is parsed on the server side (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: the request. getRequestDispatcher (address); 'in the servlet is resolved on the server side. Therefore, you need to write forward the address to a. jsp as follows:

'Request. getRequestDispatcher ("/user/. jsp ") 'relative to the current web application webapp, the absolute address is: http: // 192.168.0.1/webapp/user/. jsp.

 

2.2 client address

'Relative addresses in 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 root directory) http: // 192.168.0.1/webapp.

'Address of the action attribute of form in Html 'should be relative to the server root directory (http: // 192.168.0.1. jsp: action =/webapp/user/. jsp or action =/user/. jsp, submit to servlet as action =/webapp/handleservlet.

Javascript is also parsed on the client, so its relative path is the same as the form.

Therefore, it is recommended that you add the webapp name before the CSS, Javascript, and Action attributes referenced by JSP/HTML pages, to ensure that all referenced files belong to the Web application directory.

In addition, try to avoid using relative paths similar to...,./,.../and so on 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: 'newfile (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 ();'

Absolute path of the current web application: 'servletconfig. getServletContext (). getRealPath (/);'

ServletContext objects can be obtained in the following ways:

 

?

123 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, newFile (/) represents the Directory: System. getProperty (user. dir );'.

The following program obtains the current path of the execution class:

?

12345678910111213 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(newFile(/).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: yourconfig/yourconf. properties,

Use newFileInputStream (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 yourwebapp/yourconfig/yourconf. properties,

This method is used as follows:

NewFileInputStream (./yourconfig/yourconf. properties );

You can select either of the two methods.

(2). Tomcat

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

(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-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.

 

 

The paths used in Java are divided into absolute paths and relative paths. Specifically, there are four types:

(1) absolute resource path in URI form

For example, file:/D:/java/eclipse32/workspace/jbpmtest3/bin/aaa. B

URL is a special case of URI. The URL prefix/protocol must be known by Java. The URL can open resources, but the URI cannot.

The URL and URI objects can be converted to each other. Use the respective toURI () and toURL () methods!

(2) absolute path of the Local System

D:/java/eclipse32/workspace/jbpmtest3/bin/aaa. B

This parameter is required for classes in the Java. io package. However, they generally provide URI-type parameters, while URI-type parameters accept URI-style strings. Therefore, the absolute path of the URI style can be used in the class in the java. io package through URI conversion.

(3) Relative Path to classpath

For example, the relative path relative to file:/D:/java/eclipse32/workspace/jbpmtest3/bin. Bin is the classpath of the project. All the. class files compiled from the Java source file are copied to this directory.

(4) Relative Path to the current user directory

Is relative to the path returned by System. getProperty (user. dir.

For general projects, this is the root path of the project. For a JavaEE server, this may be a path of the server. There is no unified specification!

Therefore, do not use the relative path relative to the current user directory ".

However: by default, classes in the java. io package always analyze relative path names based on the current user directory. This directory is specified by the system property user. dir, which is usually the call Directory of the Java Virtual Machine.

This means that when using classes in the java. io package, it is best not to use relative paths. Otherwise, although it may still be normal in the J2SE application, problems may occur in the J2EE program! The path is different on different servers!

 

'Relative path best practices ': relative paths relative to the current classpath are recommended. Therefore, when using relative paths, we should use relative paths relative to the current classpath.

'Getresource (String name), getResourceAsStream (String name), and other methods of the 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 the 'resourcebundle class, which is commonly used to read attribute files.

 

By viewing the source code of the ClassLoader class and its related classes, it actually uses an absolute path in the URI form. Obtain the absolute path in the URI form of the current classpath, and construct the absolute path in the URI form of the relative path. (This is actually a conjecture, because the JDK calls SUN's source code internally, and the Code does not belong to JDK, not open source .)

 

'Relative paths are essentially absolute path'. Therefore, in the final analysis, Java can only use absolute paths to find resources. All relative paths are just some convenient methods to find resources. However, the API helps us build an absolute path at the underlying level to find resources!

 

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 () ': Obtain the URI Directory of the current FileTest. class file. 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 () ': Obtain the absolute URI path of the current ClassPath.

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

4. 'filetest. class. getClassLoader (). getResource () ': Obtain the absolute URI path of the current ClassPath.

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

5. 'classloader. getSystemResource () ': Obtain the absolute URI path of the current ClassPath.

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

 

'Use ': Thread. currentThread (). getContextClassLoader (). getResource () to obtain 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 the path returned by System. getProperty (user. dir. For the JavaEE server, this may be a path of the server. There is no uniform specification! Instead of the root directory of the Web application we released! In this way, in Web applications, we absolutely cannot use relative paths relative to the current user directory.

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.

This is a general strategy we adopt when developing Web applications.

 

General Relative Path Solution

There are many relative paths in Java, which are not easy to use and error-prone. Therefore, we have compiled a convenient method to help solve relative path problems more easily.

Addressing of resources running using JavaSE in Web Applications

In the JavaSE program, we generally use classpath as the destination for storing resources. However, in Web applications, we generally use the WEB-INF and its subdirectories outside classpath as the storage location of resource files.

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.

Web applications can be published and run as Web applications. However, we often use JavaSE to run the main method of a class of a Web application. Alternatively, use JUnit for testing. This requires the JavaSE method.

In this way, we cannot use the ServletContext. getRealPath (/) method to obtain the absolute path of the root directory of the Web application.

The ClassLoader class provided by JDK, its getResource (String name), getResourceAsStream (String name) and other methods, uses the relative path relative to the classpath of the current project to find resources.

This is also true for getBundle (String path) of the ResourceBundle class that is commonly used to read attribute files.

They can only use relative paths to read resources under classpath and cannot locate resources outside classpath.

 

Reading configuration files 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 provides FileSystem (relative to the user. dir directory) to read Web configuration files, it is not very convenient. It is inconsistent with the code usage in Web programs!

As for Hibernate, iBatis is more troublesome! You only need to move the configuration file to classpath. Otherwise, it is impossible to use the test driver for development!

 

What should I do?

General Relative Path Solution

To solve this problem, write a helper class 'classloaderutil' to 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 classpath, use the convenient method of this helper class instead of using the ServletContext that is 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 the ClassLoader class can obtain the absolute path of the current classpath. This is the capability of all Java programs and has the greatest adaptability!

Currently, the getResource (String relative path) method of the ClassLoader class provided by JDK can only accept general relative paths. In this way, you can only locate resources under classpath by using the getResource (String relative path) method of the ClassLoader class.

If it can accept parameters such as "../" and allow us to use relative paths to locate resources outside the classpath, then we can locate the resources in the location!

Of course, I cannot modify this method of the ClassLoader class, so I wrote a helper class ClassLoaderUtil class that provides the [public static URL getExtendResource (String relativePath)] method. It can accept the relative path with the "../" symbol, realizing the function of freely searching for resources.

 


 

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.