JSP中无法显示对象值求助:登录后展示订单异常
Hey there! Let’s work through why your JSP isn’t showing the OrderSample values—this is a common snag, and we’ll break it down step by step to get your orders displaying properly.
1. Fix Your Database Query First
Looking at your code snippet, your SQL is pulling from useradmin.users:
String SQL = "SELECT * from useradmin.users";
That’s fetching user data, not order data! You need to target your actual orders table instead (e.g., useradmin.orders). Update the query to select columns relevant to your OrderSample class, like:
String SQL = "SELECT order_id, order_date, total_amount FROM useradmin.orders";
2. Ensure OrderSample is JSP-Friendly
JSP can only access class properties via public getter methods, so double-check your class setup:
- Make sure all order fields (e.g.,
orderId,orderDate,totalAmount) match the data types of your database columns. - Add public getters for every field you want to display. For example:
public class OrderSample { private int orderId; private Date orderDate; private double totalAmount; // Mandatory getters for JSP access public int getOrderId() { return orderId; } public Date getOrderDate() { return orderDate; } public double getTotalAmount() { return totalAmount; } // Setters to populate from ResultSet public void setOrderId(int orderId) { this.orderId = orderId; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } public void setTotalAmount(double totalAmount) { this.totalAmount = totalAmount; } }
3. Correctly Populate the Order List in Your DAO
Your showOrders() method needs to properly map the ResultSet to OrderSample objects. I noticed a potential variable name conflict (you named the list and the object both order—that’s confusing!). Fix it like this:
public static ArrayList<OrderSample> showOrders() throws ClassNotFoundException, SQLException, LoginSampleException { ArrayList<OrderSample> ordersList = new ArrayList<>(); // Rename list to avoid conflict // Use try-with-resources to auto-close connections/statements (JDBC best practice) try (Connection con = Connector.connection(); Statement statement = con.createStatement(); ResultSet rs = statement.executeQuery("SELECT order_id, order_date, total_amount FROM useradmin.orders")) { while (rs.next()) { OrderSample order = new OrderSample(); order.setOrderId(rs.getInt("order_id")); // Match your database column name order.setOrderDate(rs.getDate("order_date")); order.setTotalAmount(rs.getDouble("total_amount")); ordersList.add(order); // Add the populated object to the list } } return ordersList; }
4. Pass the Order List to JSP Correctly
In your servlet/controller code (the one handling post-login logic), you need to add the order list to the request scope before forwarding to the JSP:
// After successful login ArrayList<OrderSample> orders = YourDaoClass.showOrders(); request.setAttribute("orders", orders); // Store the list in request scope request.getRequestDispatcher("/orders.jsp").forward(request, response); // Forward to JSP
⚠️ Don’t use response.sendRedirect() here—redirect creates a new request, so the orders attribute will be lost. Stick with forward() to keep the data available.
5. Display the Orders in JSP
Use JSTL (cleaner than scriptlets) to loop through the list. First, add the JSTL core taglib at the top of your JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Then render the orders in a table (or any format you prefer):
<h2>Your Orders</h2> <table border="1"> <tr> <th>Order ID</th> <th>Order Date</th> <th>Total Amount</th> </tr> <c:forEach items="${orders}" var="order"> <tr> <td>${order.orderId}</td> <!-- Uses getOrderId() behind the scenes --> <td>${order.orderDate}</td> <td>${order.totalAmount}</td> </tr> </c:forEach> </table>
If you can’t use JSTL, you can use scriptlets (though not recommended for modern JSP):
<% ArrayList<OrderSample> orders = (ArrayList<OrderSample>) request.getAttribute("orders"); if (orders != null && !orders.isEmpty()) { for (OrderSample order : orders) { %> <p>Order ID: <%= order.getOrderId() %> | Date: <%= order.getOrderDate() %></p> <% } } else { %> <p>No orders found.</p> <% } %>
6. Quick Debugging Tips
- Check if the
orderslist is empty: Add a log statement in your servlet to printorders.size()—if it’s 0, your query isn’t returning any data. - Catch exceptions: Wrap the
showOrders()call in a try-catch block to log any errors that might be preventing the list from being populated. - Enable EL expressions: If
${order.orderId}isn’t working, add<%@ page isELIgnored="false" %>to the top of your JSP (default is false in modern containers, but worth verifying).
内容的提问来源于stack exchange,提问作者jendellkenner

