| 層級 | 元件 | 職責 |
|---|---|---|
| Model | PersonBean | 屬性 userName、get/set、saveToPersistentStore() |
| View | hello.jsp + HelloForm (ActionForm) | 介面輸入、表單驗證 (validate) |
| Controller | HelloAction | 業務驗證 (Monster)、呼叫 Model.save()、決定轉向 |
label.name=Name:
error.name.required=Please enter your name.
error.name.monster=We don't greet monsters!
title.hello=Hello Application
JSP 使用 <bean:message key="..."/> 讀取,支援國際化。
public class HelloForm extends ActionForm {
private String name;
public ActionErrors validate(ActionMapping mapping, HttpServletRequest req) {
ActionErrors errors = new ActionErrors();
if (name == null || name.trim().length() == 0) {
errors.add("name", new ActionMessage("error.name.required"));
}
return errors;
}
// getter/setter/reset
}
public class HelloAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest req,
HttpServletResponse res) throws Exception {
HelloForm helloForm = (HelloForm) form;
String name = helloForm.getName();
// 業務邏輯驗證
if ("Monster".equals(name)) {
ActionErrors errors = new ActionErrors();
errors.add("name", new ActionMessage("error.name.monster"));
saveErrors(req, errors);
return mapping.getInputForward(); // 回輸入頁
}
// 呼叫 Model
PersonBean person = new PersonBean();
person.setUserName(name);
person.saveToPersistentStore();
// 共享資料給 View
req.setAttribute("savedName", name);
return mapping.findForward("success");
}
}
public class PersonBean {
private String userName;
public void saveToPersistentStore() {
// 實際可對接 DB、檔案、EJB、Web Service
}
// getter/setter
}
public class Constants {
public static final String SAVED_NAME_KEY = "savedName";
}
Action 用 req.setAttribute(Constants.SAVED_NAME_KEY, name),JSP 用 <bean:write name="savedName"/> 取用,避免硬編碼字串。
web.xml:設定 ActionServlet、Taglib 宣告 (bean, html, logic)struts-config.xml:串聯 FormBean、Action、Forward、MessageResources
/helloapp
hello.jsp
/WEB-INF
web.xml, struts-config.xml
/lib
struts.jar, commons-*.jar
/classes
/com/example/helloapp
HelloAction.class, HelloForm.class, PersonBean.class, Constants.class
/resources
ApplicationResources.properties
<html:errors> 顯示struts-config.xml 為整合中樞HelloApp 雖簡單,卻完整展示 Struts 開發全流程。實務專案可依此骨架擴展:引入 Service 層、DAO、Validator、Tiles、聲明式異常處理等。