I decided it differently.
First, the unbearable way is that Glassfish (and I believe Tomcat too) allows you to map the external directory to the webapps hierarchy. It works very well and does exactly what you want. It allows you to store your images in an external directory away from your web application, but still serve them.
However, this method is not portable.
A way to make this portable is to create a filter.
You put the filter in some place, for example "/ images".
What the filter does:
he checks that the image (or something, it works with any static resource) in a special directory inside webapp. In our example, we will use url / webapp / images.
if the file does NOT exist, we will copy the file from your external location to the appropriate location in webapp. So let's say reqyest url is "/images/banner.gif". And your files are stored on disk in the folder "/ home / app / images". So, our source file is "/home/app/images/banner.gif". Then we copy it to where we want it in the webapp tree. For this we use "ServletContext.getRealPath". Thus, the destination will be "ServletContext.get RealPath" ("/webapp/images/banner.gif"). Just copy the source to your destination.
- If the file already exists or exists, just go to the actual image in /webapp/images/banner.gif.
In fact, you get the cache file in your webapps deployment tree. The downside is the cache, so it needs to be maintained (i.e. you need to check if the original is newer than your cache, make sure you delete if the source is deleted, etc.). In addition, it duplicates your resources, so your images will ultimately consume twice as much disk space. Finally, the initial cost of copying at startup.
However, it works, and this prevents you from serving static resources using your own code. (This is the 3rd solution, map the filter / servlet to intercept the URLs and just pass it to yourself.)
I would look at the construct inside Tomcat (assuming it exists) to do the mapping for you. I know that it exists in Glassfish. (Google alternatedocroot for Glassfish to see how it works.)
source share