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

Struts 1.x 系列教程(一):MyEclipse 快速構建首個 Struts 應用

     編輯:Java 相關知識

本系列教程將系統講解 Struts 1.x 核心原理與實戰技巧,讀者可對照《Struts 2 系列教程》理解兩代框架異同。首篇通過「產品信息錄入查詢系統」完整演示 MyEclipse 從零構建 Struts 專案的全流程。

一、項目功能需求:mystruts 產品管理系統

  • 錄入產品 ID、名稱、價格三字段
  • 服務端驗證字段合法性,非法則 forward 顯示錯誤原因
  • 合法數據保存至數據庫,顯示「保存成功」
  • 支援按產品名稱模糊查詢,表格展示結果含記錄數;無結果提示「沒有符合要求的記錄!」

二、環境準備:數據庫與專案創建

1. 建立數據庫 (MySQL)

CREATE DATABASE IF NOT EXISTS struts DEFAULT CHARACTER SET GBK;

CREATE TABLE IF NOT EXISTS struts.t_products (
  product_id varchar(4) NOT NULL,
  product_name varchar(50) NOT NULL,
  price float NOT NULL,
  PRIMARY KEY (product_id)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

2. MyEclipse 創建支持 Struts 1.x 的 Web 專案

  • 新建 Web 專案 samples
  • 右鍵專案 → MyEclipse → New Struts Capabilities
  • 關鍵設置修改:
Struts specification: Struts 1.2
Base package for new classes: struts
Default application resources: struts.ApplicationResources

圖1:New Struts Capabilities 配置界面

點擊 Finish 後自動完成三項操作:

  1. 引入 Struts 1.2 JAR 包(專案樹出現 "Struts 1.2 Libraries")
  2. WEB-INF 生成 struts-config.xml(含標準 DTD 聲明與空配置節點)
  3. web.xml 注冊 ActionServlet(url-pattern: *.do)

struts-config.xml 默認內容

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"https://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
  <data-sources />
  <form-beans />
  <global-exceptions />
  <global-forwards />
  <action-mappings />
  <message-resources parameter="struts.ApplicationResources" />
</struts-config>

web.xml 關鍵配置

<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>
  <init-param><param-name>debug</param-name><param-value>3</param-value></init-param>
  <init-param><param-name>detail</param-name><param-value>3</param-value></init-param>
  <load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>action</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

三、實現首頁 (mystruts/index.jsp)

<%@ page pageEncoding="GBK"%>
<%@ taglib uri="https://struts.apache.org/tags-html" prefix="html"%>
<html><head><title>主界面</title></head><body>
<table align="center" cellpadding="10" width="100%">
  <tr>
    <td align="right" width="50%">
      <html:link forward="newProduct">錄入產品信息</html:link>
    </td>
    <td>
      <html:link forward="searchProduct">查詢產品信息</html:link>
    </td>
  </tr>
</table>
</body></html>

啟動 Tomcat 訪問報錯:Cannot retrieve ActionForward named newProduct。需在 struts-config.xml 添加全局 forward:

<global-forwards>
  <forward name="newProduct" path="/mystruts/newProduct.jsp" />
  <forward name="searchProduct" path="/mystruts/searchProduct.jsp" />
</global-forwards>

重新訪問 https://localhost:8080/samples/mystruts/index.jsp 正常顯示。若需設為默認頁,在 web.xml 添加:

<welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>

四、錄入與查詢頁面

newProduct.jsp(錄入)

<%@ page pageEncoding="GBK"%>
<%@ taglib uri="https://struts.apache.org/tags-html" prefix="html"%>
<html:form action="saveProduct">
  <table width="100%">
    <tr><td align="center">
      產品編號:<html:text property="productID" maxlength="4" /><p>
      產品名稱:<html:text property="productName" /><p>
      產品價格:<html:text property="price" />
    </td></tr>
    <tr><td align="center"><br>
      <html:submit value=" 保存 " />
    </td></tr>
  </table>
</html:form>

searchProduct.jsp(查詢)

<%@ page pageEncoding="GBK"%>
<%@ taglib uri="https://struts.apache.org/tags-html" prefix="html"%>
<html:form action="searchProduct">
  <table width="100%">
    <tr><td align="center">
      產品名稱:<html:text property="productName" />
    </td></tr>
    <tr><td align="center"><br>
      <html:submit value=" 查詢 " />
    </td></tr>
  </table>
</html:form>

五、模型層操作數據庫(連接池 + 兩大模型類)

1. Tomcat 配置數據庫連接池

在 <Tomcat安裝目錄>/conf/Catalina/localhost/samples.xml 中配置:

<Resource name="jdbc/struts" auth="Container"
  type="javax.sql.DataSource"
  driverClassName="com.mysql.jdbc.Driver"
  url="jdbc:mysql://localhost:3306/struts?characterEncoding=GBK"
  username="root" password="1234"
  maxActive="200" maxIdle="50" maxWait="3000"/>

2. 基類 Struts (util/Struts.java) 封裝連接獲取

package util;
import java.sql.Connection;
public class Struts {
  protected javax.naming.Context ctx = new javax.naming.InitialContext();
  protected javax.sql.DataSource ds;
  protected Connection conn;
  public Struts() throws Exception {
    ds = (javax.sql.DataSource) ctx.lookup("java:/comp/env/jdbc/struts");
    conn = ds.getConnection();
  }
}

3. Product 模型 (mystruts/model/Product.java) — 驗證+保存

package mystruts.model;
import java.sql.*;
import mystruts.actionform.*;

public class Product extends util.Struts {
  private ProductForm form;
  public Product(ProductForm form) throws Exception {
    super(); this.form = form; validate();
  }
  public void validate() throws Exception {
    if (form.getProductID().trim().equals("")) throw new Exception("產品ID不能為空!");
    if (form.getProductID().length() > 4) throw new Exception("產品ID最長為4位!");
    if (form.getProductName().trim().equals("")) throw new Exception("產品名稱不能為空");
    if (Float.compare(form.getPrice(), 0) <= 0) throw new Exception("產品價格必須大於0");
  }
  public void save() throws Exception {
    try {
      String sql = "INSERT INTO t_products VALUES('" + form.getProductID() + "','"
          + form.getProductName() + "'," + form.getPrice() + ")";
      PreparedStatement pstmt = conn.prepareStatement(sql);
      pstmt.executeUpdate(); pstmt.close(); conn.close();
    } catch (Exception e) { throw new Exception(e.getMessage()); }
  }
}

4. SearchProduct 模型 (mystruts/model/SearchProduct.java) — 模糊查詢

package mystruts.model;
import java.sql.*; import java.util.*; import mystruts.actionform.*;

public class SearchProduct extends util.Struts {
  private ProductForm form;
  public SearchProduct(ProductForm form) throws Exception { super(); this.form = form; }
  public List<String[]> search() throws Exception {
    List<String[]> result = new LinkedList<>();
    String sql = "SELECT * FROM t_products WHERE product_name like '%" + form.getProductName() + "%'";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    ResultSet rs = pstmt.executeQuery();
    while(rs.next()) {
      String[] row = {rs.getString(1), rs.getString(2), rs.getString(3)};
      result.add(row);
    }
    rs.close(); conn.close(); return result;
  }
}

六、控制器層:ActionForm + Action + 配置

1. ActionForm (mystruts/actionform/ProductForm.java)

package mystruts.actionform;
import org.apache.struts.action.*;

public class ProductForm extends ActionForm {
  private String productID, productName; private float price;
  // getter/setter 省略...
  // 注意:屬性名必須與 JSP 中 html:text 的 property 一致
}

2. struts-config.xml 配置雙 ActionForm 別名

<form-beans>
  <form-bean name="saveProductForm" type="mystruts.actionform.ProductForm" />
  <form-bean name="searchProductForm" type="mystruts.actionform.ProductForm" />
</form-beans>

3. SaveProductAction (mystruts/action/SaveProductAction.java)

package mystruts.action;
import javax.servlet.http.*; import org.apache.struts.action.*;
import mystruts.actionform.*; import mystruts.model.*;

public class SaveProductAction extends Action {
  public ActionForward execute(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response) {
    ProductForm saveProductForm = (ProductForm) form;
    try {
      Product product = new Product(saveProductForm);
      product.save(); request.setAttribute("info", "保存成功!");
    } catch (Exception e) { request.setAttribute("info", e.getMessage()); }
    return mapping.findForward("save");
  }
}

4. save.jsp 顯示結果

<%@ page pageEncoding="GBK"%> ${requestScope.info}

5. struts-config.xml 配置 saveProduct 動作

<action name="saveProductForm" path="/saveProduct" scope="request" 
    type="mystruts.action.SaveProductAction">
  <forward name="save" path="/mystruts/save.jsp" />
</action>

6. SearchProductAction + search.jsp + 配置(類似,略)

search.jsp 使用 <logic:iterate> 遍歷結果列表,<logic:present> 判斷是否有數據。

七、解決 ActionForm 中文亂碼:過濾器方案

現象:中文產品名稱入庫變亂碼。根因:客戶端提交編碼與數據庫編碼不一致。

EncodingFilter (filter/EncodingFilter.java)

package filter;
import java.io.IOException; import javax.servlet.*;

public class EncodingFilter implements Filter {
  public void destroy() {}
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    request.setCharacterEncoding("GBK");  // 統一設置為數據庫編碼
    chain.doFilter(request, response);    // 必須調用,否則請求不再繼續
  }
  public void init(FilterConfig filterConfig) throws ServletException {}
}

web.xml 配置過濾器

<filter>
  <filter-name>EncodingFilter</filter-name>
  <filter-class>filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>EncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

重啟 Tomcat 後測試中文錄入,數據庫將正確存儲中文。

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