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

Struts 開發指南:安裝配置與 Hello World 完整示例

     編輯:Java 相關知識

運行環境要求

  • Servlet 2.3+ / JSP 1.2+ 容器 (Tomcat 5+, Jetty, Resin, WebLogic, WebSphere)。
  • Struts 1.x 分發包含 struts-core.jar, struts-taglib.jar, struts-tiles.jar, commons-*.jar 等。

web.xml 核心配置

<web-app>
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern> <!-- 擴展映射 -->
    <!-- 或 <url-pattern>/do/*</url-pattern> 路徑映射 -->
  </servlet-mapping>

  <!-- 歡迎頁面 -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

struts-config.xml 標準結構

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
  "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
  "https://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
  <data-sources/>           <!-- 數據源 (舊版) -->
  <form-beans/>             <!-- ActionForm 定義 -->
  <global-exceptions/>      <!-- 全局異常映射 -->
  <global-forwards/>        <!-- 全局轉發 -->
  <action-mappings/>        <!-- Action 映射 (核心) -->
  <controller/>             <-- 控制器參數 (輸入緩衝區大小、區域等) -->
  <message-resources/>      <-- 國際化資源 -->
  <plug-in/>                <-- Validator、Tiles 等插件 -->
</struts-config>

請求處理流程圖解

HTTP Request (*.do)
      ↓
ActionServlet.init() → 解析 struts-config.xml
      ↓
RequestProcessor.process(request, response)
      ├─ lookup ActionMapping (path=/example)
      ├─ create/populate ActionForm (name=exampleActionForm)
      ├─ ActionForm.validate() → errors? → return input
      ├─ Action.execute(mapping, form, request, response)
      │      ├─ business logic
      │      └─ return ActionForward (name="forward")
      └─ mapping.findForward("forward") → /forward.jsp
            ↓
      RequestDispatcher.forward → JSP Rendering
            ↓
HTTP Response

最簡 Hello World 完整代碼

1. 輸入頁面 input.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
  <form method="post" action="example.do">
    請輸入值: <input type="text" name="test"/>
    <br><br>
    <input type="submit" value="提交"/>
    <input type="reset" value="重置"/>
  </form>
</body>
</html>

2. FormBean ExampleActionForm.java

package com.demo.struts;
import org.apache.struts.action.ActionForm;

public class ExampleActionForm extends ActionForm {
    private String test;
    public String getTest() { return test; }
    public void setTest(String test) { this.test = test; }
    // 可選 validate() 返回 ActionErrors
}

3. Action ExampleAction.java

package com.demo.struts;
import javax.servlet.http.*;
import org.apache.struts.action.*;

public class ExampleAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response) {
        ExampleActionForm f = (ExampleActionForm) form;
        String test = f.getTest();
        if (test == null || test.trim().isEmpty()) {
            request.setAttribute("test", "empty");
        } else {
            request.setAttribute("test", test);
        }
        return mapping.findForward("forward");
    }
}

4. 結果頁面 forward.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<html><body>
  處理結果: ${requestScope.test}
</body></html>

5. struts-config.xml 片段

<form-beans>
  <form-bean name="exampleActionForm" type="com.demo.struts.ExampleActionForm"/>
</form-beans>

<action-mappings>
  <action path="/example"
          type="com.demo.struts.ExampleAction"
          name="exampleActionForm"
          scope="request"
          validate="false"> <!-- 簡化示例關閉驗證 -->
    <forward name="forward" path="/forward.jsp"/>
  </action>
</action-mappings>

URL 訪問測試

啟動 Tomcat,瀏覽器訪問:https://localhost:8080/your-context/input.jsp → 輸入內容 → 提交 → 顯示結果。

常見坑點避雷

  • url-pattern 與 Action path 對應:*.do 映射時 path="/example" 對應 example.do;/do/* 映射時對應 /do/example。
  • form-bean name 必須與 action name 一致。
  • ActionForm 屬性名需與表單 name 完全匹配 (大小寫敏感)。
  • load-on-startup 確保容器啟動時初始化 ActionServlet,避免首次請求延遲。
  • Struts JAR 必須放在 WEB-INF/lib (Web 應用級) 或容器共享庫 (需類加載器隔離注意)。

總結

Struts 安裝配置核心在於 web.xml 註冊 ActionServlet、struts-config.xml 聲明 Form/Action/Forward 三要素。掌握請求流程與最小示例,是進階掌握驗證框架、Tiles、插件機制的基石。

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