JAVA gets the path to the current directory/servlet/class/file path/web path/url address

Source: Internet
Author: User
Tags rfc jboss

JAVA gets the path to the current directory/servlet/class/file path/web path/url address

It is unavoidable to get the path of the file when writing Java program ... Sum up, the omission of the time to fill up
1. You can do this in the Init method of the servlet
String path = Getservletcontext (). Getrealpath ("/");
This will get the full path of the Web project
Example: E:\eclipseM9\workspace\tree\
Tree is the root directory of my Web project

2. You can also call in any class at any time.
This.getclass (). getClassLoader (). GetResource ("/"). GetPath ();
This will get the full path to the classes directory
Example: e:\eclipsem9/workspace/tree/web-inf/classes/

This method can also not be used in the Web environment to determine the path, more useful

3.request.getcontextpath ();
Get the Web root context
such as/tree
Tree is the root context of my web project

/*jsp get the path to the current directory
Path=request.getrealpath ("");
/* Get Jbossweb Release temp directory warurl=.../tmp/deploy/tmp14544test-exp.war/
Path=c:\jboss-4.0.5.ga\server\default\tmp\deploy\tmp14544test-exp.war\

String path = (string) request.getcontextpath ();
/* Get the actual path where the project (test) is applied path=/test
String path = Request.getrequesturi ();
/* Get the real path where the app is located path=/test/admin/admindex.jsp

String Savepath=request.getrealpath (Request.getservletpath ());
/* Get the disk absolute path to the current file

JAVA gets the path to the current directory
File File=new file (".");
String Path=file.getabsolutepath ();
Path=file.getpath ();
/* Get JBoss Run directory path=c:\jboss-4.0.5.ga\bin\

---------------------------------------------

Java relative path/absolute path summary

Category: Data bar

Transferred from: http://www.javaeye.com/topic/117978

1. Understanding of Basic concepts

AbsolutelyPath: AbsolutelyPathis the file or directory on your home page on the hard drive realPath, (URL and physicalPathFor example
C:xyz Est.txt represents the absolute test.txt file.Path。 Http://www.sun.com/index.htm also represents a URL absolutePath

RelativePath: Relative to a base directoryPath。 Contains the relative webPath(relative directories in HTML), for example:
In a servlet, "/" represents a directory of Web apps. and physicalPathRelative representation of the. For example: "./" represents the current directory, ". /"represents the parent directory. This similar representation is also part of the relativePath
For additional information about Uri,url,urn, please refer to RFC documentation standards.

RFC 2396:uniform Resource Identifiers (URI): Generic Syntax,
(Http://www.ietf.org/rfc/rfc2396.txt)


2. About the relative path and absolute path in Jsp/servlet.

2.1 Server-side address

The server-side relative address refers to the address that is relative to your Web application, which is resolved on the server side (different from the relative addresses in HTML and JavaScript, which are made by the client Browser resolution) that is, the relative address 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:
Forward:servlet in Request.getrequestdispatcher (address); This address is parsed on the server side, so you need to forward to a. JSPIt should be written like this: Request.getrequestdispatcher ("/user/a. JSPThis/relative to the current Web application WebApp, its absolute address is: http://192.168.0.1/webapp/user/a. JSP。 Sendredirect: <%response.sendredirect in JSP ("/rtccp/user/a. JSP");%>

2.22, the address of the client

Relative addresses in all HTML pages are relative to the serverroot directory(HTTP://192.168.0.1/), not (with the directory of the Web app under the directory) http://192.168.0.1/webapp/. The address of the Action property of the form form in HTML should be relative to the serverroot directory(HTTP://192.168.0.1/), so, if submitted to a. JSPis: action= "/webapp/user/a. JSP"or action=" <%=request.getcontextpath ()%> "/user/a. JSP
Submitted to the servlet as actiom= "/webapp/handleservlet" JavaScript is also parsed on the client, so its relativePathThe same as the form form.


Therefore, in general, in the Jsp/html page and other references such as css,javascript.action attributes are best added
<%=request.getcontextpath ()%> To ensure that the referenced files belong to a directory in the Web App. In addition, you should try to avoid the use of similar ".", "./", "http://www.cnblogs.com/", etc. relative to the location of the filePath, so that when the file moves, it is prone to problems.


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

3.1 jsp to get the current application of the relativePathand absolutePath
Root directory
The corresponding absolutePath: Request.getrequesturi ()
The absolute filePath: Application.getrealpath (Request.getrequesturi ());
The current web app's absolutePath: Application.getrealpath ("/");
Gets the upper directory of the requested file: NewFile (Application.getrealpath (Request.getrequesturi ())). GetParent ()

3.2 servlet to get the current application relativePathand absolutePath
Root directory
The corresponding absolutePath: Request.getservletpath ();
The absolute filePath: Request.getsession (). Getservletcontext (). Getrealpath
(Request.getrequesturi ())
The current web app's absolutePath: Servletconfig.getservletcontext (). Getrealpath ("/");
(ServletContext objects are available in several ways:
Javax.servlet.http.HttpSession.getServletContext ()
Javax.servlet. JSP. Pagecontext.getservletcontext ()
Javax.servlet.ServletConfig.getServletContext ()
)

Method of obtaining relative path, absolute path in 4.java class

4.1 Separate Java classes to get absolutePath
According to Java.io.File's doc text, we know:
By default, the directory represented by new File ("/") is: System.getproperty ("User.dir").
The program obtains the execution class's currentPath

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 ("/"));
The class file is locatedPath
System.out.println (New File ("/"). GetAbsolutePath ());
System.out.println (System.getproperty ("User.dir"));
}
}

4.2 Java classes in the server get the currentPath(from the network)

(1). Weblogic

System files for WebApplicationroot directoryIt's your weblogic. Installation locationroot directory
For example: If your WebLogic is installed in c:beaweblogic700 .....
So, the root of your filePathis C:.
So there are two ways to get you to access your server-side files:
A. Use absolutePath
For example, put your parameter file in C:yourconfigyourconf.properties,
Direct use of the new FileInputStream ("Yourconfig/yourconf.properties");
B. Use relativePath
RelativePathOfroot directoryis the root of your webapplication.Path, which is the top-level directory of Web-inf, put your parameter file

In Yourwebappyourconfigyourconf.properties,
This is used:
New FileInputStream ("./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.

(3). Resin

Not the relative of your JSP putPathIs that the JSP engine executes this JSP and compiles it into a servlet.
OfPathAs the root. For example, the new file method is used to test for file F = new ("a.htm");
This a.htm is under the resin installation directory.

(4). How to read relativePathWhich?

In a Java file, getresource or getresourceasstream can be

Example: GetClass (). getResourceAsStream (FilePath);//filepath can be "/filename", here/on behalf of the Web

Publish RootPathNext web-inf/classes

This method is used by defaultPathYes: web-inf/classes. has been tested in Tomcat.

5. When reading a file, the relativePath, avoid hard coding and absolutePathThe use of. (from the network)
5.1 Use spring's di mechanism to get the file and avoid hard coding.
Refer to the following connection content:
http://www.javajia.net/viewtopic.php?p=90213&
5.2 Reading of configuration files
Refer to the following connection content:
Http://dev.csdn.net/develop/article/39/39681.shtm

5.3 Read an XML file from a virtual path or relative path, avoiding hard-coded

Refer to the following connection content:
Http://club.gamvan.com/club/clubPage. JSP? ipage=1&tid=10708&ccid=8

Common operations for files in 6.Java (copy, move, delete, create, etc.) (from the network)
Common Java File Operation classes
Http://www.easydone.cn/014/200604022353065155.htm

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

Java file operation details (Java Chinese network)
Http://www.51cto.com/html/2005/1108/10947.htm

JAVA How to create a delete modify copy directory and file
Http://www.gamvan.com/developer/java/2005/2/264.html

Summarize:
Through the use of the above content can be resolved on the Web application server side, move files, find files, copy
Delete files and other operations, while the relative address of the server, the concept of absolute address clearer.
Recommended reference URI, RFC standard text block. At the same time, Java.io.File. Java.net.URI and other content to understand thoroughly
Other aspects of the understanding can be more thorough and thorough.

This is the way to go to the root of the current project in Java

Java code

/**
* TODO Gets the currentProjectOfroot directory
* @author Pheh

* Created on 2006-12-30 17:15:41
*/
public class Application {

/**
* TODO Getroot directory
* @return
* @author Pheh

*created on 2007-5-10 15:16:21
*/
public static String Getrootpath () {
Because the class name is "Application", "Application.class" must be able to find
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, return the "jar:file:/f:/..." kind ofPath
result = Result.substring (10);
}else if (result.startswith ("file")) {
When the class file is in the class file, return the "file:/f:/..." kind ofPath
result = result.substring (6);
}
if (Result.endswith ("/")) result = Result.substring (0,result.length ()-1);//does not contain the last "/"
return result;
}
}

From:http://hi.baidu.com/89806/blog/item/086a08737525061f8601b019.html

JAVA gets the path to the current directory/servlet/class/file path/web path/url address

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.