Home > Java > javaTutorial > What does ServletContext.getRealPath('/') return and when should I avoid using it?

What does ServletContext.getRealPath('/') return and when should I avoid using it?

Patricia Arquette
Release: 2024-12-19 22:54:11
Original
736 people have browsed it

What does ServletContext.getRealPath(

What is the Meaning of servletcontext.getRealPath("/")?

The ServletContext#getRealPath() method translates a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.

The "/" passed to getRealPath() represents the web content root, the /web folder in the following project structure:

 |-- src<br> |    :<br> |<br> |-- web<br> |    |-- META-INF<br> |    |    `-- MANIFEST.MF<br> |    |-- WEB-INF<br> |    |    `-- web.xml<br> |    |-- index.jsp<br> |    `-- login.jsp<br> :    <br>

Thus, getRealPath("/") returns the absolute disk file system path of the /web folder of the project's expanded WAR file.

When should I use it?

Avoid using getRealPath(), as there are more portable solutions for:



  • Obtaining an InputStream of a web resource: use ServletContext#getResourceAsStream()

  • Obtaining a list of available web resource paths: use ServletContext#getResourcePaths()

  • Obtaining an individual resource as a URL: use ServletContext#getResource()

Additional Notes

Modifications made to files written into the path returned by getRealPath() are lost upon WAR redeployment.

getRealPath() assumes the WAR file is expanded to the disk file system, which is not always the case. In such scenarios, getRealPath() may return null or an unexpected path.

The above is the detailed content of What does ServletContext.getRealPath('/') return and when should I avoid using it?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template