I. servlet
We may often need to handle some Path Problems in the servlet, for example, to obtain the physical path of a file in the current application, or to know the specific path of a request, these methods are required.
1: Obtain the physical absolute path of the Web Application
The getrealpath () method in getservletcontext () is used to return the physical absolute path of a file in the current web application.
String webrealpath = request. getsession (). getservletcontext (). getrealpath ("/");
Here, "/" is used to return the physical path of the Web application root directory. For example, the storage location of my web application on the local machine is
C:/Eclipse/workspace/mynews
|__ WEB-INF
| ___ Class
| ___ Lib
C:/Eclipse/workspace/mynews
2: When I enter the following request path in the browser: http: // localhost: 8080/mynews/index. jsp
The output results of the following methods are as follows:
Request. getcontextpath () output:
/Mynews
Get URI
Request. getrequesturi () output:
/Mynews/index. jsp
Get URL
Request. getrequesturl () output:
Http: // localhost: 8080/mynews/index. jsp
It is easy to use these methods in the program.
Ii. Path Problems in JSP
Relative paths can be used in JSP, so some problems may occur.
For example, a Web application named path has the following file structure:
Web
|__ WEB-INF
|__ Index. jsp
|__ Internal
|__ Internal. jsp
In index. jsp, there is a connection <a href = "Internal/Internal. jsp"> link </a>. Click this connection and the connection will be connected to the following address:
Http: // localhost: 8080/web/Internal. jsp. That is to say, the connection address above is relative to index. jsp.
When you change the link to <a href = "/Internal. jsp"> link </a>, the link address is changed to the following:
Http: // localhost: 8080/Internal. jsp that is to say, when "/" is added, it becomes relative to the root directory of the website, rather than the root directory of the Web application.
Similarly, in internal. jsp, we can use.../index. jsp to link to the index. jsp page.
The above principles also apply to the path issue in the action when submitting the form, whether the action is directed to the servlet or JSP page.
End!