前端頁面根據後端返回的 PicturePath 顯示圖片。當路徑為 null、空串或無效時,需展示預設佔位圖或提示文字「No Picture」。
// 後端 Java 示例
String pictureUrl = (picturePath != null && !picturePath.trim().isEmpty())
? "https://cdn.example.com/" + picturePath
: "/static/images/placeholder.png"; // 或返回空串由前端處理
<img id="targetImg" src="" alt="圖片" />
<script>
const path = "{{PicturePath}}"; // 服務端模板渲染
const img = document.getElementById('targetImg');
if (path && path.trim()) {
img.src = "https://cdn.example.com/" + path;
} else {
img.src = "/static/images/placeholder.png";
img.alt = "無圖片";
}
</script>
<img v-if="picturePath" :src="fullImageUrl" alt="業務圖片" />
<img v-else src="/static/images/placeholder.png" alt="無圖片" />
<img :src="picturePath ? cdnBase + picturePath : placeholder" alt="圖片" />
const ImgDisplay = ({picturePath}) => (
<img
src={picturePath ? `https://cdn.example.com/${picturePath}` : '/static/images/placeholder.png'}
alt={picturePath ? '業務圖片' : '無圖片'}
/>
);
<!-- JSP JSTL -->
<c:choose>
<c:when test="${not empty picturePath}">
<img src="https://cdn.example.com/${picturePath}" alt="業務圖片" />
</c:when>
<c:otherwise>
<img src="/static/images/placeholder.png" alt="無圖片" />
</c:otherwise>
</c:choose>
<!-- Thymeleaf -->
<img th:src="${picturePath} ? @{'https://cdn.example.com/' + picturePath} : @{/static/images/placeholder.png}"
th:alt="${picturePath} ? '業務圖片' : '無圖片'" />
<img src="..." onerror="this.src='/static/images/placeholder.png'"> 捕獲 404/網絡錯誤。getImageUrl(path) 集中管理 CDN 域名、默認圖、簽名參數等。picturePath 缺失時返回 null 而非空串,前端統一判斷 if (path)。"null" 或 "undefined" 非真正 null,需 path && path !== 'null'。encodeURIComponent。「判空賦默認」是前後端協作的基礎模式。關鍵在於統一空值定義、集中處理邏輯、提供多層兜底(後端默認值 → 前端判空 → onerror 兜底),構建健壯的圖片展示體驗。