Get path and Web application get path method in Java file

Source: Internet
Author: User

Original address: Http://my.oschina.net/xianggao/blog/85172?fromerr=WnWLB6aV

1. Understanding of Basic Concepts

' Absolute path ': The real path on the hard disk where you apply the file or directory, such as: URL, physical path

For example:

C:/xyz/test.txt represents the absolute path of the Test.txt file;

Http://www.sun.com/index.htm also represents a URL absolute path;

' Relative path ': The path relative to a base directory, containing the relative path to the web (relative to the directory in HTML).

For example:

In the servlet, "/" represents the root directory of the Web app, and the relative representation of the physical path.

For example:

"./" represents the current directory, ".. /"represents the parent directory. This similar representation also belongs to the relative path.

2. About the relative path and absolute path in Jsp/servlet. 2.1 Server-side address

' Server-side relative address ': refers to the address of your Web application, which is resolved on the server side (different from the relative address in HTML and JavaScript). They are parsed by the client browser) in other words, the relative addresses in the JSP and servlet should be relative to your Web application, that is, relative to http://192.168.0.1/webapp/.

Where they are used are:

' Request.getrequestdispatcher in Forward:servlet, ' This address is parsed on the server side, so you forward to a.jsp should write:

' Request.getrequestdispatcher ("/user/a.jsp") this/relative to the current Web application WebApp, its absolute address is: http://192.168.0.1/webapp/user/a.jsp.

2.2 Address of the client

The relative addresses in all HTML pages are relative to the server root (HTTP://192.168.0.1/), not (the directory of the Web app under the root directory) http://192.168.0.1/webapp/.

' The address of the Action property of the form form in HTML ' should be relative to the server root (HTTP://192.168.0.1/), so if committed to a.jsp: action= "/webapp/user/a.jsp" or action = "/user/a.jsp", submitted to servlet as action= "/webapp/handleservlet".

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

Therefore, in general, it is best to add the WebApp app name before attributes such as css,javascript,action such as jsp/html pages, to ensure that the referenced files belong to the directory in the Web App.

In addition, you should try to avoid the use of similar ".", "./", ". /.. /"Similar relative path relative to the location of the file, so that when the file is moved, it is prone to problems.

3. Get the relative and absolute paths of the current application in Jsp/servlet obtaining the relative and absolute paths of the current application in the 3.1 JSP

Absolute path to the root directory: ' Request.getrequesturi (); '

Absolute path to file: ' Application.getrealpath (Request.getrequesturi ()); '

Absolute path to the current web app: ' Application.getrealpath ("/"); '

Get the upper directory of the requested file: ' NewFile (Application.getrealpath (Request.getrequesturi ())). GetParent ();

obtaining the relative and absolute paths of the current application in the 3.2 servlet

Absolute path to the root directory: ' Request.getservletpath (); '

Absolute path to file: ' Request.getsession (). Getservletcontext (). Getrealpath (); '

Absolute path to the current web app: ' Servletconfig.getservletcontext (). Getrealpath ("/"); '

ServletContext objects are available in several ways:

Javax.servlet.http.HttpSession.getServletContext () Javax.servlet.jsp.PageContext.getServletContext () Javax.servlet.ServletConfig.getServletContext ()

4. Method of obtaining relative path, absolute path in Java class 4.1 Obtaining an absolute path in a separate Java class

According to Java.io.File's doc, we know: ' By default NewFile ("/") represents the directory: System.getproperty ("User.dir"); '.

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

 PackageOrg.cheng.file;ImportJava.io.File; Public classfiletest{ Public Static voidMain (String[]args)throwsexception{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 ("/"));//The path of the class fileSystem.out.println (NewFile ("/"). GetAbsolutePath ()); System.out.println (System.getproperty ("User.dir")); } }

4.2 Java classes in the server get 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 .....

So, your file root path is C:.

So there are two ways to get you to access your server-side files:

A. Using an absolute path:

For example, put your parameter file in C:yourconfig/yourconf.properties,

Direct use of Newfileinputstream ("yourconfig/yourconf.properties");

B. Using relative paths:

The root of the relative path is the root path of your webapplication, which is the top level directory of Web-inf, placing your parameter file in Yourwebapp/yourconfig/yourconf.properties,

This is used:

Newfileinputstream ("./yourconfig/yourconf.properties");

Both of these methods can be chosen by themselves.

(2). Tomcat

Output System.getproperty ("User.dir") in the class;%tomcat_home%/bin is displayed.

(4). How to read the relative path?

In a Java file, getresource or getresourceasstream can be

Example: ' GetClass (). getResourceAsStream (FilePath); '//FilePath can be '/filename ', here/on behalf of the Web publishing root path web-inf/classes

The default path for using this method is: web-inf/classes. has been tested in Tomcat.

5. Relative path when reading files, avoid hard coding and absolute path use. 5.1 Use spring's di mechanism to get the file and avoid hard coding.

There are two types of paths used in Java: absolute paths and relative paths. In particular, it is divided into four types:

(1) absolute resource path in URI form

such as: file:/d:/java/eclipse32/workspace/jbpmtest3/bin/aaa.b

A URL is a special case of a URI. The prefix/protocol of the URL must be Java-aware. URLs can open resources, but URIs do not.

URL and Uri objects can be converted to each other, using their respective touri (), Tourl () Method!

(2) Absolute path of the Local system

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

Java.io the class in the package, you need to use this form of argument. However, they generally also provide a URI-type parameter, and a URI-type parameter that accepts a URI-style string. Therefore, by URI conversion, you can still use the absolute path of the URI style in the class in the Java.io package.

(3) Relative path to Classpath

such as: relative to the path of the file:/d:/java/eclipse32/workspace/jbpmtest3/bin/relative path. Among them, bin is the classpath of this project. All Java source files are copied into this directory after the compiled. class file.

(4) Relative path to the current user directory

Is the path returned relative to System.getproperty ("User.dir").

For a generic project, this is the root path of the project. For Java EE servers, this could be a path to the server. This does not have a uniform norm!

Therefore, never use a relative path to the current user directory.

However: By default, the classes in the Java.io package always parse relative path names based on the current user directory. This directory is specified by the system property User.dir, which is usually the calling directory for 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 in the J2SE application may be normal, but to the Java EE program, there will be a problem! And this path, in different servers are different!

' Relative Path best practices ': It is recommended to use relative paths to the current classpath, so when we use relative paths, we should use relative paths versus the current classpath.

The ' ClassLoader class ' GetResource (string name), getResourceAsStream (string name), and so on, uses the relative path to the classpath of the current project to find the resource.

The same is true of the ' ResourceBundle class ' Getbundle (String path) that is commonly used to read the properties file.

By looking at the source code of the ClassLoader class and its related classes, it actually uses an absolute path in the form of a URI. The absolute path of the URI form of the relative path is constructed by obtaining the absolute path of the URI form of the current classpath. (This is actually a conjecture, because the JDK internally invokes Sun's source code, which is not part of the JDK, not open source.) )

The ' relative path is essentially an absolute path ', so in the final analysis, Java can essentially use absolute paths to find resources. All the relative paths to find resources are just a few convenient ways. It's just the API that helps us build an absolute path to find resources!

Here are some ways to get the absolute path of classpath and 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 (") ': Gets the URI directory of the current class Filetest.class file. Don't include yourself!

such as: file:/d:/java/eclipse32/workspace/jbpmtest3/bin/com/test/

2. ' FileTest.class.getResource ("/") ': Gets the absolute URI path of the current classpath.

such as: file:/d:/java/eclipse32/workspace/jbpmtest3/bin/

3. ' Thread.CurrentThread (). Getcontextclassloader (). GetResource (""): the resulting absolute URI path is also the current classpath.

such as: file:/d:/java/eclipse32/workspace/jbpmtest3/bin/

4. ' FileTest.class.getClassLoader (). GetResource ("") ': The obtained is also the absolute URI path of the current classpath.

such as: file:/d:/java/eclipse32/workspace/jbpmtest3/bin/

5. ' Classloader.getsystemresource (") ': The obtained is also the absolute URI path of the current classpath.

such as: file:/d:/java/eclipse32/workspace/jbpmtest3/bin/

' Recommended ': Thread.CurrentThread (). Getcontextclassloader (). GetResource ("") to get the URI representation of the absolute path of the current classpath.

Addressing resources in a Web application

As stated above, the current user directory, which is the path returned relative to System.getproperty ("User.dir"). For Java EE server, this may be a server path, this does not have a unified specification! Instead of the root directory of the Web application we publish! In this way, in a Web application, we absolutely cannot use relative paths to the current user directory.

In a Web application, we typically get the absolute path to the root of the Web application through the ' Servletcontext.getrealpath ('/') ' method. This way, we only need to provide a path relative to the root of the Web application to build the absolute path to the location resource.

This is the strategy we generally take when developing Web applications.

Common approach to relative paths

There are a lot of relative paths in Java that are not easy to use and very error prone. Therefore, a convenient method has been written to help solve relative path problems more easily.

Resource addressing issues with javase running in Web applications

In the Javase program, we generally use classpath as the destination for storing resources. However, in a Web application, we generally use web-inf and its subdirectories outside of Classpath as the repository for resource files.

In a Web application, we generally get the absolute path to the root of the Web application through the Servletcontext.getrealpath ("/") method. This way, we only need to provide a path relative to the root of the Web application to build the absolute path to the location resource.

Web application that can be published and run as a Web application. However, we also often run the main method of a class for a Web application in a javase way. Or, use JUnit testing. This needs to be run using the Javase method.

This way, we cannot use the Servletcontext.getrealpath ("/") method to get the absolute path of the Web application's root directory.

The JDK provides the ClassLoader class, its getresource (string name), getResourceAsStream (string name), and other methods that use relative paths to the classpath of the current project to find resources.

The same is true of the Getbundle (String path) of the ResourceBundle class that is commonly used to read property files.

They can only use relative paths to read resources under Classpath and cannot navigate to resources outside of Classpath.

Classpath external configuration file read problem

For example, we use test-driven development methods to develop Web applications that use configuration files such as spring, Hibernate, Ibatis, and so on, and encounter problems.

Although spring itself provides a way to read the Web configuration file filesystem (that is, relative to the User.dir directory), it is not very convenient at all. and inconsistent with the way code is used in Web programs!

As for Hibernate,ibatis, it's even more troublesome! It is impossible to use test-driven development unless you move the configuration file to Classpath!

What about this?

Common approach to relative paths

In the face of this problem, write an assistant class ' Classloaderutil ', which provides a convenient method [public static URL Getextendresource (String relativepath)]. In all Java programs, such as Web applications, when you need to locate resources outside of classpath, you use the convenience of this helper class instead of using the Web application-specific Servletcontext.getrealpath ("/") method to locate resources.

Use the absolute path of classpath to locate all resources

The principle of this convenient method is to "use the absolute path of classpath to locate all resources".

The GetResource ("") Method of the ClassLoader class is able to get the absolute path of the current classpath, which is the ability of all Java programs to have the greatest adaptability!

The current JDK provides a getresource (String relative path) method of the ClassLoader class, which can only accept generic relative paths. This way, the getresource (String relative path) method of the ClassLoader class can only be used to locate resources under CLASSPATH.

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

Of course, I can't modify this method of the ClassLoader class, so I wrote an assistant class Classloaderutil class that provides the [public static URL Getextendresource (String relativepath )] This method. It can be accepted with the ".. /"The relative path of the symbol, which realizes the function of free looking for resources.

Get path and Web application get path method in Java file

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.