首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Struts 應用實戰:HelloApp 完整開發流程詳解

     編輯:Java 程式設計入門

需求分析

  • 接受使用者輸入姓名,回傳 "Hello !"
  • 未輸入姓名 → 表單驗證錯誤提示
  • 輸入 "Monster" → 業務邏輯拒絕並顯示錯誤
  • 使用 Model 元件 (PersonBean) 持久化姓名

MVC 模組劃分

層級元件職責
ModelPersonBean屬性 userName、get/set、saveToPersistentStore()
Viewhello.jsp + HelloForm (ActionForm)介面輸入、表單驗證 (validate)
ControllerHelloAction業務驗證 (Monster)、呼叫 Model.save()、決定轉向

關鍵實作細節

1. 訊息資源檔 (ApplicationResources.properties)

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="..."/> 讀取,支援國際化。

2. HelloForm.java (ActionForm)

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
}

3. HelloAction.java

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");
    }
}

4. PersonBean.java

public class PersonBean {
    private String userName;
    public void saveToPersistentStore() {
        // 實際可對接 DB、檔案、EJB、Web Service
    }
    // getter/setter
}

5. 常數類別 (Constants.java)

public class Constants {
    public static final String SAVED_NAME_KEY = "savedName";
}

Action 用 req.setAttribute(Constants.SAVED_NAME_KEY, name),JSP 用 <bean:write name="savedName"/> 取用,避免硬編碼字串。

6. web.xml 與 struts-config.xml

  • web.xml:設定 ActionServlet、Taglib 宣告 (bean, html, logic)
  • struts-config.xml:串聯 FormBean、Action、Forward、MessageResources

部署目錄結構 (符合 Servlet 規範)

/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

核心知識點總結

  1. 需求 → MVC 分解 → 配置檔串聯
  2. Taglib + 訊息資源 → 國際化、減少 Scriptlet
  3. ActionForm 跨請求共享 (request/session scope)
  4. 驗證分層:表單驗證 (ActionForm.validate) + 業務驗證 (Action/Model)
  5. ActionMessage/ActionErrors 統一錯誤處理,<html:errors> 顯示
  6. Action 決定轉向,Model 封裝業務細節,支援遠端遷移
  7. Request/Session 屬性實現 View-Controller 資料交換
  8. struts-config.xml 為整合中樞

結語

HelloApp 雖簡單,卻完整展示 Struts 開發全流程。實務專案可依此骨架擴展:引入 Service 層、DAO、Validator、Tiles、聲明式異常處理等。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved