Search code examples
javajspservletsresourcesclassloader

Reloading resources in Java Web Application


I upload an image from hard drive and then store it in some folder in my app.
But the image isn't displayed immediately on my JSP, it is displayed only after I restart the app.
I guess that's because when the app resources are loaded, required image file doesn't exist in the destination folder yet.
So, I think that reloading app resources programmaticaly immediately after storing the image file into the destination folder will solve my problem, but I don't have a clue how to do it.

Update 1: Part of jsp were the image is asked for:

<img src="${pageContext.servletContext.contextPath}/img/${imageUrl}" />

where imageUrl is the image file name with it's extension.

The images are stored in MyProject/src/main/webapp/img/

Could anyone help me?
Thanks in advance.


Solution

  • I see.. Thanks.

    Here is what happens (IMHO :) ) :

    During the JSP processing the variable gets resolved to some static path and gets passed to the browser.

    Browses renders the static content here, once it sees the path it issues additional http request to the server, but it seems like your server can't find your image statically. Its due to the fact that you Can't change the war physical structure once it gets deployed. Think just like you work with a file based representation of WAR and not with exploded directory.

    Now what you can do?

    Try to create a resource servlet that will get the request to bring the binary image and will return it.

    Register this servlet in your web.xml with path like,say, /resource and make it get the get parameter imgName

    Example

    <img src="resource?imageName=${imageNameYouWant}" />

    In your jsp instead of static content in img src tag call the servlet with image as a parameter. When browser sees this it issues a regular request like before but this time it gets processed by your resource servlet and it will bring the image.

    Another thing I would try is just to move the images folder outside the webapp directory. This directory is tracked by your web container automatically but there is no reason to store the images there as well.

    You do like this:

    1. Create a directory like: /myapp/images

    2. You'll still need to create some component on the server side. But this time it can probably be done by creating some configuration on the web server side (no custom servlet). I'm not sure this will work when you use the first approach...

    3. In JSP point on the server as I've already explained above.

    It its an enterprise serious application I would recommend the first approach in conjunction with storing the images in the database but its a different story :)

    Hope this helps