完整實作流程
1. Action 類別準備資料
public class SongAction extends ActionSupport {
private List searchSongResult;
private String songname;
private SongManageService songManageService;
// getter/setter 省略
public String search() {
try {
searchSongResult = songManageService.getSongByName(songname);
return SUCCESS;
} catch (Exception e) {
return ERROR;
}
}
}
2. struts.xml 配置結果
/songList.jsp
/error.jsp
3. JSP 頁面使用 JSTL 迭代
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
| 歌名 | 歌手 | 專輯 |
| ${song.name} |
${song.singer} |
${song.album} |
關鍵點解析
- 屬性名稱一致:Action 的
getSearchSongResult() 對應 EL 表達式 ${searchSongResult}。
- JSTL 依賴:專案需包含
jstl-1.2.jar (或 javax.servlet:jstl)。
- 避免 Scriptlet:不建議在 JSP 寫 `<% ... %>`,改用 EL + JSTL 符合 MVC 分離。
- 泛型保留:
List 編譯後泛型擦除,但 JSTL 仍能正確存取 Song 的屬性 getter。
常見錯誤與修正
| 錯誤現象 | 原因 | 修正 |
| 頁面顯示空白 / 無資料 | Action 回傳 result 名稱與 struts.xml 不符,或 List 為 null | 檢查 struts.xml result name;Action 中初始化 List = new ArrayList<>() |
| EL 表達式不解析 (原樣輸出 ${...}) | web.xml servlet 版本 < 2.4 或缺少 isELIgnored="false" | web.xml 宣告 <web-app version="3.0">;JSP 頁首加 `<%@ page isELIgnored="false" %>` |
| 找不到 Song 屬性 | Song 類別缺少對應的 getter (getName/getSinger...) | 補齊標準 JavaBean getter |
進階:分頁、排序、條件顯示
| ${status.count} |
${song.name} |
- 上一篇文章: Java 只想覆寫框架介面中單一方法,卻被迫實作所有 500 個方法的解決之道
- 下一篇文章: Android WebView 在 ScrollView+ViewPager 嵌套中無法提前獲取內容高度的替代方案
Copyright ©
程式碼之家 All Rights Reserved