You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Spring MVC实现JSP页面数组排序前后展示功能

Alright, let's build out this feature exactly as you described—showing 10 unsorted arrays on a JSP, letting users click a button to sort them, and displaying both the original and sorted arrays on the same page. Here's a complete, working implementation with Spring MVC and JSP:

1. AlgorithmModel: Handle Array Generation & Sorting

First, let's refine the model class to hold both original and sorted arrays, plus the logic to generate random arrays and sort them:

import java.util.Arrays;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;

public class AlgorithmModel {
    private List<int[]> originalArrays;
    private List<int[]> sortedArrays;

    public AlgorithmModel() {
        // Generate 10 random arrays (each with 5 elements, values 0-99)
        this.originalArrays = generateRandomArrays(10, 5, 100);
        this.sortedArrays = new ArrayList<>();
    }

    // Helper to create random arrays
    private List<int[]> generateRandomArrays(int arrayCount, int elementCount, int maxValue) {
        List<int[]> arrays = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < arrayCount; i++) {
            int[] arr = new int[elementCount];
            for (int j = 0; j < elementCount; j++) {
                arr[j] = random.nextInt(maxValue);
            }
            arrays.add(arr);
        }
        return arrays;
    }

    // Sort all original arrays and store the results
    public void sortAllArrays() {
        sortedArrays.clear();
        for (int[] arr : originalArrays) {
            int[] sortedCopy = Arrays.copyOf(arr, arr.length);
            Arrays.sort(sortedCopy);
            sortedArrays.add(sortedCopy);
        }
    }

    // Getters & Setters
    public List<int[]> getOriginalArrays() { return originalArrays; }
    public void setOriginalArrays(List<int[]> originalArrays) { this.originalArrays = originalArrays; }
    public List<int[]> getSortedArrays() { return sortedArrays; }
    public void setSortedArrays(List<int[]> sortedArrays) { this.sortedArrays = sortedArrays; }
}
2. Spring MVC Controller: Manage Request Flow

The controller will handle initial page load (generating the arrays) and the sort action, passing the model to the JSP using @ModelAttribute:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class ArraySortController {

    // Load the initial page with 10 unsorted arrays
    @GetMapping("/home")
    public String showHomePage(Model model) {
        AlgorithmModel algorithmModel = new AlgorithmModel();
        model.addAttribute("algorithmModel", algorithmModel);
        return "home";
    }

    // Handle the sort button click and return to the same page with sorted arrays
    @PostMapping("/sortArrays")
    public String sortArrays(@ModelAttribute("algorithmModel") AlgorithmModel algorithmModel) {
        algorithmModel.sortAllArrays();
        return "home";
    }
}
3. home.jsp: Display Arrays & Handle User Action

This JSP will show the unsorted arrays, a sort button, and the sorted arrays (only after the button is clicked). We'll use JSTL for looping:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Array Sort Demo</title>
    <style>
        .array-group { margin: 20px 0; }
        .array-box {
            display: inline-block;
            margin: 10px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .number {
            display: inline-block;
            margin: 0 5px;
            padding: 4px 8px;
            background: #f5f5f5;
            border-radius: 3px;
        }
        button {
            padding: 8px 16px;
            background: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover { background: #1976D2; }
    </style>
</head>
<body>
    <h1>10 Arrays: Unsorted & Sorted</h1>

    <!-- Unsorted Arrays Section -->
    <div class="array-group">
        <h2>Unsorted Arrays</h2>
        <c:forEach var="arr" items="${algorithmModel.originalArrays}" varStatus="idx">
            <div class="array-box">
                <p>Array ${idx.index + 1}:</p>
                <c:forEach var="num" items="${arr}">
                    <span class="number">${num}</span>
                </c:forEach>
            </div>
        </c:forEach>
    </div>

    <!-- Sort Button Form -->
    <form method="post" action="/sortArrays">
        <button type="submit">Sort All Arrays</button>
    </form>

    <!-- Sorted Arrays Section (only visible after sorting) -->
    <c:if test="${not empty algorithmModel.sortedArrays}">
        <div class="array-group">
            <h2>Sorted Arrays</h2>
            <c:forEach var="arr" items="${algorithmModel.sortedArrays}" varStatus="idx">
                <div class="array-box">
                    <p>Array ${idx.index + 1} (Sorted):</p>
                    <c:forEach var="num" items="${arr}">
                        <span class="number">${num}</span>
                    </c:forEach>
                </div>
            </c:forEach>
        </div>
    </c:if>
</body>
</html>

Key Details to Note

  • Separation of Concerns: The model handles all data logic, while the controller only manages requests—this keeps code clean and maintainable.
  • Model Consistency: Using @ModelAttribute ensures the same model instance is retained across the GET and POST requests, so original arrays don't get lost when sorting.
  • Conditional Rendering: The <c:if> tag ensures the sorted arrays section only appears after the user clicks the sort button, avoiding empty UI space on initial load.
  • Readability: Basic CSS styles make the arrays easy to distinguish and read—feel free to tweak this to match your design system.

内容的提问来源于stack exchange,提问作者CoderFromKPI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:34:25