简体   繁体   English

JSP-404处理图像

[英]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 ? 上面的代码处理了imageURL为null的情况,但是当imageURL返回正确的URL但在服务器上找不到该图像(即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. 目前,您没有对JSP中的路径进行任何检查,只是将路径放入HTML(如果存在)中。 This means that you don't know if the path exists until the HTTP request comes through for the image. 这意味着,直到对图像的HTTP请求通过,您才知道路径是否存在。 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: 在包含该文件之前,请检查JSP代码中该路径是否存在文件,否则回退到占位符:

<% 
    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: 或者让您的HTML处理非显示图像,例如:

<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 : 我使用jquery和onerror属性解决了这个问题:

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 : 和一个小的jquery函数:

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 . 这里更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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