Full path acquisition by JavaEE and full path acquisition by javaee

Source: Internet
Author: User

Full path acquisition by JavaEE and full path acquisition by javaee

This blog is a comprehensive summary of how the Java Web Application Server obtains file paths in different environments.

The main application scenario after obtaining the file path is to read the custom configuration file of JavaWeb and generate various types of files in a specific path for download ......

Check whether the above directory can solve your problem. If so, click the corresponding section. If there is no speed to close it, check the next record listed by the search engine.

1. obtain from the init method of Servlet
getServletContext().getRealPath("/");

Output: E: \ workspace \ tree \ (tree is the root directory of my web project)

2. Obtain from any class
this.getClass().getClassLoader().getResource("/").getPath();Thread.currentThread().getContextClassLoader().getResource("/").getPath();

Output: E: \ workspace \ tree \ WEB-INF \ classes \

3. Get it from HttpServletRequest
request.getServletContext().getRealPath("/");

Output: E: \ Workspaces \ tree \ WebContent \

4. JSP obtains the path of the current directory
request.getRealPath("");

Get the jbossWEB release temporary directory warUrl =.../tmp/deploy/tmp14544test-exp.war/
Path = C: \ jboss-4.0.5.GA \ server \ default \ tmp \ deploy \ tmp14544test-exp.war \

(String)request.getContextPath();

Obtain the real path of the project (test) application. path =/test

request.getRequestURI();

Obtain the actual path of the application. path =/test/admin/admindex. jsp

request.getRealPath(request.getServletPath());

Obtain the absolute disk path of the current file.

new File(".").getAbsolutePath(); 
new File(".").getPath();
new File(application.getRealPath(request.getRequestURI())).getParent()

Get the jboss running directory path = C: \ jboss-4.0.5.GA \ bin \

5. server address [view the client on the server side]

The relative address of the server is relative to the address of your web application. This address is parsed on the server side (different from the relative addresses in html and javascript, they are parsed by the client browser)

That is to say, the relative address in jsp and servlet should be relative to your web application, that is, relative to http: // 192.168.0.1/webapp.

Eg:
Forward: request. getRequestDispatcher (address) in servlet; this address is resolved on the server side.

You need to forward to a. jsp, which should be written as follows: request. getRequestDispatcher ("/user/a. jsp ")

The absolute address of this/relative to the current web application webapp is: http: // 192.168.0.1/webapp/user/a. jsp.

SendRedirect: <% response. sendRedirect ("/rtccp/user/a. jsp") in jsp; %>

6. Client Address [client view server side]

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 is relative to the server root directory (http: // 192.168.0.1.

If it is submitted to. 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.

7. Obtain the relative and absolute paths of the current application in Servlet.

A. the absolute path corresponding to the root directory: request. getServletPath ();

B. absolute path of the file: request. getSession (). getServletContext (). getRealPath (request. getRequestURI ())

C. The absolute path of the current web application: servletConfig. getServletContext (). getRealPath ("/");

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

D. method for obtaining relative paths and absolute paths in Java Class

According to the java. io. File Doc, we can see that by default, new File ("/") represents the directory System. getProperty ("user. dir ").

        System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));        System.out.println(Test.class.getClassLoader().getResource(""));        System.out.println(ClassLoader.getSystemResource(""));        System.out.println(Test.class.getResource(""));        System.out.println(Test.class.getResource("/"));        System.out.println(new File("/").getAbsolutePath());        System.out.println(System.getProperty("user.dir"));
8. The Java class in the Web server obtains the current path

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

The root path of your file is c:

Therefore, you can access files on your server in two ways.

Use absolute path: for example, place your parameter file in c: yourconfigyourconf. properties.

new FileInputStream("yourconfig/yourconf.properties");

Use 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,

new FileInputStream("./yourconfig/yourconf.properties");

B. Tomcat

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

C. 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 ");

This a.htm is in the resin installation directory.

Java to get the root directory of the current project

// 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, "jar: file:/F:/..." is returned :/... "Sample Path result = result. substring (10);} else if (result. startsWith ("file "))... {// when the class file is in the class file, "file:/F:/..." is returned :/... "Sample Path result = result. substring (6);} if (result. endsWith ("/") result = result. substring (0, result. length ()-1); // does not contain the last "/" return result;
9. JavaScript to get the project root directory
// Js obtain the project root path, such as http: // localhost: 8083/uimcardprjfunction getRootPath () {// obtain the current URL, such as http: // localhost: 8083/uimcardprj/share/meun. jsp var curwwwpathpattern contains invalid Doc ument. location. href; // The directory after obtaining the host address, for example, uimcardprj/share/meun. jsp var pathname=w.doc ument. location. pathname; var pos = curWwwPath. indexOf (pathName); // obtain the host address, for example, http: // localhost: 8083 var localhostPaht = curWwwPath. substring (0, pos); // obtain the project name with "/", for example,/uimcardprj var projectName = pathName. substring (0, pathName. substr (1 ). indexOf ('/') + 1); return (localhostPaht + projectName );}
10. Understanding of ClassLoader

GetClassLoader () is used in any class: The Class Loader that obtains the class object, and the understanding of classLoader is continuously established after being contacted in subsequent work.

The process of loading classes is very simple: Find the Class location, and load the byte code of the found Java Class into the memory to generate the corresponding Class object.

Java classloaders are used to implement such a process. JVM does not have more than one classloader. In fact, if you want to, you can make the JVM have countless classloaders.

The Class Loader itself is also a class, and it also needs to be loaded into the memory. So who will load these class loaders will have a root?

Such a root exists. It is the Bootstrap ClassLoader that never comes to the fore. Why does it mean that it never ends?

Because you cannot catch even a little bit of its tail in Java code,

Although you can always understand its existence, because all the class libraries required by the java Runtime Environment are loaded by it, and it is a program written in C ++, it can run independently. It can be said that it is the starting point of JVM running. trembling, cool!

After Bootstrap completes its task, it will generate an AppClassLoader (in fact, the system will also use the extended Class Loader ExtClassLoader, which is used to load classes in the Java Runtime Environment extension package ).

This class loader is frequently used and can be obtained by calling ClassLoader. getSystemClassLoader.

We assume that the program does not use the class loader-related operation settings or customize the new class loader, then all the java classes we write will be loaded by it. It is worthy of respect.

The area of the AppClassLoader search class is the familiar Classpath, which must be crossed by beginners. Is there any flashing sensation? Let's name it the class path Class Loader according to its class search range.

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.