Detailed explanation of relative paths and absolute paths in java (Web)
Foreword:
Some time ago, due to dealing with file creation and movement under Web applications, it involved many issues about relative paths, absolute paths and other issues in java
. At the same time, I learned about relative paths, absolute paths, and Java.io.File
classes in web applications. I also found some information. I hope that if you encounter similar problems, you can solve them more effectively.
============================================== =====================================
1. Understanding of basic concepts
Absolute path: The absolute path is the real path of the file or directory on your homepage on the hard disk, (URL and physical path). For example:
C:/xyz/test.txt represents the absolute path of the test.txt file. path. www.sun.com/index.htm also represents a
URL absolute path.
Relative path: a path relative to a base directory. Contains the relative path of the Web (relative directory in HTML). For example: in
Servlet, "/" represents the directory of the Web application. and a relative representation of the physical path. For example: "./" represents the current directory,
"../" represents the upper-level directory. This similar representation also belongs to relative path.
In addition, for URI, URL, URN, etc., please refer to RFC related document standards.
RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax,
(www.ietf.org/rfc/rfc2396.txt)
2. About JSP/Servlet Relative paths and absolute paths in .
2.1 Server-side address
The server-side relative address refers to the address relative to your web application. This address is resolved
on the server side (different from html and JavaScript) Relative addresses, they are parsed by the client browser) In other words, at this time, the relative addresses in jsp and servlet should be relative to your web application, that is, relative to http://192.168.0.1/ webapp/.
forward: request.getRequestDispatcher(address) in the servlet; this address is
parsed on the server side, so if you want to forward to a.jsp, it should Write this:
request.getRequestDispatcher("/user/a.jsp") This/relative to the current web application webapp,
its absolute address is: 192.168.0.1/webapp/user/a.jsp.
sendRedirect: In jsp
All html The relative addresses in the page are relative to the server root directory (http://192.168.0.1/),
instead of (the directory of the web application under the directory) http://192.168.0.1/webapp/ of.
The address of the action attribute of the form in Html should be relative to the server root directory 192.168.0.1/),
So, if submitted to a.jsp: action="/webapp/user/a. jsp" or action=""/user/a.jsp;
Submitted to the servlet as actiom="/webapp/handleservlet"
JavaScript is also parsed on the client side , so its relative path is the same as the form form.
In addition, you should try to avoid using similar relative paths to the file location such as ".", "./", "../../", etc., so that
it is easy to cause problems when the file is moved. question.
3. Obtain the relative path and absolute path of the current application in JSP/Servlet
3.1 Obtain the relative path and absolute path of the current application in JSP
The absolute path corresponding to the root directory: request.getRequestURI()
The absolute path of the file :application.getRealPath(request.getRequestURI());
The absolute path of the current web application: application.getRealPath("/");
Get the requested file Upper directory: new File(application.getRealPath(request.getRequestURI())).getParent()
The absolute path corresponding to the root directory: request.getServletPath();
The absolute path of the file :request.getSession().getServletContext().getRealPath
(request.getRequestURI())
The absolute path of the current web application: servletConfig.getServletContext() .getRealPath("/");
(ServletContext对象获得几种方式: javax.servlet.http.HttpSession.getServletContext() javax.servlet.jsp.PageContext.getServletContext() javax.servlet.ServletConfig.getServletContext() )4.java's Class to obtain the relative path, the absolute path method
4.1 Obtain the absolute path in a separate Java class
According to java. From the Doc file of io.File, we can see:
By default, the directory represented by new File("/") is: System.getProperty("user.dir").
The following 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("/")); //Class文件所在路径 System.out.println(new File("/").getAbsolutePath()); System.out.println(System.getProperty("user.dir")); }}4.2 The Java class in the server obtains the current path (from the network)
(1).Weblogic
The system file root directory of WebApplication is the root directory where your weblogic installation is located.
For example: If your weblogic is installed at c:/bea/weblogic700....
Then, your file root path is c:/.
So, there are two ways for you to access Your server-side file:
a. Use absolute path:
For example, put your parameter file in c:/yourconfig/yourconf.properties,
directly use new FileInputStream("yourconfig/yourconf.properties" );
b. Use relative paths:
The root directory of the relative path is the root path of your webapplication, which is the upper-level directory of WEB-INF. Place your parameter file in
yourwebapp/yourconfig/yourconf.properties,
Use like this:
new FileInputStream("./yourconfig/yourconf.properties");
Both methods are available, you can choose.
(2).Tomcat
Output System.getProperty("user.dir") in the class; what is displayed is %Tomcat_Home%/bin
(3). Resin
is not the relative path where your JSP is placed. It is the path where the JSP engine executes the JSP and compiles it into SERVLET
as the root. For example, use the new file method to test File f = new File("a.htm" );
This a.htm is in the installation directory of resin
(4). How to read the relative path?
You can getResource or getResourceAsStream in Java files
Example: getClass().getResourceAsStream(filePath);//filePath can be "/filename", where / represents web
Publish WEB-INF/classes under the root path
The default path to use this method is: WEB-INF/classes. Already tested in Tomcat.
5. Relative paths when reading files, avoid the use of hard coding and absolute paths. (From the Internet)
5.1 Use spring's DI mechanism to obtain files to avoid hard coding.
Refer to the following connection content:
www.javajia.net/viewtopic.php?p=90213&
5.2 Reading the configuration file
Refer to the following connection content:
dev.csdn. net/develop/article/39/39681.shtm
5.3 Read an xml file through a virtual path or relative path to avoid hard coding
Refer to the following connection content:
club.gamvan.com/club/ clubPage.jsp?iPage=1&tID=10708&ccID=8
6. Common operations of files in Java (copy, move, delete, create, etc.) (from the Internet)
Commonly used Java File operation classes
www.easydone.cn/014/200604022353065155.htm
Java file operations (in JSP)
www.pconline.com.cn/pcedu/empolder/gj/java/0502/559401.html
Detailed explanation of java file operations (Java Chinese website)
www.51cto.com/html/2005/1108/10947.htm
How to create/delete/modify/copy directories and files in JAVA
www.gamvan.com/developer/java/2005/2/264.html
Summary:
Through the use of the above content, you can solve the problem of moving files and finding files on the Web application server side , Copy
Delete files and other operations, and at the same time, the concept of relative address and absolute address of the server will be clearer.
It is recommended to refer to the RFC standard document of URI. At the same time, we have a thorough understanding of Java.io.File. Java.NET.URI. and other contents
The understanding of other aspects can be more in-depth and thorough.
The above is the detailed content of Detailed explanation of relative paths and absolute paths in java (Web). For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!