[英]JSP - 404 handling for image
我正在使用以下代碼從服務器獲取圖像:
<a href="#">
<img src="<%
if(user.getImageURL()!=null){
out.print(user.getImageURL);
}else{
out.print("images/no-profile-pic-small.jpg");
}%>" />
</a>
上面的代碼處理了imageURL為null的情況,但是當imageURL返回正確的URL但在服務器上找不到該圖像(即404 Not Found)時,該如何處理?
編輯 :圖像位於其他服務器上。
目前,您沒有對JSP中的路徑進行任何檢查,只是將路徑放入HTML(如果存在)中。 這意味着,直到對圖像的HTTP請求通過,您才知道路徑是否存在。 您有兩個主要選擇:
在包含該文件之前,請檢查JSP代碼中該路徑是否存在文件,否則回退到占位符:
<%
String userImagePath = user.getImageURL();
File userImage= new File(userImagePath);
if(!userImage.exists()){
userImagePath = "fallBackImagePath.png";
}
%>
<img src="<%= userImagePath %>"/>
或者讓您的HTML處理非顯示圖像,例如:
<img src="non-existent.png" class="fallBackBackground"/>
<style>
.fallBackBackground {
background: url(./placeholderImage.png);
}
</style>
這可能會導致您提供不需要的后備圖片,而且它依賴於相同大小的圖片。
我使用jquery和onerror
屬性解決了這個問題:
我的服務器端代碼現在是:
<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>
和一個小的jquery函數:
function profilePicNotFound(image){
image.src='images/no-profile-pic-small.jpg';
}
如果映像位於其他服務器上,則效果很好。 這里更多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.