简体   繁体   中英

JSP - 404 handling for image

I am using the below code to fetch images from my server :

<a href="#">
    <img src="<%
        if(user.getImageURL()!=null){
           out.print(user.getImageURL);
        }else{
           out.print("images/no-profile-pic-small.jpg");
        }%>" />
</a>

The above code handles the case when the imageURL is null, but how do I handle the case when the imageURL returns a proper URL but that image is not found on the server ie 404 Not Found ?

EDIT : The image is located on a different server.

At the moment, you're not doing any checking of the path in JSP, merely putting the path in the HTML if present. This means that you don't know if the path exists until the HTTP request comes through for the image. You've two main options:

Check if there's a file at that path in your JSP code before including it, otherwise fallback to your placeholder:

<% 
    String userImagePath = user.getImageURL();
    File userImage= new File(userImagePath);
    if(!userImage.exists()){
        userImagePath = "fallBackImagePath.png";
    }
%>

<img src="<%= userImagePath %>"/>

Or let your HTML handle a non-displaying image, eg:

<img src="non-existent.png" class="fallBackBackground"/>

<style>
    .fallBackBackground {
        background: url(./placeholderImage.png);
    }
</style>

This may result in you serving a fallback image that's not needed though, plus it relies on the images being the same size.

I resolved this problem using jquery and onerror attribute :

My server side code now is :

<a href="#">
    <img src="<%
        if(user.getImageURL()!=null){
           out.print(user.getImageURL);
        }else{
           out.print("images/no-profile-pic-small.jpg");
        }%>" onerror="profilePicNotFound(this);" 
    />
</a>

And a small jquery function :

function profilePicNotFound(image){
    image.src='images/no-profile-pic-small.jpg';
}

This works nicely if the image is located on a different server. More here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM