"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Access Resources in the WAR/WEB-INF Directory with ServletContext?

How to Access Resources in the WAR/WEB-INF Directory with ServletContext?

Published on 2024-12-21
Browse:700

How to Access Resources in the WAR/WEB-INF Directory with ServletContext?

Accessing Resources in the WAR/WEB-INF Directory with ServletContext

Introduction:

Java web applications often store essential resources within the WAR/WEB-INF directory. To access these resources, developers can leverage the ServletContext API.

Question:

How can you create the correct path to a resource located in the WAR/WEB-INF folder, such as "/war/WEB-INF/test/foo.txt"?

Answer:

There are two primary methods for constructing the path to resources in the WAR/WEB-INF directory using ServletContext:

1. getRealPath() Method:

If the WAR file has been expanded into a set of files, you can use the getRealPath() method:

ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");

This will return the complete system path to the resource.

2. getResource() or getResourceAsStream() Methods:

These methods can be used regardless of whether the WAR file is expanded or not:

ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt"); // for URL
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt"); // for input stream

Additional Notes:

  • The getContext() method mentioned in the sample code is application-specific. In JSP pages, it is available as "context," while in servlets, it is obtained from the ServletConfig during initialization.
  • The getRealPath() method may not work if the Servlet Container does not extract the WAR file.
  • The getResource() and getResourceAsStream() methods are reliable and work in all deployment scenarios.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3