萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Java 實作 AJAX 三級聯動下拉選單:JDOM 解析 XML 資料源

資料來源:product.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE class SYSTEM "product.dtd">
<class>
  <class1 className="電腦配件" id="1">
    <class2 className="記憶體" id="1">
      <class3 id="1" className="Kingmax"/>
      <class3 id="2" className="Kingston"/>
      <class3 id="3" className="Samsung"/>
      <class3 id="4" className="Hynix"/>
      <class3 id="5" className="IBM"/>
    </class2>
    <class2 className="硬碟" id="2">
      <class3 id="6" className="Seagate"/>
      <class3 id="7" className="Western Digital"/>
      <class3 id="8" className="Samsung"/>
      <class3 id="9" className="Toshiba"/>
    </class2>
  </class1>
  
  <class1 className="食品飲料" id="2">
    <class2 className="漢堡" id="1">
      <class3 id="1" className="McDonald's"/>
      <class3 id="2" className="KFC"/>
      <class3 id="3" className="MOS Burger"/>
    </class2>
    <class2 className="飲料" id="2">
      <class3 id="4" className="Coca-Cola"/>
      <class3 id="5" className="Sprite"/>
      <class3 id="6" className="Coffee"/>
      <class3 id="7" className="Water"/>
    </class2>
  </class1>
</class>

DTD 定義 (product.dtd)

<!ELEMENT class (class1+)>
<!ELEMENT class1 (class2+)>
<!ATTLIST class1 className NMTOKEN #REQUIRED>
<!ATTLIST class1 id NMTOKEN #REQUIRED>
<!ELEMENT class2 (class3+)>
<!ATTLIST class2 className NMTOKEN #REQUIRED>
<!ATTLIST class2 id NMTOKEN #REQUIRED>
<!ELEMENT class3 EMPTY>
<!ATTLIST class3 className NMTOKEN #REQUIRED>
<!ATTLIST class3 id NMTOKEN #REQUIRED>

資料實體類別

package com.ajaxlab.ajax;

public class ProductClass {
    private String id;
    private String className;
    
    public ProductClass(String id, String className) {
        this.id = id;
        this.className = className;
    }
    // Getter/Setter 省略
    public String getId() { return id; }
    public String getClassName() { return className; }
    public void setId(String id) { this.id = id; }
    public void setClassName(String className) { this.className = className; }
}

服務層:ClassService (JDOM 解析 XML)

package com.ajaxlab.ajax;

import java.util.*;
import org.jdom.*;
import org.jdom.input.SAXBuilder;

public class ClassService {
    private Document doc;
    
    public ClassService() {
        try {
            SAXBuilder builder = new SAXBuilder();
            // 從 classpath 載入 (WEB-INF/classes 或 src/main/resources)
            this.doc = builder.build(getClass().getResource("product.xml"));
        } catch (Exception e) {
            throw new RuntimeException("載入 product.xml 失敗", e);
        }
    }
    
    // 取得所有一級分類
    public ProductClass[] getAllClass1() {
        List list = new ArrayList<>();
        for (Element el : doc.getRootElement().getChildren("class1")) {
            list.add(new ProductClass(el.getAttributeValue("id"), 
                                      el.getAttributeValue("className")));
        }
        return list.toArray(new ProductClass[0]);
    }
    
    // 依一級 ID 取得二級分類
    public ProductClass[] getAllClass2ById(String class1Id) {
        Element class1El = findClass1(class1Id);
        if (class1El == null) return new ProductClass[0];
        
        List list = new ArrayList<>();
        for (Element el : class1El.getChildren("class2")) {
            list.add(new ProductClass(el.getAttributeValue("id"),
                                      el.getAttributeValue("className")));
        }
        return list.toArray(new ProductClass[0]);
    }
    
    // 依一級、二級 ID 取得三級分類
    public ProductClass[] getAllClass3ById(String class1Id, String class2Id) {
        Element class1El = findClass1(class1Id);
        if (class1El == null) return new ProductClass[0];
        
        Element class2El = null;
        for (Element el : class1El.getChildren("class2")) {
            if (class2Id.equals(el.getAttributeValue("id"))) {
                class2El = el; break;
            }
        }
        if (class2El == null) return new ProductClass[0];
        
        List list = new ArrayList<>();
        for (Element el : class2El.getChildren("class3")) {
            list.add(new ProductClass(el.getAttributeValue("id"),
                                      el.getAttributeValue("className")));
        }
        return list.toArray(new ProductClass[0]);
    }
    
    private Element findClass1(String id) {
        for (Element el : doc.getRootElement().getChildren("class1")) {
            if (id.equals(el.getAttributeValue("id"))) return el;
        }
        return null;
    }
}

Servlet 控制器 (三個端點)

// Class1Servlet.java
@WebServlet("/ajax/class1")
public class Class1Servlet extends HttpServlet {
    private ClassService service = new ClassService();
    
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        ProductClass[] list = service.getAllClass1();
        // 使用 Jackson/Gson 序列化
        resp.getWriter().write(new ObjectMapper().writeValueAsString(list));
    }
}

// Class2Servlet.java
@WebServlet("/ajax/class2")
public class Class2Servlet extends HttpServlet {
    private ClassService service = new ClassService();
    
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String class1Id = req.getParameter("class1Id");
        resp.setContentType("application/json;charset=UTF-8");
        ProductClass[] list = service.getAllClass2ById(class1Id);
        resp.getWriter().write(new ObjectMapper().writeValueAsString(list));
    }
}

// Class3Servlet.java (類似,參數 class1Id, class2Id)

前端頁面 (index.jsp)

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>三級聯動選單</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function() {
    // 載入一級
    $.getJSON('ajax/class1', function(data) {
        var $sel1 = $('#class1').empty().append('');
        $.each(data, function(i, item) {
            $sel1.append($('').prop('disabled', !id1);
        var $sel3 = $('#class3').empty().append('').prop('disabled', true);
        
        if (!id1) return;
        $.getJSON('ajax/class2', { class1Id: id1 }, function(data) {
            $.each(data, function(i, item) {
                $sel2.append($('').prop('disabled', !id2);
        
        if (!id2) return;
        $.getJSON('ajax/class3', { class1Id: id1, class2Id: id2 }, function(data) {
            $.each(data, function(i, item) {
                $sel3.append($('

依賴管理 (Maven)

<dependencies>
    <!-- JDOM 2.x -->
    <dependency>
        <groupId>org.jdom</groupId>
        <artifactId>jdom2</artifactId>
        <version>2.0.6.1</version>
    </dependency>
    
    <!-- Jackson JSON -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>
    
    <!-- Servlet API (provided) -->
    <dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>5.0.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

現代化改進建議

  • **資料來源改用資料庫**:XML 適合靜態配置,動態分類應用資料表 + 遞迴 CTE 查詢
  • **一次性載入全樹**:前端快取完整 JSON,本地過濾,減少請求
  • **RESTful 設計**:`GET /api/categories?parentId={id}` 統一端點
  • **Spring Boot + JPA** 簡化 Servlet 開發
  • **前端組件化**:Vue/React/Angular 封裝 `` 組件
copyright © 萬盛學電腦網 all rights reserved