基于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:
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; } }
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"; } }
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
@ModelAttributeensures 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

