本文說明 Struts 核心配置檔 struts-config.xml 各區段功能,並示範 MyEclipse 整合 Struts 開發流程:從專案建立、ActionForm 產生、驗證設定、到查詢功能實作。
<struts-config>
<data-sources/> <!-- JDBC 連線池 (建議改用 JNDI) -->
<form-beans/> <!-- ActionForm 定義 -->
<global-exceptions/> <!-- 全域例外對應 -->
<global-forwards/> <!-- 全域轉向 -->
<action-mappings/> <!-- 核心:Action 映射 -->
<message-resources/> <!-- 國際化訊息資源 -->
</struts-config>
web.xml 註冊 ActionServlet、struts-config.xml 骨架、TLD 複製至 WEB-INFT_user userId (PK, Char(10)) 用戶ID userName (Varchar(20)) 用戶名
org.apache.struts.action.ActionFormuserId、userName、results (List<User>)reset() 清空屬性validate() 做前端格式檢查public class User {
private String userId;
private String userName;
// getter/setter
}
<html:form action="/userQuery">
用戶ID: <html:text property="userId"/>
用戶名: <html:text property="userName"/>
<html:submit property="submit" value="查詢"/>
</html:form>
<logic:present name="UserQueryForm" property="results">
<logic:iterate id="user" name="UserQueryForm" property="results">
<bean:write name="user" property="userId"/> -
<bean:write name="user" property="userName"/><br>
</logic:iterate>
</logic:present>
org.apache.struts.action.Actionexecute() 內:取得 Form 資料 → 呼叫 Service/DAO 查詢 → 將 List<User> 存入 Form.results → 回傳 mapping.findForward("success")<form-bean name="UserQueryForm" type="com.example.form.UserQueryForm"/>
<action path="/userQuery"
type="com.example.action.UserQueryAction"
name="UserQueryForm"
scope="request"
validate="false">
<forward name="success" path="/userQueryResult.jsp"/>
</action>
camelCase (如 userId, userName)PascalCase (如 UserQueryForm)/userQuery, /editRecord)掌握 struts-config.xml 五大區段用途,善用 MyEclipse 產生樣板碼,遵循命名規範,即能高效開發 Struts 應用。後續可引入 Validator 框架、Tiles 模板、Service 層分離等進階技術。