支付頁面需顯示數十家銀行圖示,若每次請求皆掃描檔案系統,會造成不必要的 I/O 開銷。銀行圖示屬「靜態、低變動」資源,適合在專案啟動時一次載入至 ServletContext (Application),前台直接從 Application 讀取,效能最佳。
@Component("fileUpload")
public class FileUploadUtil implements FileUpload {
@Value("#{prop.basePath + prop.bankImagePath}")
private String bankImagePath; // 例:E:/webapps/ROOT/files/bankImages
public String[] getBankImages() {
File dir = new File(bankImagePath);
return dir.list((d, name) -> name.toLowerCase().endsWith(".gif"));
}
}
FilenameFilter 僅保留 .gif 副檔名,避免隱藏檔或非圖示檔案混入。
public class InitDataListener implements ServletContextListener {
private ApplicationContext context;
private FileUpload fileUpload;
@Override
public void contextInitialized(ServletContextEvent event) {
context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
fileUpload = (FileUpload) context.getBean("fileUpload");
// 將圖示檔名陣列存入 Application
event.getServletContext().setAttribute("bankImageList", fileUpload.getBankImages());
// 同場加映:啟動首頁資料定時同步(參考第 15 戰)
// new Timer(true).schedule(...)
}
}
<c:forEach var="img" items="${applicationScope.bankImageList}">
<input type="radio" name="pd_FrpId" value="${img}" id="${img}" />
<label for="${img}">
<img src="${pageContext.request.contextPath}/files/bankImages/${img}" alt="${img}" />
&label>
</c:forEach>
搭配 CSS 排版,即可呈現整齊的銀行選單。
使用者從「訂單確認頁」點擊「去付款」時,原始訂單物件因重導向而消失。解法:在導向支付頁前,將訂單關鍵資訊(訂單號、金額、收件人等)暫存 Session,支付頁從 Session 取出顯示,付款完成後再清除。
本文示範「啟動時掃描靜態資源 → 存入 Application → 前台 JSTL 讀取」的經典快取模式,搭配 Session 傳遞訂單資訊,完成支付頁面的核心渲染邏輯,為後續「表單簽名提交易寶」鋪路。