How to use a Servlet to find the Real path of resources
This is a quick tip to show how you can find the path to the resources which are distributed in a Web application. From this information, you will be able to open an input stream to access them.
In the beginning, to fetch the real path of a Web resource you could use the method request.getRealPath() . This is now deprecated.
The correct way to retrieve the real path of a resource bundled in your application you can use the getRealPath method of the ServletContext(). Example:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String path = "/index.html";
String realPath = getServletConfig().getServletContext().getRealPath(path);
PrintWriter writer = response.getWriter();
writer.println(realPath);
writer.flush();
}
The output of getRealPath depends if your Web application is in exploded format or if itβs a compressed WAR file.
If your application is an exploded directory, you will see the path from your deployments directory. Example:
/home/jboss/wildfly-preview-27.0.0.Alpha2/standalone/deployments/test.war/index.html
On the other hand, if you are deploying the application as a compressed archive, the real path will be under the temp folder of your application server. For WildFly, this could be like that:
/home/jboss/wildfly-preview-27.0.0.Alpha2/standalone/tmp/vfs/temp/temp2b8dcd3e1db9736b/content-e747f1df1f597cba/index.html
Recommended Articles
Fix Java.lang.OutOfMemoryError: Compressed Class Space Error on 64-bit Platforms
Learn how to resolve 'java.lang.OutOfMemoryError: Compressed class space error' in Java 1.8 and later versions.
Dynamically Register Servlets and Filters in Java EE 6 Applications
Learn how to use the ServletContext class to programmatically add servlets and filters to a web application during startup with Java EE 6.
Implementing WebSockets in Java for Real-Time Bi-Directional Communication
Learn how to build real-time bi-directional communication using WebSockets in Java, with a step-by-step guide on creating a WebSocket application using Maven and WildFly 31.
Mastering Java Machine Learning: Weka and Beyond
Discover the power of Java-based machine learning libraries and platforms. Learn about popular projects like Weka and how to solve real-world problems with classification, regression, and clustering.