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

Struts 超簡單入門(三):Action、Form、Model 與 Filter 完整代碼實作

     編輯:Java 相關知識

Struts 超簡單入門(三):Action、Form、Model 與 Filter 完整代碼實作

承接前兩篇(環境搭建、JSP 與配置檔),本文給出完整的 Java 類別代碼,放置於 Tomcat 5.0/webapps/struts/WEB-INF/classes/com/javer/test/struts/。

1. HelloForm.java — ActionForm 表單驗證與重置

package com.javer.test.struts;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;

public final class HelloForm extends ActionForm {
    private String person = null;

    public String getPerson() { return person; }
    public void setPerson(String person) { this.person = person; }

    public void reset(ActionMapping mapping, HttpServletRequest request) {
        this.person = null; // 表單重置
    }

    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (person == null || person.length() < 1) {
            errors.add("person", new ActionError("com.javer.test.struts.hello.error"));
        }
        return errors;
    }
}

2. HelloModel.java — 極簡業務邏輯(模擬持久化)

package com.javer.test.struts;
public class HelloModel {
    public void saveToPersistentStore(HelloForm hf) {
        System.out.println("Hello " + hf.getPerson() + "!這裡可存儲數據到數據庫中!");
    }
}

3. HelloAction.java — 控制器核心:驗證、轉碼、轉發

package com.javer.test.struts;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.util.MessageResources;
import org.apache.commons.beanutils.PropertyUtils;

public final class HelloAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        MessageResources messages = getResources(request);
        ActionErrors errors = new ActionErrors();

        // 使用 BeanUtils 取得屬性,避免強轉
        String person = (String) PropertyUtils.getSimpleProperty(form, "person");

        // 業務規則:名字不得包含逗號
        if (person.indexOf(",") != -1) {
            errors.add("person", new ActionError("com.javer.test.struts.hello.unallowed.person", form));
            saveErrors(request, errors);
            request.removeAttribute(mapping.getAttribute());
            return new ActionForward(mapping.getInput()); // 返回輸入頁
        }

        // 業務處理
        HelloModel hm = new HelloModel();
        hm.saveToPersistentStore((HelloForm) form);

        // 準備轉發數據
        request.removeAttribute(mapping.getAttribute());
        request.setAttribute("helloForm", form);

        return mapping.findForward("SayHello"); // 對應 struts-config.xml 的 forward
    }
}

4. EncodingFilter.java — 統一請求編碼過濾器(非 Struts 必需,但強烈建議)

package com.javer.test.struts;
import java.io.IOException;
import javax.servlet.*;

public class EncodingFilter implements Filter {
    protected String encoding = null;
    protected FilterConfig filterConfig = null;
    protected boolean ignore = true;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("ignore");
        if (value == null) this.ignore = true;
        else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")) this.ignore = true;
        else this.ignore = false;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (ignore || request.getCharacterEncoding() == null) {
            request.setCharacterEncoding(selectEncoding(request));
        }
        chain.doFilter(request, response);
    }

    protected String selectEncoding(ServletRequest request) { return this.encoding; }
    public void destroy() { this.encoding = null; this.filterConfig = null; }
    // getter/setter 略
}

關鍵設計點解析

類別職責Struts 介面/基類
HelloForm表單數據承載、驗證、重置ActionForm
HelloModel業務邏輯封裝(DAO 前身)POJO
HelloAction請求處理、驗證協調、轉發決策Action
EncodingFilter全局字符編碼統一Filter (Servlet 標準)
  • PropertyUtils.getSimpleProperty() 避免直接強轉 (HelloForm)form,鬆耦合。
  • ActionError 使用 MessageResources 國際化鍵值,訊息定義於 Application.properties。
  • EncodingFilter 在 web.xml 中映射 /*,確保所有請求編碼一致。

下一步

將本篇類別編譯部署,配合前兩篇的 hello.jsp、struts-config.xml、web.xml,啟動 Tomcat 訪問 https://localhost:8080/struts/hello.jsp 即可體驗完整流程。系列完結,歡迎實作驗證!

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