Access to various paths in JAVA Web projects

Source: Internet
Author: User

access to various paths in JAVA Web projectsTags: java webpath file path2014-02-14 15:04 1746 people read comments (0) favorite reports Classification:Java Development ($)1. You can do this in the Init method of the servletString path = Getservletcontext (). Getrealpath ("/"); This gets the full path of the Web project for 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 gets the full path to the classes directory for 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 environment like/tree Www.2cto.comtree is the root of my Web project context/*jsp get the path Path=request.getrealpath ("") of the current directory;/* 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 ();/* Gets the real path to the project (test) application path=/test String Path = Request.getrequesturi ();/* Get the actual path where the application resides path=/test/admin/admindex.jspstring Savepath=request.getrealpath ( Request.getservletpath ());/* Gets the disk absolute path of the current file//java gets the path to the current directory, file File=new file ("."); String Path=file.getabsolutepath ();p ath=file.getpath ();/* Get JBoss Run directory path=c:\jboss-4.0.5.ga\bin\

Java relative path/absolute path summary1. The basic concept of Understanding absolute path: Absolute path is the real path on the hard disk of the file or directory on your home page, (URL and physical path) For example: C:xyz est.txt represents the absolute path of the Test.txt file. The http://www.sun.com/index.htm also represents a URL absolute path. Relative path: The path relative to a base directory. Contains the relative path to the web (relative to the directory in HTML), for example: In a servlet, "/" represents a directory of Web apps. 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. 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 server-side relative address refers to the address of your Web application, this address is resolved on the server side (different from HTML and JavaScript relative address, they are resolved by the client   browser) that is, this time in the   The relative addresses in the JSP and servlet should be relative to your web app, which is relative to http://192.168.0.1/webapp/. Where it is used: request.getrequestdispatcher (address) in Forward:servlet; This address is parsed on the server side, so You want to 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. Sendredirect: <%response.sendredirect ("/rtccp/user/a.jsp") in the JSP; the relative addresses in all HTML pages of the%>2.22 and client addresses are relative to the server root directory ( HTTP://192.168.0.1/), instead of (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 server root directory (HTTP://192.168.0.1/), so if committed to a.jsp: action= "/webapp/user/a.jsp" or action= " <%=request.getcontextpath ()% > "/user/a.jsp; submit to servlet for actiom="/webapp/handleservlet "  JavaScript is also parsed on the client side, so its relative path is the same as the form form.   Therefore, in general, in the Jsp/html page and other references such as  css,javascript.action and other properties are preferably preceded by <%=request.getcontextpath ()%> To ensure that the referenced files belong to a directory in your Web app. In addition, you should try to avoid the use of similar ".", "./", ". /.. Relative path relative to the location of the file, so that when the file is moved, it isProne to problems.  3. Get the relative and absolute paths of the current application in Jsp/servlet3.1 JSP gets the absolute path to the current app's relative path and absolute path root: The absolute path to the Request.getrequesturi () file: Application.getrealpath ( Request.getrequesturi ()); The absolute path of the current Web application: Application.getrealpath ("/"); Gets the upper-level directory of the requested file: New file (Application.getrealpath (Request.getrequesturi ())). The GetParent () 3.2 servlet obtains the absolute path corresponding to the current app's relative path and absolute path root: Request.getservletpath (); absolute path to the file: Request.getsession (). Getservletcontext (). Getrealpath (Request.getrequesturi ()) 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 ())method of obtaining relative path, absolute path in 4.java class4.1 The absolute path in a separate Java class is based on the doc text of Java.io.File, which shows that the directory represented by the new File ("/") by default 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 ("/"));
The path of the class file
System.out.println (New File ("/"). GetAbsolutePath ());
System.out.println (System.getproperty ("User.dir"));
}
}
4.2 Java classes in the server get the current path(1). The weblogicwebapplication system file root directory is the root directory where your WebLogic installation is located. For example: If your WebLogic is installed in c:beaweblogic700 ..... So, your file root path is C:. So there are two ways you can access your server-side files: A. Use absolute path: For example, put your parameter file in C:yourconfigyourconf.properties, use new directly FileInputStream ("Yourconfig/yourconf.properties"); B. Using a relative path: the root of the relative path is the root of your webapplication, which is the top-level directory of Web-inf, where you put your parameter file in Yourwebappyourconfigyourconf.properties, so you use: New FileInputStream ("./yourconfig/yourconf.properties"), both of which can be chosen by themselves. (2). Tomcat outputs System.getproperty ("User.dir") in the class, and%tomcat_home%/bin (3) is displayed. Resin is not the relative path that your JSP puts, it is the JSP engine that executes this JSP to compile the path of the servlet to the root. For example, use the new file method to test file F = new ("A.htm"), which is a.htm in the Resin installation directory (4). How to read a relative path? Examples of getresource or getResourceAsStream in Java files are: GetClass (). getResourceAsStream (FilePath);//filepath can be "/filename", Here/on behalf of the WEB publishing root path under Web-inf/classes The default path for using this method is: web-inf/classes. has been tested in Tomcat. Summary: Through the use of the above content can be resolved in the Web application server side, move files, find files, copy delete files and other operations, while the relative address of the server, the absolute address concept clearer. Recommended reference URI, RFC standard text block. At the same time, the understanding of Java.io.File Java.net.URI and other aspects can be more thorough and thorough. This is the way to go to the root of the current project in Java/** *//**
* TODO Gets the root directory of the current project
* @author Pheh
*/
public class application ... {

/** *//**
* TODO Get root directory
* @return
* @author Pheh
*/
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")) ... {
Returns the path of "jar:file:/f:/..." When the class file is in the jar file
result = Result.substring (10);
}else if (result.startswith ("file")) ... {
Returns the path of "file:/f:/..." When the class file is in the class file
result = result.substring (6);
}
if (Result.endswith ("/")) result = Result.substring (0,result.length ()-1);//does not contain the last "/"
return result;
}
}Java Web get web App root path (GO)Tags: webjavaservletjspstrutsweb service2012-05-09 10:52 15369 People read Comments (1) favorite reports

The most basic

1,request.getrealpath ("/"); This method has not been recommended

2, use This.getservletcontext (). Getrealpath ("/") in the servlet; get the path.
or Request.getsession (). Getservletcontext (). Getrealpath ("/") to obtain.

3,struts with This.getservlet (). Getservletcontext (). Getrealpath ("/") to obtain the path.

In spring, you can use the

Contextloader.getcurrentwebapplicationcontext (). Getservletcontext (). Getrealpath ("/") to obtain.

Then go to Java to get the real path to the Web service:

(1), Request.getrealpath ("/");//not recommended to get the root path of the project
(2), Request.getrealpath (Request.getrequesturi ());//Get the path of the JSP, this method is more useful, can be used directly in the servlet and JSP
(3), Request.getsession (). Getservletcontext (). Getrealpath ("/");//Get the root path of the project, this method is more useful, can be used directly in the servlet and JSP
(4), This.getclass (). getClassLoader (). GetResource (""). GetPath ();//Get the path under the project classes, this method can be in any jsp,servlet, Java files, because either Jsp,servlet is actually a Java program and is a class. So it should be a common method.

Re-rotating:

This.getclass (). getClassLoader (). GetResource ("template");
First, the GetClass () method of the calling object is to get the object's current class type, which exists in the method area, and then calls the getClassLoader () method on the class type to get the class loader of the current type. We know that all classes in Java are loaded into the virtual machine by the loader, and that there is a parent-child relationship between the ClassLoader, that is, the child knows the parent, the parent does not know the child, so that the different types of child loading are inaccessible (although they are all placed in the method area), So the loading of resources through the loader of the current class here is guaranteed to be loaded with the same loader as the class type.
Finally, the class loader's getResourceAsStream () method is called to load the resource.

Access to various paths in JAVA Web projects

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.