The relative paths called in JSP and class files are different. In JSP, the root directory is webroot in the class file, the root directory is webroot/WEB-INF/classes of course you can also use system. getproperty (& quot; user. dir & quot;) to obtain the absolute path of your project.
1. Obtain the path in JSP:
Take the project name test as an example.
(1) obtain the full path of the current page containing the Project name:
- Request. getrequesturi ()
Request. getrequesturi ()
Result:/test. jsp
(2) obtain the Project name:
- Request. getcontextpath ()
Request. getcontextpath ()
Result:/test
(3) obtain the full name of the directory where the current page is located:
- Request. getservletpath ()
Request. getservletpath ()
Result: If the page is in the/test/JSP/test. jsp directory
(4) obtain the full path of the server where the page is located:
- Application. getrealpath ("test. jsp ")
Application. getrealpath ("test. jsp ")
Result: D: \ resin \ webapps \ test. jsp
(5) obtain the absolute path of the server where the page is located:
- Abspath =NewJava. Io. File (application. getrealpath (request. getrequesturi (). getparent ();
Abspath = new java. Io. File (application. getrealpath (request. getrequesturi (). getparent ();
Result: D: \ resin \ webapps \ test
2. Obtain the path in the class:
(1) absolute path of the class:
- Class.Class. Getclass (). getresource ("/"). getpath ()
Class. Class. getclass (). getresource ("/"). getpath ()
(2) obtain the project path:
- System. getproperty ("user. dir ")
System. getproperty ("user. dir ")
Result: D: \ test
3. Get the path in servlet:
(1) obtain the project directory:
- Request. getsession (). getservletcontext (). getrealpath ("") // you can specify the package name.
Request. getsession (). getservletcontext (). getrealpath ("") // you can specify the package name.
Result: e: \ Tomcat \ webapps \ test
(2) obtain the address in the IE address bar:
- Request. getrequesturl ()
Request. getrequesturl ()
Result: http: // localhost: 8080/test
(3) obtain the relative address:
- Request. getrequesturi ()
Request. getrequesturi ()
Result:/test