上面的代码处理 imageURL 为 null 时的情况,但是当 imageURL 返回正确的 URL 但在服务器上找不到该图像(即 4-6ren">
gpt4 book ai didi

java - JSP - 图像的 404 处理

转载 作者:行者123 更新时间:2023-11-30 04:25:25 25 4
gpt4 key购买 nike

我正在使用以下代码从我的服务器获取图像:

<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>

这可能会导致您提供不需要的后备图像,而且它依赖于相同大小的图像。

关于java - JSP - 图像的 404 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15997982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com