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

Struts 1.1 實戰入門:以登入/登出範例掌握 MVC 架構、配置與標籤庫應用

     編輯:Java 相關知識

前言

Struts 是早期 Java Web 開發的經典 MVC 框架,將 JSP (View)、Servlet (Controller)、JavaBean (Model) 解耦。本文以簡單的登入/登出系統為例,完整示範 Struts 1.1 的專案結構、配置檔、ActionForm、Action、JSP 標籤庫與國際化訊息資源的應用。

開發環境與專案結構

  • Tomcat 4.1.24 / Apache 2.0.43 / JDK 1.4 / Struts 1.1 / Eclipse 2.1
  • 專案目錄 logonApp/:
    • src/ - Java 原始碼
    • WEB-INF/classes/ - 編譯輸出
    • WEB-INF/lib/ - struts.jar, servlet.jar
    • WEB-INF/struts-*.tld - 標籤庫描述檔

核心配置檔

web.xml - Servlet 容器部署描述

<web-app>
  <!-- ActionServlet: Struts 前端控制器 -->
  <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>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
  <!-- 標籤庫宣告 -->
  <taglib><taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri><taglib-location>/WEB-INF/struts-bean.tld</taglib-location></taglib>
  <taglib><taglib-uri>/WEB-INF/struts-html.tld</taglib-uri><taglib-location>/WEB-INF/struts-html.tld</taglib-location></taglib>
  <taglib><taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri><taglib-location>/WEB-INF/struts-logic.tld</taglib-location></taglib>
</web-app>

struts-config.xml - Struts 核心配置

<struts-config>
  <!-- 動態表單 Bean:無需撰寫 ActionForm 類別 -->
  <form-beans>
    <form-bean name="logonForm" type="org.apache.struts.validator.DynaValidatorForm">
      <form-property name="username" type="java.lang.String"/>
      <form-property name="password" type="java.lang.String"/>
    </form-bean>
  </form-beans>

  <!-- 全域轉向 -->
  <global-forwards>
    <forward name="success" path="/main.jsp"/>
    <forward name="logoff" path="/logoff.do"/>
  </global-forwards>

  <!-- Action 映射 -->
  <action-mappings>
    <action path="/logon"
            type="org.monotonous.struts.LogonAction"
            name="logonForm"
            scope="session"
            input="logon">  <!-- 驗證失敗導向 -->
    </action>
    <action path="/logoff"
            type="org.monotonous.struts.LogoffAction">
      <forward name="success" path="/index.jsp"/>
    </action>
  </action-mappings>

  <controller>
    <set-property property="inputForward" value="true"/>  <!-- input 參數視為 forward name -->
  </controller>

  <message-resources parameter="org.monotonous.struts.ApplicationResources"/>
</struts-config>

View 層:JSP + Struts 標籤庫

index.jsp - 登入頁面

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html locale="true">
<head>
  <title><bean:message key="index.title"/></title>
  <html:base/>
</head>
<body>
  <html:errors/>  <!-- 顯示驗證錯誤 -->
  <html:form action="/logon">
    <bean:message key="prompt.username"/>
    <html:text property="username"/><br/>
    <bean:message key="prompt.password"/>
    <html:password property="password"/><br/>
    <html:submit><bean:message key="index.logon"/></html:submit>
  </html:form>
</body>
</html:html>

main.jsp - 登入成功頁面

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html>
<head><title><bean:message key="main.title"/></title><html:base/></head>
<body>
  <html:link forward="logoff"><bean:message key="main.logoff"/></html:link>
</body>
</html:html>

ApplicationResources.properties - 國際化訊息資源

index.title=Struts Homepage
prompt.username=Username
prompt.password=Password
index.logon=Log on
main.title=Struts Main page
main.logoff=Log off
error.password.mismatch=Invalid username and/or password.

Controller 層:Action 實作

LogonAction.java - 登入處理

package org.monotonous.struts;
public final class LogonAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response) throws Exception {
        Locale locale = getLocale(request);
        MessageResources messages = getResources(request);
        ActionErrors errors = new ActionErrors();
        
        // 從 DynaValidatorForm 取值
        String username = (String) PropertyUtils.getSimpleProperty(form, "username");
        String password = (String) PropertyUtils.getSimpleProperty(form, "password");
        
        // 簡單驗證 (實務應查詢資料庫/服務)
        if (!"foo".equals(username) || !"bar".equals(password)) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.password.mismatch"));
        }
        
        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            return mapping.getInputForward();  // 返回 input="logon" 對應的 forward
        }
        
        // 登入成功:存入 Session
        HttpSession session = request.getSession();
        session.setAttribute("user", username);  // 實務存入 User 物件
        
        // 移除舊的 Form Bean (scope=session 時需手動清理)
        if (mapping.getAttribute() != null) {
            if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute());
            else session.removeAttribute(mapping.getAttribute());
        }
        
        return mapping.findForward("success");  // global-forwards success → /main.jsp
    }
}

LogoffAction.java - 登出處理

package org.monotonous.struts;
public final class LogoffAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        session.invalidate();  // 銷毀 Session
        return mapping.findForward("success");  // action-mappings logoff success → /index.jsp
    }
}

關鍵技術重點解析

概念說明
ActionServlet前端控制器,攔截 *.do 請求,委派給對應 Action
DynaValidatorForm動態表單,XML 定義屬性,免寫 ActionForm 類別,整合 Validator 框架
ActionMappingstruts-config.xml 元素對應物件,含 path、type、name、scope、input、forwards
ActionForward邏輯視圖名稱對應實際路徑,支援全域與區域轉向
ActionErrors/ActionError驗證錯誤收集器, 自動顯示
MessageResources國際化訊息資源管理, 取值
PropertyUtilsCommons BeanUtils 元件,動態存取 Form Bean 屬性

安全性補充建議 (原文預告)

  1. 密碼加密傳輸:強制 HTTPS,避免明文傳輸
  2. Session 管理:設定 Session timeout、防止 Session Fixation (登入後換發 Session ID)
  3. 防暴力破解:登入失敗計數、帳號鎖定、驗證碼
  4. 輸入驗證:Struts Validator 框架 (validation.xml) 進行伺服器端驗證
  5. CSRF 防護:Struts 1.1 需自行實作 Token 模式 (Struts 2 內建)

Struts 1.x 歷史定位與遷移

Struts 1.x (2000-2008) 確立了 Java Web MVC 模式,但有侵入性強 (繼承 Action)、表單處理繁瑣、靠攏 Servlet API 等缺點。現代專案建議遷移至:

  • Spring MVC:POJO Controller、強大的資料綁定、REST 支援、生態系完整
  • Struts 2:WebWork 繼承者、攔截器架構、OGNL 表達式、慣例優於配置
  • JSF / Spring Boot / Micronaut / Quarkus:現代化框架選擇

理解 Struts 1 核心概念 (前端控制器、Action 對應、Form Bean、轉向、標籤庫、國際化) 有助於快速掌握後續框架的同源設計思想。

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