0

Is there anyway to check if required resource available or not

My code

<img id="photo" src="http://localhost:8081/test.png" />

Now suppose my image name is test.png

now what i want to do is check if http://localhost:8081/test.png available or not

e.g <c:if test="${resource}">

if not available i want to put default.png as http://localhost:8081/default.png in the src which is available that i know for sure.

and If it is available then i will put src value to http://localhost:8081/test.png

How to do this??

LynAs
  • 6,407
  • 14
  • 48
  • 83
  • 1
    That's not as easy as it sounds, because basically what you're asking is if the webserver is physically capable of providing that image through a HTTP request. – Gimby Mar 03 '14 at 10:15
  • yes. is it not possible?? – LynAs Mar 03 '14 at 10:18
  • Well where are the images stored? If they are in some directory on the server, you could check with a simple File object if an image exists or not. If they are part of a deployed WAR or EAR, I'd see if there is a client side / javascript way to do it in stead. – Gimby Mar 03 '14 at 10:20
  • 1
    It is possible but you will have to check in a http request if that resource is present and can be served – Jabir Mar 03 '14 at 10:20
  • the images are stored in a separate server (nginx) but both tomcat and nginx are in the same PC – LynAs Mar 03 '14 at 10:23
  • Then Jabir's comment is probably the only reliable way; you'd have to do a HTTP request from Java code to know if the resource can be served or not before the page is rendered. – Gimby Mar 03 '14 at 10:53
  • Using Java i can do this easily, i know that. but i was wondering if i could do that from front end – LynAs Mar 03 '14 at 10:55
  • Then why post this as a java question which is back end!? – Gimby Mar 03 '14 at 11:39

2 Answers2

0

You can use following code from this answer. Please note this is not JSTL based solution as stated in question.

function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status != 404;

}
Community
  • 1
  • 1
Jabir
  • 2,776
  • 1
  • 22
  • 31
0

I think you should develop your own custom tag, that returns one picture or another depending on the availavility of the first.

You should use two parameters: One for the image that may be available or not, and another for the "default" image.

Here's a good introduction to the subject.

http://www.tutorialspoint.com/jsp/jsp_custom_tags.htm

Andres
  • 10,561
  • 4
  • 45
  • 63